method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
d2f283eb-c8a8-4730-93fe-52bbb8447080 | 9 | public int command(int cmd) {
if (cmd_pending) // If this is the second word of a command
{
int A14_15 = (cmd & 0x0003) << 14;
rw_addr = (rw_addr & 0xffff3fff) | A14_15;
// Copy rw_addr to mirror register
rw_addr = (rw_addr & 0x0000ffff) | (rw_addr << 16);
// CD{4,3,2}
int CD4_2 = (cmd & 0x0070);
rw_mode |= CD4_2;
// if CD5 == 1
rw_dma = ((cmd & 0x80) == 0x80) ? 1 : 0;
cmd_pending = false;
} else // This is the first word of a command
{
// masking away command bits CD1 CD0
int A00_13 = cmd & 0x3fff;
rw_addr = (rw_addr & 0xffffc000) | A00_13;
// Copy rw_addr to mirror register
rw_addr = (rw_addr & 0x0000ffff) | (rw_addr << 16);
// CD {1,0}
int CD0_1 = (cmd & 0xc000) >> 12;
rw_mode = CD0_1;
rw_dma = 0;
// we will expect the second half of the command next
cmd_pending = true;
return 0;
}
// if it's a dma request do it straight away
if (rw_dma != 0) {
int mode = (reg[0x17] >> 6) & 3;
int s = 0, d = 0, i = 0, len = 0;
s = dma_addr();
d = rw_addr;
len = dma_length();
switch (mode) {
case 0:
case 1:
for (i = 0; i < len; i++) {
int val;
val = dma_mem_read(s++);
val <<= 8;
val |= dma_mem_read(s++);
putWord(val);
}
break;
case 2:
// Done later on (VRAM fill I believe)
break;
case 3:
for (i = 0; i < len; i++) {
int val;
val = vram[(s++) & 0xffff];
val <<= 8;
val |= vram[(s++) & 0xffff];
putWord(val);
}
break;
}
}
return 0;
} |
f6a82a88-46e2-4e41-b049-5eb1326a48eb | 5 | final String _readComment_() throws IOException {
final Reader source = this._reader_;
final StringBuilder result = this._builder_;
result.setLength(0);
while (true) {
int symbol = source.read();
switch (symbol) {
case -1:
case '\r':
case '\n':
return result.toString();
case '\\':
symbol = this._readSymbol_(source.read());
}
result.append((char)symbol);
}
} |
008a1edd-5e3b-4ee4-91da-1b10b62ee379 | 0 | public void setMaxSpyDepth(int maxSpyDepth) {
this.miningDepth = maxSpyDepth;
} |
ba01946f-2f1a-44b1-9e63-b22ce7852519 | 6 | @Override
public boolean onCommand(CommandSender sender, Command command, String label,
String[] args) {
String lbl = label.toLowerCase();
// label must be help
if(lbl.equalsIgnoreCase("help")) {
String nested;
// get first argument (could be one of the commands)
try {
nested = args[0];
} catch(Exception e) {
// there are no arguments, so
// executed the main command
help(sender, args);
return true;
}
// remove first argument (which is a command label)
String[] newArgs;
try {
newArgs = Arrays.copyOfRange(args, 1, args.length);
} catch(Exception e) {
newArgs = new String[0];
}
//
// Find and execute nested command.
// Use the newArgs, so that it doesn't include
// the label of the nested command.
//
if(nested.equalsIgnoreCase("-list")) {
list(sender, newArgs);
}
else if(nested.equalsIgnoreCase("-reload")) {
reload(sender, newArgs);
}
else if(nested.equals("?")) {
commandHelp(sender, newArgs);
}
else {
// didn't execute a nested command
// So don't use newArgs here.
// The first argument is probably a page name!
help(sender, args);
}
return true;
}
else {
// we don't know this command label
return false;
}
} |
4c79ce15-3c1b-4f8b-9d14-3a3ce900014d | 6 | public static void call(final String mapping, final String data) throws Exception {
Iterator errors = null;
DataError dataError = null;
final Parser pzparser = DefaultParserFactory.getInstance().newFixedLengthParser(new File(mapping), new File(data));
final DataSet ds = pzparser.parse();
while (ds.next()) {
if (ds.isRecordID("header")) {
System.out.println(">>>>found header");
System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("INDICATOR"));
System.out.println("COLUMN NAME: HEADERDATA VALUE: " + ds.getString("HEADERDATA"));
System.out.println("===========================================================================");
continue;
}
if (ds.isRecordID("trailer")) {
System.out.println(">>>>found trailer");
System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("INDICATOR"));
System.out.println("COLUMN NAME: TRAILERDATA VALUE: " + ds.getString("TRAILERDATA"));
System.out.println("===========================================================================");
continue;
}
System.out.println("COLUMN NAME: FIRSTNAME VALUE: " + ds.getString("FIRSTNAME"));
System.out.println("COLUMN NAME: LASTNAME VALUE: " + ds.getString("LASTNAME"));
System.out.println("COLUMN NAME: ADDRESS VALUE: " + ds.getString("ADDRESS"));
System.out.println("COLUMN NAME: CITY VALUE: " + ds.getString("CITY"));
System.out.println("COLUMN NAME: STATE VALUE: " + ds.getString("STATE"));
System.out.println("COLUMN NAME: ZIP VALUE: " + ds.getString("ZIP"));
System.out.println("===========================================================================");
}
if (ds.getErrors() != null && !ds.getErrors().isEmpty()) {
errors = ds.getErrors().iterator();
while (errors.hasNext()) {
dataError = (DataError) errors.next();
System.out.println("ERROR: " + dataError.getErrorDesc() + " LINE NUMBER: " + dataError.getLineNo());
}
}
} |
55a375c4-3f9e-4ca3-b578-fe9db9c22dbf | 1 | public static void main(String args[]) throws InvocationTargetException, InterruptedException {
new Thread() {
public void run() {
CardFrame frame = new CardFrame();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.restartGame();
}
}.start();
// final CardFrame[] frame = new CardFrame[1];
//
//
// frame[0].startGame();
} |
efc4d7b5-8bce-49ea-944f-49ad5da0a149 | 1 | public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
} |
7f75da6a-0996-4548-b0cf-4adc1580abec | 0 | public void aboutCourse() {
System.out.println("Course name: "+ name);
System.out.println("Hours: " + hours);
} |
7e457a4a-b7df-4c9b-b904-30b01e5f7f24 | 9 | public static Stella_Object justificationArgumentBoundTo(Stella_Object argument, Justification justification) {
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(argument), Logic.SGT_LOGIC_PATTERN_VARIABLE)) {
{ PatternVariable argument000 = ((PatternVariable)(argument));
if (justification == null) {
justification = ((Justification)(Logic.$CURRENTJUSTIFICATION$.get()));
}
if (justification != null) {
{ Justification pattern = ((justification.inferenceRule == Logic.KWD_PATTERN) ? justification : justification.patternJustification);
KeyValueMap substitution = ((pattern != null) ? pattern.substitution : ((KeyValueMap)(null)));
Stella_Object value = null;
if (substitution != null) {
value = substitution.lookup(argument000);
}
if ((value == null) &&
(pattern != null)) {
pattern = pattern.patternJustification;
if (pattern != null) {
value = Logic.justificationArgumentBoundTo(argument000, pattern);
}
}
return (value);
}
}
}
}
else {
return (argument);
}
return (null);
} |
8f2cc80f-2f01-4673-985e-8bfdaf16b91c | 6 | @Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_DOWN:
{
downPressed=true;
}
break;
case KeyEvent.VK_UP:
{
upPressed=true;
}
break;
case KeyEvent.VK_RIGHT:
{
rightPressed=true;
}
break;
case KeyEvent.VK_LEFT:
{
leftPressed=true;
}
break;
case KeyEvent.VK_SPACE:
{
spacePressed=true;
}
break;
case KeyEvent.VK_P:
{
pPressed=!pPressed;
}
break;
}
} |
da463c47-fa0a-4e7d-a24e-862df50b63d5 | 3 | public ArrayList<String> getProperties(){
ArrayList<String> commands = new ArrayList<String>();
try {
r = new BufferedReader(new FileReader(config));
} catch (IOException e) {
}
String temp;
try {
while((temp = r.readLine()) != null){
commands.add(temp.substring(temp.indexOf(": ")));
}
} catch (IOException e) {
e.printStackTrace();
}
return commands;
} |
93fdd336-f277-4c8d-9d24-5bc78fcee9a2 | 2 | @Override
public boolean contains(final String column) {
final Iterator<ColumnMetaData> cmds = ParserUtils.getColumnMetaData(row.getMdkey(), metaData).iterator();
while (cmds.hasNext()) {
final ColumnMetaData cmd = cmds.next();
if (cmd.getColName().equalsIgnoreCase(column)) {
return true;
}
}
return false;
} |
29d4594c-b859-4f94-b575-4b8843109725 | 8 | Object callChunk(ScriptContext context) throws ScriptException {
try {
// Apply context
Object[] argv;
if (context != null) {
// Global bindings
Bindings bindings;
bindings = context.getBindings(ScriptContext.GLOBAL_SCOPE);
if (bindings != null) {
applyBindings(bindings);
}
// Engine bindings
bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
if (bindings != null) {
if (bindings instanceof LuaBindings
&& ((LuaBindings) bindings).getScriptEngine() == this) {
// No need to apply our own live bindings
} else {
applyBindings(bindings);
}
}
// Readers and writers
put(READER, context.getReader());
put(WRITER, context.getWriter());
put(ERROR_WRITER, context.getErrorWriter());
// Arguments
argv = (Object[]) context.getAttribute(ARGV);
} else {
argv = null;
}
// Push arguments
int argCount = argv != null ? argv.length : 0;
for (int i = 0; i < argCount; i++) {
luaState.pushJavaObject(argv[i]);
}
// Call
luaState.call(argCount, 1);
// Return
try {
return luaState.toJavaObject(1, Object.class);
} finally {
luaState.pop(1);
}
} catch (LuaException e) {
throw getScriptException(e);
}
} |
7e72f388-28b2-4b48-be9a-e5be0f85bc91 | 3 | @Override
public boolean onCommand(CommandSender sender, Command command, String label,
String[] args) {
plugin.debugMsg("PvPTime command:" + label.toString());
if(args.length > 0) {
plugin.debugMsg("Args length: " + args.length);
if(args[0].equalsIgnoreCase("reload")) {
plugin.debugMsg("Reload command");
if(sender.hasPermission("pvptime.reload")) {
plugin.debugMsg("Calling reloadPvP method.");
plugin.reloadPvP();
sender.sendMessage(ChatColor.GREEN + "Config reloaded");
return true;
} else {
sender.sendMessage(ChatColor.RED + "You do not have the permission pvptime.reload");
return true;
}
}
} else {
plugin.debugMsg("Showing main commands");
sender.sendMessage("PvPTime plugin");
sender.sendMessage(ChatColor.GREEN + "/" + label.toString() + " reload" + ChatColor.WHITE + " - Reload configs" );
return true;
}
return false;
} |
5d9f5a1a-d528-4c20-8769-5cc9d9ec241c | 4 | public static void postData(String url, JSONObject obj) throws IOException {
URL posturl = new URL(url);
HttpURLConnection con;
if (ApiProperties.get().getUrl().contains("https")) {
setupConnection();
con = (HttpsURLConnection) posturl.openConnection();
} else {
con = (HttpURLConnection) posturl.openConnection();
}
JSONObject.testValidity(obj); // testet ob valides JSON
con.setRequestMethod("POST"); // setzt PostMethode
con.setDoOutput(true); // ermöglicht Transferinput
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json"); // setzt den
// type auf
// json
con.connect();
OutputStream out = con.getOutputStream();
try {
OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(obj.toString());
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
if (con.getResponseCode() == 200) {
// UI.throwPopup("Produktname erfolgreich geändert",JOptionPane.INFORMATION_MESSAGE);
}
con.disconnect(); // Disconnect
// ApiCsvDaemon.requestProduct(); //aktualisiere Produktanzeige
} |
fb083c2d-ded4-42b7-90a4-4b6b6d2bd0d6 | 5 | @Override
public void update(Observable o, Object arg) {
if (arg instanceof SearchModel) {
this.model = (SearchModel) arg;
}
/**-50 to count for the offset of the textbox*/
show(this.textField, -50, this.textField.getHeight());
List<PictureObject> pictures = this.model.getPictures();
this.setListItems(pictures);
this.panel.removeAll();
/**Adds the search results to the popup, if result resulted in no matches, add
a no result label.*/
if (!pictures.isEmpty()) {
if (pictures.size() > 2) {
this.messageItem.setMessage(SearchConstants.SEE_MORE);
this.panel.add(this.messageItem);
this.panel.add(new JSeparator());
}
int nbrOfItems = 0;
for (JPopupListItem item : listItems) {
if (item.hasPicture()) {
this.panel.add(item);
nbrOfItems++;
}
}
setPopupSize(250, (nbrOfItems * 70));
} else {
this.messageItem.setBackground(Color.GRAY);
this.messageItem.setMessage(SearchConstants.NO_ITEMS);
this.panel.add(this.messageItem);
setPopupSize(250, 40);
}
this.panel.revalidate();
} |
ef30dbe9-691f-4180-baa0-1e2b76bfd1ba | 2 | public void setValue(int i) {
if (this.slider != null) {
this.slider.setValue(i);
}
if (this.spinner != null) {
this.spinner.setValue(new Integer(i));
}
} |
d649eab4-8707-4bc6-83e3-65ea5f746ffe | 8 | void readSessions()
{
Sheet sessions_sheet = workbook.getSheet("Sessions");
for (int si = 1; si < sessions_sheet.getRows(); si++)
{
String name = sessions_sheet.getCell(0, si).getContents();
String title = sessions_sheet.getCell(1, si).getContents();
String kind = sessions_sheet.getCell(2, si).getContents();
if (name.equals("EOF"))
break;
Session session = new Session(name, title, kind);
sessions.put(name, session);
// And now read also the papers of that session
//if (name.startsWith("Demo"))
// System.out.println("");
Sheet papers_sheet = workbook.getSheet("Papers");
for (int pi = 1, pimax = papers_sheet.getRows(); pi < pimax; pi++)
{
String currSession = papers_sheet.getCell(0, pi).getContents();
if (currSession.equals("EOF"))
break;
if (!currSession.equals(name))
continue;
int pid = Integer.parseInt(papers_sheet.getCell(1, pi).getContents());
String plink = papers_sheet.getCell(2, pi).getContents();
String ptitle = papers_sheet.getCell(3, pi).getContents();
String pabstract = papers_sheet.getCell(5, pi).getContents();
String pauthors = fixAuthorList(papers_sheet.getCell(4, pi).getContents());
ArrayList<String> photos = new ArrayList<String>();
ArrayList<String> bios = new ArrayList<String>();
for (int k = 6, kmax = papers_sheet.getColumns(); k < (kmax - 1);)
{
String photo = papers_sheet.getCell(k, pi).getContents();
String bio = papers_sheet.getCell(k + 1, pi).getContents();
if (photo.equals("") && bio.equals(""))
break;
photos.add(photo);
bios.add(bio);
k += 2;
}
Paper tmpPaper = new Paper(pid, plink, ptitle, pauthors, pabstract, photos, bios);
session.papers.add(tmpPaper);
}
}
} |
fef73d34-aca5-4b38-b258-2ccb1ab987fb | 1 | private boolean inRange(Unit unit)
{
int dist = Math.abs(unit.getX() - x) + Math.abs(unit.getY() - y);
return dist >= getMinRANGE() && dist <= getMaxRANGE();
} |
8f17f7f4-36e5-41b4-93f3-bef30ad45ee7 | 9 | public void render(Graphics g){
// if(!walkable){
// g.drawImage(wall, x, y);
// return;
// }
//g.drawImage(floor, x, y);
// if(minion != null){
// g.setColor(Color.white);
// g.fillRect(x, y, width, height);
// minion.render(g,x,y);
// //return;
// }
g.setColor(Color.transparent);
if(start){
// g.setColor(Color.green);
}
else if(path || furthest){
g.setColor(new Color(0, 255, 255,0.5f));//cyan
}
if(end){
g.setColor(Color.red);
}
if(image != null){
g.drawImage(image, x, y);
}
g.fillRect(x, y, width, height);
if(minion != null){
minion.render(g,x,y);
}
if(GameGrid.playingState == 2 && GameGrid.currentPlayer == buyingZoneOwner && buyingZone){
g.setColor(new Color(0,0,200,0.5f));
g.fillRect(x, y, width, height);
}
// if(furthest){
// g.setColor(Color.red);
// g.drawRoundRect((float)x+5, (float)y+5, (float)GameGrid.colWidth-10, (float)GameGrid.rowHeight-10,1);
// }
// g.drawString(String.valueOf(f),x+1,y-2);
// g.drawString(String.valueOf(g),x+1,y+11);
// g.drawString(String.valueOf(f),x+1,y);
} |
9fe9a455-0309-4bda-9b67-46c8c4419af4 | 2 | public static Cause findCauseById(ArrayList<Cause> causes, int id) {
for(Cause cause:causes) {
if(cause.getId()==id) {
return cause;
}
}
return new Cause();
} |
e3bfffd7-8bdc-4fdf-a422-78adef3afb19 | 2 | public ErrorPanel() {
setBackground(Color.BLACK);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(ar && !running) {
HavenApplet.this.remove(ErrorPanel.this);
startgame();
}
}
});
} |
82edb591-cad5-4d13-8b2b-6155e94c283d | 6 | public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
String[] in = br.readLine().split(" ");
String a = in[0];
String b = in[1];
int l = a.length() > b.length() ? a.length() : b.length();
int ldiff = a.length() > b.length() ? a.length() - b.length() : b
.length() - a.length();
int n1 = Integer.parseInt(a);
int n2 = Integer.parseInt(b);
if (l == a.length())
n2 = (int) (n2 * Math.pow(10, ldiff));
else
n1 = (int) (n1 * Math.pow(10, ldiff));
int remainder = 0;
String ans = "";
for (int j = l - 1; j >= 0; j--) {
int div = (int) Math.pow(10, j);
int s1 = (n1 / div) % 10;
int s2 = (n2 / div) % 10;
int sum = s1 + s2 + remainder;
ans = ans + sum % 10;
remainder = sum / 10;
}
if (remainder != 0)
ans = ans + remainder;
System.out.println(Integer.parseInt(ans));
}
} |
913d0fab-c70c-4d3b-aa46-73204e31dfe3 | 5 | @Override
public String transform(String s) {
StringBuilder sb = new StringBuilder();
if (s != null){
if (this.removeMultipleWhitespaces) {
s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
}
if (this.trimIt) {
s = s.trim();
}
Matcher m = regex.matcher(s);
while (m.find()){
if (sb.length() > 0) sb.append(" ");
sb.append(m.group());
}
}
return sb.toString();
} |
24375831-05e5-4ce4-8f51-b6df777551d3 | 5 | @Override
public void actionPerformed(ActionEvent e) {
try {
conn = DriverManager.getConnection(Utils.DB_URL);
PreparedStatement checkStat;
checkStat = conn.prepareStatement("select name from user where name = ?");
checkStat.setString(1, textField.getText());
resSet = checkStat.executeQuery();
if (!resSet.next()) {
if (Utils.checkEnteredTextForLetters(textField.getText()) && textField.getText().length()>0) {
PreparedStatement pst = conn.prepareStatement("insert into user (name, date_created, date_lastlog) values (?, ?, ?)");
pst.setString(1, textField.getText());
pst.setString(2, Utils.getTodaysDate());
pst.setString(3, Utils.getTodaysDate());
pst.execute();
user.setName(textField.getText());
openMainMenuFrame();
}
else {
statusLbl.setText("You can use only letters");
}
}
else {
statusLbl.setText("Such name is already in DB");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
finally {
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
} |
25edbe4f-e1db-47e8-9ef9-042d6a08909e | 8 | @Override
public void visitLdcInsn(final Object cst) {
Item i = cw.newConstItem(cst);
// Label currentBlock = this.currentBlock;
if (currentBlock != null) {
if (compute == FRAMES) {
currentBlock.frame.execute(Opcodes.LDC, 0, cw, i);
} else {
int size;
// computes the stack size variation
if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
size = stackSize + 2;
} else {
size = stackSize + 1;
}
// updates current and max stack sizes
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
}
// adds the instruction to the bytecode of the method
int index = i.index;
if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
code.put12(20 /* LDC2_W */, index);
} else if (index >= 256) {
code.put12(19 /* LDC_W */, index);
} else {
code.put11(Opcodes.LDC, index);
}
} |
9b99ff18-c32a-45fa-b142-22f7dea8583d | 7 | private void reactToPartChange(IWorkbenchPartReference part) {
if (!autoSync)
return;
if (!(part.getPart(false) instanceof IEditorPart))
return;
IEditorPart editorPart = (IEditorPart) part.getPart(false);
if (!getViewSite().getPage().isPartVisible(editorPart))
return;
IGraphicalFileProvider graphicalSource = (IGraphicalFileProvider) editorPart
.getAdapter(IGraphicalFileProvider.class);
if (graphicalSource != null)
selectedFile = graphicalSource.getGraphicalFile();
else
selectedFile = null;
if (selectedFile == null) {
IFile asFile = (IFile) editorPart.getAdapter(IFile.class);
if (asFile == null)
asFile = (IFile) editorPart.getEditorInput().getAdapter(IFile.class);
if (asFile == null)
return;
selectedFile = asFile;
}
requestUpdate();
} |
fc5bf2c6-c8e0-46b0-ab7c-ae08834f5ab2 | 7 | protected String getBestDistance(long d)
{
String min=null;
final long sign=(long)Math.signum(d);
d=Math.abs(d);
for(SpaceObject.Distance distance : SpaceObject.DISTANCES)
{
if((distance.dm * 2) < d)
{
double val=(double)d/(double)distance.dm;
if((val<0)||(val<100))
val=Math.round(val*100.0)/100.0;
else
val=Math.round(val);
if(val!=0.0)
{
String s=Double.toString(sign*val);
if(s.endsWith(".0"))
s=s.substring(0,s.length()-2);
s+=distance.abbr;
min = s;
break;
//if((min==null)||(min.length()>s.length())) min=s;
}
}
}
if(min==null)
return (sign*d)+"dm";
return min;
} |
20f9b511-1801-4ed8-9ea6-7b897b318e7a | 9 | public Object localise()
{
Object o = null;
try
{
Class<?> c = Class.forName(Obj_Name+"_stub");
Constructor<?> constructor = c.getConstructor(String.class, int.class);
o = constructor.newInstance(IP_adr, Port);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return o;
} |
13f75bfd-a525-4841-8ae5-00841bfca1e3 | 1 | protected void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja sair ?","",JOptionPane.OK_CANCEL_OPTION) == 0){
this.dispose();
}
}//GEN-LAST:event_btnSairActionPerformed |
2b9aebe8-0149-498c-82f4-2a575ec3a34a | 5 | public static void elevTilFil(ArrayList<Elev> minListe)
{
Formatter output = null;
try
{
//For å skrive til fil må jeg bruke klassen FileWriter
FileWriter fileWriter = new FileWriter("elever.txt", true);
output = new Formatter (fileWriter);//åpner fila elever.txt for skriving, hvis den ikke finnes, opprettes den
}
//Oppretter feilmeldinger slik at hvis programmet ikke finner filen, kommer det en feilmelding som sier det, istedenfor errorer
catch ( SecurityException securityException )
{
JOptionPane.showMessageDialog(null, "", "Du har ikke skriverettigheter til denne fila", JOptionPane.PLAIN_MESSAGE );
System.exit( 1 ); // avslutter programmet
}
catch ( FileNotFoundException fileNotFoundException )
{
JOptionPane.showMessageDialog(null, "", "Feil ved åpning av fila", JOptionPane.PLAIN_MESSAGE );
System.exit( 1 ); // avslutter programmet
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// skrive ordene til fil via system out print
for (Elev denneEleven : minListe){
System.out.println(denneEleven.getFornavn());
System.out.println(denneEleven.getEtternavn());
System.out.println(denneEleven.getnivaaElev());
output.format("%s %s %d \r\n", denneEleven.getFornavn(), denneEleven.getEtternavn(), denneEleven.getnivaaElev());
}
//Lukker filen
if ( output != null)
output.close();
} |
437bba84-6461-4a1d-b4b7-156690c7785a | 7 | private void fireCellSelectionChangeNotification() {
if ( _locked) {
return;
}
Set<CellKey> changedKeys = new HashSet<CellKey>();
for(CellKey oldKey : _oldCellKeys) {
if(!isCellKeySelected(oldKey)) {
changedKeys.add(oldKey);
}
}
for(CellKey selectedKey : _selectedCellKeys) {
if ( !_oldCellKeys.contains( selectedKey)) {
changedKeys.add( selectedKey);
}
}
if(changedKeys.size() != 0) {
for(SelectionListener listener : _listeners) {
listener.cellSelectionChanged(this, changedKeys);
}
}
_oldCellKeys = new HashSet<CellKey>(_selectedCellKeys);
} |
73a1476c-05c3-417b-bfb5-b13561bcd06b | 6 | @Override
public <T> T sudo(final SudoAction<T> c) throws LoginException, SudoExecutionException {
final Subject s = createSubject(c);
// save the current security context...
final SecurityContext secCtx = SecurityContext.getCurrent();
final LoginContext lc;
if(c.getType() != LoginType.NO_LOGIN) {
// this issues the real login and fills the subject with user roles...
lc = new LoginContext(c.getRealm(), s);
lc.login();
} else {
lc = null;
}
T result = null;
try {
// establish a new security context for the "sudo"...
final SecurityContext newCtx = AccessController.doPrivileged(
new PrivilegedAction<SecurityContext>() {
@Override
public SecurityContext run() {
return new SecurityContext(s);
}
});
SecurityContext.setCurrent(newCtx);
if(log.isLoggable(Level.FINE)) {
log.fine("[SUDO] New SecurityContext established");
}
// execute whatever you want...
try {
result = c.run();
} catch(Exception x) {
throw new SudoExecutionException(secCtx.getCallerPrincipal(), x);
}
} finally {
if(lc != null) {
try {
lc.logout();
} catch(LoginException x) {
x.printStackTrace(System.err);
}
}
// restore the original security context to not break anything...
SecurityContext.setCurrent(secCtx);
if(log.isLoggable(Level.FINE)) {
log.fine("[SUDO] Original SecurityContext restored");
}
}
return result;
} |
3f6c1a09-c1d9-4675-984b-1cf4111d0bdc | 1 | public static double meandev(double[] vals) {
double mean = mean(vals);
int size = vals.length;
double sum = 0;
for (int i = size; --i >= 0;) {
sum += Math.abs(vals[i] - mean);
}
return sum / size;
} |
d3d2430a-75a4-4110-9204-9c26190d5297 | 9 | private RenderableObject generateElipse(Scanner inFile) {
Point s = null, e = null, loc = null;
int thickness = 0;
Color c = null;
String current = inFile.next();
while (inFile.hasNext()
&& !(isCloseTag(current) && parseTag(current) == LegalTag.Object)) {
if (isOpenTag(current)) {
switch (parseTag(current)) {
case Start:
s = new Point(inFile.nextInt(), inFile.nextInt());
break;
case End:
e = new Point(inFile.nextInt(), inFile.nextInt());
break;
case Color:
c = new Color(inFile.nextInt(), inFile.nextInt(),
inFile.nextInt());
break;
case Location:
loc = new Point(inFile.nextInt(), inFile.nextInt());
break;
case Thickness:
thickness = inFile.nextInt();
break;
default:
break;
}
}
current = inFile.next();
}
Ellipse ell = new Ellipse(s, e, thickness, c);
ell.setLocation(loc);
return ell;
} |
b424dd27-e97f-41fc-be7d-b9a2455c0c20 | 9 | public void set(String in, int field,Scanner s) {
switch(field){
case 1:
number = in;
break;
case 2:
name = in;
break;
case 3:
address = in;
break;
case 4:
city = in;
break;
case 5:
while (in.length() != 2){
System.out.println("Please enter a valid state: ");
in = s.next();
}
state = in;
break;
case 6:
while (in.length() != 5 || !isInt(in)){
System.out.println("Please enter a valid id: ");
in = s.next();
}
zip = in;
break;
default:
System.out.println("Invalid number");
}
} |
9b10d470-7987-4674-9be8-0ce2e6a91632 | 6 | private void miNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miNewActionPerformed
if (story.isSomethingChanged()) {
// Show save confirm window
int n = JOptionPane.showConfirmDialog(null,
"You made one or several changes to the current story.\n"
+ "Do you want to save this before starting a new one?\n",
"Save?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (n == JOptionPane.YES_OPTION) {
// saveStory returns false if the user cancels
if (!saveStory()) {
return;
}
} else if (n == JOptionPane.CANCEL_OPTION) {
return;
}
}
String storyName = JOptionPane.showInputDialog("Name of the new story", defaultStoryName);
if (storyName != null) {
if (!storyName.equals("")) {
story = new Story(storyName, panelRoutes, this);
map.Clear(story);
panelRoutes.createStoryTree(story);
panelRoutes.refreshList(story.getRoutes());
this.setTitle(storyName + " - iStory designer " + Application.getVersion());
return;
}
}
miNewActionPerformed(evt);
}//GEN-LAST:event_miNewActionPerformed |
60a9f12b-528c-40e9-8cc5-d5e2741c3621 | 6 | public Contenu getContenu(Agent joueur){
if (wumpus==true && !joueur.getWumpusTue()){return Contenu.WUMPUS;}
else if (pit==true){return Contenu.TROU;}
else if (gold==true){return Contenu.OR;}
else if (joueur.getPosition().getXReel()==this.coord.getX()&&joueur.getPosition().getYReel()==this.coord.getY())/*agent==true*/{return Contenu.AGENT;}
return Contenu.VIDE;
} |
b4787211-a0ff-4e12-89c7-8f1483278e9b | 4 | private static byte[] appendByteArrays( byte[] arrayOne, byte[] arrayTwo,
int length )
{
byte[] newArray;
if( arrayOne == null && arrayTwo == null )
{
// no data, just return
return null;
}
else if( arrayOne == null )
{
// create the new array, same length as arrayTwo:
newArray = new byte[ length ];
// fill the new array with the contents of arrayTwo:
System.arraycopy( arrayTwo, 0, newArray, 0, length );
arrayTwo = null;
}
else if( arrayTwo == null )
{
// create the new array, same length as arrayOne:
newArray = new byte[ arrayOne.length ];
// fill the new array with the contents of arrayOne:
System.arraycopy( arrayOne, 0, newArray, 0, arrayOne.length );
arrayOne = null;
}
else
{
// create the new array large enough to hold both arrays:
newArray = new byte[ arrayOne.length + length ];
System.arraycopy( arrayOne, 0, newArray, 0, arrayOne.length );
// fill the new array with the contents of both arrays:
System.arraycopy( arrayTwo, 0, newArray, arrayOne.length,
length );
arrayOne = null;
arrayTwo = null;
}
return newArray;
} |
757b8c16-6953-46fa-8f33-e767f4c62d39 | 0 | public void setWidth(int width)
{
marker[markers-1].setWidth(width);
} |
6cbb5bd4-e742-41d2-8328-c9218f023bcf | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
a775ec79-91ad-4b57-a641-54008866c7fc | 3 | private void setTextUnderIcons() {
//if showTextunderButtons is true, the text will
//not be shown
if(!showText)
{
startRecordButton.setText(null);
stopRecordButton.setText(null);
hearMusicButton.setText(null);
scheduleButton.setText(null);
infoButton.setText(null);
deleteButton.setText(null);
editButton.setText(null);
addButton.setText(null);
openMusicFolderButton.setText(null);
configButton.setText(null);
exitButton.setText(null);
browseGenreButton.setText(null);
}
else
{
//set the translated text under icons
try
{
startRecordButton.setText(trans.getString("mainWin.startRecordButton"));
stopRecordButton.setText(trans.getString("mainWin.stopRecordButton"));
scheduleButton.setText(trans.getString("mainWin.scheduleButton"));
deleteButton.setText(trans.getString("mainWin.deleteButton"));
editButton.setText(trans.getString("mainWin.editButton"));
addButton.setText(trans.getString("mainWin.addButton"));
hearMusicButton.setText(trans.getString("mainWin.hearMusicButton"));
openMusicFolderButton.setText(trans.getString("mainWin.openMusicFolderButton"));
exitButton.setText(trans.getString("mainWin.exitButton"));
configButton.setText(trans.getString("mainWin.configButton"));
infoButton.setText(trans.getString("mainWin.infoButton"));
browseGenreButton.setText(trans.getString("mainWin.browseGenreButton"));
}
catch (MissingResourceException e)
{
SRSOutput.getInstance().logE("Could not find an translation (Text under Icons)");
}
//set an smaller font
startRecordButton.setFont(textUnderIconsFont);
stopRecordButton.setFont(textUnderIconsFont);
scheduleButton.setFont(textUnderIconsFont);
deleteButton.setFont(textUnderIconsFont);
editButton.setFont(textUnderIconsFont);
addButton.setFont(textUnderIconsFont);
hearMusicButton.setFont(textUnderIconsFont);
openMusicFolderButton.setFont(textUnderIconsFont);
exitButton.setFont(textUnderIconsFont);
configButton.setFont(textUnderIconsFont);
infoButton.setFont(textUnderIconsFont);
browseGenreButton.setFont(textUnderIconsFont);
}
//if there is a use of the intern player, update the text, too
if(useInternalPlayer & audioPanel != null)
{
audioPanel.setTextUnderIcons(showText);
}
} |
5a3a6faa-bd15-4ebe-9a2c-bea3505ca594 | 8 | public boolean equals(Object obj){
if(obj==null){
return false;
}
if(getClass()!=obj.getClass()){
return false;
}
BloomFilter<E> o2 = (BloomFilter<E>) obj;
final BloomFilter<E> other=o2;
if(this.expectedNumOfElements!=other.expectedNumOfElements){
return false;
}
if(this.k!=other.k){
return false;
}
if(this.bitSetSize!=other.bitSetSize){
return false;
}
if(this.bitSet!=other.bitSet&&(this.bitSet==null)||!this.bitSet.equals(other.bitSet)){
return false;
}
return true;
} |
b8d37781-397d-4402-beb0-82f9404844d1 | 2 | private static String getFilenameWithoutPathOrExtension( String filename )
{
String newFilename;
// Remove the ".java" extension from the filename, if it exists
int extensionIndex = filename.lastIndexOf( ".java" );
if ( extensionIndex == -1 )
{
newFilename = filename;
}
else
{
newFilename = filename.substring( 0, extensionIndex );
}
// Remove the path, after unifying path separators
newFilename = StringUtils.replace( newFilename, "\\", "/" );
int pathIndex = newFilename.lastIndexOf( "/" );
if ( pathIndex == -1 )
{
return newFilename;
}
else
{
return newFilename.substring( pathIndex + 1 );
}
} |
b1acc145-1b25-4461-aa88-0917a4603d53 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DatasetType)) {
return false;
}
DatasetType other = (DatasetType) object;
if ((this.key == null && other.key != null) || (this.key != null && !this.key.equals(other.key))) {
return false;
}
return true;
} |
f4b9a489-7e00-4482-bedc-cc3296ec163e | 7 | public static void main(String[] args) {
int BITS_PER_LINE = 16;
if (args.length == 1) {
BITS_PER_LINE = Integer.parseInt(args[0]);
}
int count;
for (count = 0; !BinaryStdIn.isEmpty(); count++) {
if (BITS_PER_LINE == 0) { BinaryStdIn.readBoolean(); continue; }
else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println();
if (BinaryStdIn.readBoolean()) StdOut.print(1);
else StdOut.print(0);
}
if (BITS_PER_LINE != 0) StdOut.println();
StdOut.println(count + " bits");
} |
377cfba8-c6c6-4dc0-af92-a6e0a65c4534 | 3 | public static void releaseAll() {
if (isDiagnosticsEnabled()) {
logDiagnostic("Releasing factory for all classloaders.");
}
synchronized (factories) {
Enumeration elements = factories.elements();
while (elements.hasMoreElements()) {
LogFactory element = (LogFactory) elements.nextElement();
element.release();
}
factories.clear();
if (nullClassLoaderFactory != null) {
nullClassLoaderFactory.release();
nullClassLoaderFactory = null;
}
}
} |
fb8ca2db-2761-47ba-9485-87b517181197 | 2 | private static void initGussian(Composite inComposite, int heightHint) {
final Composite toolbar = new Composite(inComposite, SWT.BORDER);
final Composite gaussion = new Composite(inComposite, SWT.BORDER);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.grabExcessHorizontalSpace = true;
gridData.heightHint = heightHint;
gaussion.setLayoutData(gridData);
gaussion.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event event) {
ImageUtils.paintImage(event.gc, gaussionImage, gaussionImageHistogram);
}
});
createToolbarGridData(toolbar);
toolbar.setLayout(new GridLayout(100, false));
Label label = new Label(toolbar, SWT.NONE);
label.setText("Mean: ");
final Text mt = new Text(toolbar, SWT.BORDER);
mt.setText("0");
label = new Label(toolbar, SWT.NONE);
label.setText("Variance: ");
final Text vt = new Text(toolbar, SWT.BORDER);
vt.setText("100");
Button button = new Button(toolbar, SWT.PUSH);
button.setText("Add Gaussian Noise");
button.setBounds(0, 0, 100, 30);
button.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
button.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
double mean = 2;
try {
mean = Double.parseDouble(mt.getText());
} catch (Exception e) {
e.printStackTrace();
}
double variance = 25;
try {
variance = Double.parseDouble(vt.getText());
} catch (Exception e) {
e.printStackTrace();
}
gaussionImage = addGaussionNoise(originalImage, mean, variance);
gaussionImageHistogram = ImageUtils.analyzeHistogram(gaussionImage.getImageData());
ImageUtils.paintImage(new GC(gaussion), gaussionImage, gaussionImageHistogram);
}
});
} |
8a88d101-2393-423e-8b3d-5ad6e2153fde | 1 | public void defocus(Configuration configuration) {
setNormal(configuration);
Configuration parent = configuration;
parent.setFocused(false);
while (parent.getParent() != null) {
parent = parent.getParent();
parent.setFocused(false);
}
} |
a00c9d67-d3ad-4528-a215-0dda209911e2 | 3 | @Override
public String process(String content) throws ProcessorException {
// TODO Auto-generated method stub
pipeline = new SimpleAuthenticationPipeline();
context = new AuthorizeContext();
pipeline.setBasic(new AuthEntryValve());
pipeline.addValve(new FlushValve());
pipeline.addValve(new EncodeValve());
pipeline.addValve(new AuthorizeResponseValve());
pipeline.addValve(new AuthorizeValve());
pipeline.addValve(new ValidationValve());
pipeline.addValve(new DecoderValve());
pipeline.setContext(context);
try {
pipeline.invoke(context.getRequest(), context.getResponse(), null);
} catch (ValveException e) {
User user = context.getRequest().getCurrentUser();
String response = "";
if (user == null || user.getUserName() == null) {
response = ExceptionWrapper.toJSON(503, "Internal Error");
} else {
response = ExceptionWrapper.toJSON(user, e.getCode(),
e.getMessage());
}
return response;
}
return context.getResponse().getResponse();
} |
5802e89e-fe7a-4185-9779-c1252c660157 | 8 | private void btnSalvarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalvarMouseClicked
dao = new ProdutoDAO();
produto = new Produto();
produto.setNome(txtNome.getText());
produto.setValorcompra(Double.parseDouble(txtValorCompra.getText()));
produto.setValorvenda(Double.parseDouble(txtValorVenda.getText()));
produto.setEstoque(Integer.parseInt(txtEstoque.getText()));
String comp = txtNome.getText();
int est = Integer.parseInt(txtEstoque.getText());
double vc = Double.parseDouble(txtValorCompra.getText());
double vv = Double.parseDouble(txtValorVenda.getText());
if (comp.length()>3 && comp.length()<250){
if (est > 0){
if (vc>0 && vv>0){
try{
if (JOptionPane.showConfirmDialog(rootPane, "Deseja salvar todos os dados?") == 0){
if (dao.Salvar(produto)) {
JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!");
} else {
JOptionPane.showMessageDialog(rootPane, "Falha ao salvar! Consulte o administrador do sistema!");
}
}
}catch (Exception ex) {
JOptionPane.showMessageDialog(rootPane, "Nao foi possivel salvar!");
}
}else{
JOptionPane.showMessageDialog(rootPane, "Valor invalido!");
}
}else{
JOptionPane.showMessageDialog(rootPane, "Estoque Invalido!");
}
}else{
JOptionPane.showMessageDialog(rootPane, "Nome invalido");
}
}//GEN-LAST:event_btnSalvarMouseClicked |
fd624bd5-ef8e-4c13-b297-27b00efa2a3e | 8 | public int[] search (ASEvaluation ASEval, Instances data)
throws Exception {
m_best = null;
m_generationReports = new StringBuffer();
if (!(ASEval instanceof SubsetEvaluator)) {
throw new Exception(ASEval.getClass().getName()
+ " is not a "
+ "Subset evaluator!");
}
if (ASEval instanceof UnsupervisedSubsetEvaluator) {
m_hasClass = false;
}
else {
m_hasClass = true;
m_classIndex = data.classIndex();
}
SubsetEvaluator ASEvaluator = (SubsetEvaluator)ASEval;
m_numAttribs = data.numAttributes();
m_startRange.setUpper(m_numAttribs-1);
if (!(getStartSet().equals(""))) {
m_starting = m_startRange.getSelection();
}
// initial random population
m_lookupTable = new Hashtable(m_lookupTableSize);
m_random = new Random(m_seed);
m_population = new GABitSet [m_popSize];
// set up random initial population
initPopulation();
evaluatePopulation(ASEvaluator);
populationStatistics();
scalePopulation();
checkBest();
m_generationReports.append(populationReport(0));
boolean converged;
for (int i=1;i<=m_maxGenerations;i++) {
generation();
evaluatePopulation(ASEvaluator);
populationStatistics();
scalePopulation();
// find the best pop member and check for convergence
converged = checkBest();
if ((i == m_maxGenerations) ||
((i % m_reportFrequency) == 0) ||
(converged == true)) {
m_generationReports.append(populationReport(i));
if (converged == true) {
break;
}
}
}
return attributeList(m_best.getChromosome());
} |
3bf658a0-2cfb-4814-b08f-e23928bf005d | 3 | private void disconnect(Channel channel, String message) {
if (channel.isActive() && this.currentProtocol == Protocol.PLAY || this.currentProtocol == Protocol.LOGIN) {
ByteBuf header = Unpooled.buffer();
ByteBuf data = Unpooled.buffer();
ByteBufUtils.writeVarInt(data, 0x0);
JSONObject json = new JSONObject();
json.put("text", message);
ByteBufUtils.writeUTF(data, json.toJSONString());
ByteBufUtils.writeVarInt(header, data.readableBytes());
sendPacket(channel, Unpooled.wrappedBuffer(header, data));
} else {
channel.close();
}
} |
88622c91-a5b5-48f5-8f07-221788239e7b | 8 | double evaluateInstanceLeaveOneOut(Instance instance, double [] instA)
throws Exception {
DecisionTableHashKey thekey;
double [] tempDist;
double [] normDist;
thekey = new DecisionTableHashKey(instA);
if (m_classIsNominal) {
// if this one is not in the table
if ((tempDist = (double [])m_entries.get(thekey)) == null) {
throw new Error("This should never happen!");
} else {
normDist = new double [tempDist.length];
System.arraycopy(tempDist,0,normDist,0,tempDist.length);
normDist[(int)instance.classValue()] -= instance.weight();
// update the table
// first check to see if the class counts are all zero now
boolean ok = false;
for (int i=0;i<normDist.length;i++) {
if (Utils.gr(normDist[i],1.0)) {
ok = true;
break;
}
}
// downdate the class prior counts
m_classPriorCounts[(int)instance.classValue()] -=
instance.weight();
double [] classPriors = m_classPriorCounts.clone();
Utils.normalize(classPriors);
if (!ok) { // majority class
normDist = classPriors;
}
m_classPriorCounts[(int)instance.classValue()] +=
instance.weight();
//if (ok) {
Utils.normalize(normDist);
if (m_evaluationMeasure == EVAL_AUC) {
m_evaluation.evaluateModelOnceAndRecordPrediction(normDist, instance);
} else {
m_evaluation.evaluateModelOnce(normDist, instance);
}
return Utils.maxIndex(normDist);
/*} else {
normDist = new double [normDist.length];
normDist[(int)m_majority] = 1.0;
if (m_evaluationMeasure == EVAL_AUC) {
m_evaluation.evaluateModelOnceAndRecordPrediction(normDist, instance);
} else {
m_evaluation.evaluateModelOnce(normDist, instance);
}
return m_majority;
} */
}
// return Utils.maxIndex(tempDist);
} else {
// see if this one is already in the table
if ((tempDist = (double[])m_entries.get(thekey)) != null) {
normDist = new double [tempDist.length];
System.arraycopy(tempDist,0,normDist,0,tempDist.length);
normDist[0] -= (instance.classValue() * instance.weight());
normDist[1] -= instance.weight();
if (Utils.eq(normDist[1],0.0)) {
double [] temp = new double[1];
temp[0] = m_majority;
m_evaluation.evaluateModelOnce(temp, instance);
return m_majority;
} else {
double [] temp = new double[1];
temp[0] = normDist[0] / normDist[1];
m_evaluation.evaluateModelOnce(temp, instance);
return temp[0];
}
} else {
throw new Error("This should never happen!");
}
}
// shouldn't get here
// return 0.0;
} |
105f2b24-9795-4865-a47d-60566f7b8c22 | 4 | public static ProjectileType parseType(String type) {
if(type.matches("PROJECTILE")) {
return PROJECTILE;
} else if(type.matches("HOMING")) {
return HOMING;
} else if(type.matches("AREA")) {
return AREA;
} else if(type.matches("ENCHANT")) {
return ENCHANT;
}
return null;
} |
6259def2-624e-440f-bc10-8ed9838a3ecb | 5 | public void addChar(char ch) {
ch = normalize(ch);
char lastchar = grams_.charAt(grams_.length() - 1);
if (lastchar == ' ') {
grams_ = new StringBuffer(" ");
capitalword_ = false;
if (ch==' ') return;
} else if (grams_.length() >= N_GRAM) {
grams_.deleteCharAt(0);
}
grams_.append(ch);
if (Character.isUpperCase(ch)){
if (Character.isUpperCase(lastchar)) capitalword_ = true;
} else {
capitalword_ = false;
}
} |
be6952d2-b5af-453a-bfbd-9a02af0791ca | 7 | public static void main(String[] args) {
Random randomGenerator = new Random();
int dice;
int[] result = new int[6];
for(int i = 0; i < 1000; i++) {
dice = randomGenerator.nextInt(6) + 1;
switch(dice) {
case 1:
result[dice - 1]++;
break;
case 2:
result[dice - 1]++;
break;
case 3:
result[dice - 1]++;
break;
case 4:
result[dice - 1]++;
break;
case 5:
result[dice - 1]++;
break;
case 6:
result[dice - 1]++;
break;
}
}
System.out.println(
"Eins:\t" + result[0] + "\nZwei:\t" + result[1] + "\nDrei:\t" + result[2] + "\nVier:\t" + result[3] +
"\nFuenf:\t" + result[4] + "\nSechs:\t" + result[5]);
} |
4b0183ee-eeef-4a00-a7e4-35b0195057e0 | 5 | protected void createContents()
{
shell = new Shell();
shell.setSize(640, 480);
shell.setText(title);
Label lblTaskTitle = new Label(shell, SWT.NONE);
lblTaskTitle.setBounds(10, 13, 64, 15);
lblTaskTitle.setText("Task Title *");
txtTitle = new Text(shell, SWT.BORDER);
txtTitle.setTextLimit(Task.MAX_TITLE_LENGTH);
txtTitle.setBounds(90, 10, 524, 21);
btnSave = new Button(shell, SWT.NONE);
btnSave.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent arg0)
{
if(txtTitle.getText().isEmpty() || txtTitle.getText().length() == 0 || txtTitle.getText() == null)
{
MyMessageBox error = new MyMessageBox(shell, "Task has no Title", "Please enter a Title for the task.", "OK");
error.open();
}
else if (!Validate.isPositiveDouble(txtTimeSpent.getText())
|| !Validate.isPositiveDouble(txtTimeEstimate.getText()))
{
MyMessageBox error = new MyMessageBox(shell, "Error", "Please enter a non-negative numeric value for Time Estimate and Time Spent.", "OK");
error.open();
}
else
{
save();
}
}
});
btnSave.setBounds(539, 407, 75, 25);
btnSave.setText("Save");
btnCancel = new Button(shell, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent arg0)
{
shell.close();
}
});
btnCancel.setBounds(458, 407, 75, 25);
btnCancel.setText("Cancel");
Label titleSeparator = new Label(shell, SWT.SEPARATOR
| SWT.HORIZONTAL);
titleSeparator.setBounds(10, 34, 604, 2);
Label lblCreatedBy = new Label(shell, SWT.NONE);
lblCreatedBy.setBounds(10, 45, 64, 15);
lblCreatedBy.setText("Created By");
cboxAssignedTo = new Combo(shell, SWT.READ_ONLY);
cboxAssignedTo.setBounds(90, 71, 195, 23);
Label lblAssignedTo = new Label(shell, SWT.NONE);
lblAssignedTo.setText("Assigned To");
lblAssignedTo.setBounds(10, 74, 75, 15);
Label lblCreatedDate = new Label(shell, SWT.NONE);
lblCreatedDate.setBounds(312, 45, 75, 15);
lblCreatedDate.setText("Created Date");
lblCreatedByField = new Label(shell, SWT.BORDER
| SWT.SHADOW_IN);
lblCreatedByField.setBounds(90, 45, 195, 15);
lblCreatedByField.setText(AccessUsers.getLoggedInUser().getUserName());
lblCreatedDateField = new Label(shell, SWT.BORDER
| SWT.SHADOW_IN);
lblCreatedDateField.setBounds(458, 45, 156, 15);
lblCreatedDateField.setText(FormatDate.formatDate(Calendar.getInstance()));
Label lblDueDate = new Label(shell, SWT.NONE);
lblDueDate.setText("Due Date");
lblDueDate.setBounds(312, 74, 75, 15);
dueDate = new DateTime(shell, SWT.BORDER);
dueDate.setBounds(458, 66, 156, 24);
cboxStatus = new Combo(shell, SWT.READ_ONLY);
cboxStatus.setBounds(90, 100, 195, 23);
Label lblStatus = new Label(shell, SWT.NONE);
lblStatus.setText("Status");
lblStatus.setBounds(10, 103, 75, 15);
Label lblAmountOfWork = new Label(shell, SWT.NONE);
lblAmountOfWork.setBounds(312, 132, 140, 15);
lblAmountOfWork.setText("Current Time Spent");
txtTimeSpent = new Text(shell, SWT.BORDER);
txtTimeSpent.setText("0");
txtTimeSpent.setBounds(457, 129, 157, 21);
cboxPriority = new Combo(shell, SWT.READ_ONLY);
cboxPriority.setBounds(90, 129, 195, 23);
Label lblPriority = new Label(shell, SWT.NONE);
lblPriority.setBounds(10, 132, 55, 15);
lblPriority.setText("Priority");
Label lblTimeEstimate = new Label(shell, SWT.NONE);
lblTimeEstimate.setBounds(312, 103, 87, 15);
lblTimeEstimate.setText("Time Estimate");
txtTimeEstimate = new Text(shell, SWT.BORDER);
txtTimeEstimate.setText("0");
txtTimeEstimate.setBounds(458, 100, 156, 21);
txtDescription = new Text(shell, SWT.MULTI | SWT.BORDER
| SWT.WRAP | SWT.V_SCROLL);
txtDescription.setTextLimit(Task.MAX_TEXT_LENGTH);
txtDescription.setBounds(10, 183, 275, 210);
txtComments = new Text(shell, SWT.MULTI | SWT.BORDER
| SWT.WRAP | SWT.V_SCROLL);
txtComments.setTextLimit(Task.MAX_TEXT_LENGTH);
txtComments.setBounds(312, 183, 302, 210);
Label lblDescription = new Label(shell, SWT.NONE);
lblDescription.setBounds(10, 162, 64, 15);
lblDescription.setText("Description");
Label lblComments = new Label(shell, SWT.NONE);
lblComments.setBounds(312, 162, 75, 15);
lblComments.setText("Comments");
Label bottomSeparator = new Label(shell, SWT.SEPARATOR
| SWT.HORIZONTAL);
bottomSeparator.setBounds(10, 399, 604, 2);
setTextFieldValues();
} |
c0956baf-d129-49b7-8eee-a91cc253104a | 0 | @Basic
@Column(name = "pass")
public String getPass() {
return pass;
} |
c496ef1d-bad9-4152-b52b-16f4fbfd8149 | 5 | public static boolean canConnect(Connector<?> c1, Connector<?> c2) {
if( c1 == null || c2 == null ) return true;
return c1.getPayloadClass() == c2.getPayloadClass() &&
c1.getConnectorType().canConnectTo(c2.getConnectorType());
} |
c363ac15-4f1a-4d4d-9abd-421595a54998 | 0 | @RequestMapping(value = "/image_src/{imageId}", method = RequestMethod.GET)
public void imageSrc(@PathVariable String imageId, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Image image = imageService.getImageBytesAndContentTypeById(imageId);
response.setContentType(image.getContentType());
ServletOutputStream out = response.getOutputStream();
out.write(image.getBytes());
out.flush();
} |
54461960-f068-44a6-8230-78c080d2bca1 | 1 | public static String mkString(Collection<String> c, final String sep) {
if (c.isEmpty()) {
return "";
}
String head = c.iterator().next();
Collection<String> tail = new ArrayList<String>(c);
tail.remove(head);
return reduce(tail, new Function2<String, String>() {
@Override
public String apply(String a, String b) {
return a + sep + b;
}
}, head);
} |
453e6449-dbdb-48dc-927c-e8a19a95a650 | 3 | public FireBall(TileMap tileMap, boolean right) {
super(tileMap);
facingRight = right;
moveSpeed = 3.8;
if(right) dx = moveSpeed;
else dx = -moveSpeed;
sWidth = sHeight = 30;
width = height = 14;
BufferedImage spritesheet = new Texture("/textures/fireball.gif").getImage();
sprites = new BufferedImage[4];
for(int i = 0; i < sprites.length; i++)
sprites[i] = spritesheet.getSubimage(i * sWidth, 0, sWidth, sHeight);
hitSprites = new BufferedImage[3];
for(int i = 0; i < hitSprites.length; i++)
hitSprites[i] = spritesheet.getSubimage(i * sWidth, sHeight, sWidth, sHeight);
animation = new Animation();
animation.setFrames(sprites);
animation.setDelay(70);
} |
9053fce6-9039-48af-ba37-65b17aca4015 | 6 | private int getCollidingBouncyBlockBounciness() {
if(!collidable)
return -1;
if(!crouch || !crouchable){
if(game.getCurrentLevel().getBlockAtPixel(x,y-(height/4)) instanceof BlockBouncy){
BlockBouncy bb = (BlockBouncy) game.getCurrentLevel().getBlockAtPixel(x,y-(height/4));
return bb.getBounciness();
}
} else if(crouchable){
if(game.getCurrentLevel().getBlockAtPixel(x,y-(height/4)+(int)((tempHeight/crouchAmount)*1.5)) instanceof BlockBouncy){
BlockBouncy bb = (BlockBouncy) game.getCurrentLevel().getBlockAtPixel(x,y-(height/4)+(int)((tempHeight/crouchAmount)*1.5));
return bb.getBounciness();
}
}
return -1;
} |
a261c5fc-1e18-4669-a12f-18f890f04d43 | 2 | public int[][] DFA(String pattern) {
int patternLength = pattern.length();
int[][] dfa = new int[alphabet][patternLength];
dfa[pattern.charAt(0)][0] = 1;
for (int X = 0, j = 1; j < patternLength; j++) {
for (int character = 0; character < alphabet; character++)
dfa[character][j] = dfa[character][X];
dfa[pattern.charAt(j)][j] = j+1;
X = dfa[pattern.charAt(j)][X];
}
return dfa;
} |
a9b6253f-cea1-4a2d-83e7-92c884d6f44f | 5 | @Override
public void update(float delta) {
handleInput();
Vector2D[] vertices = this.bounds.getVertices();
Rectangle r = (Rectangle)this.bounds;
if(vertices[0].x<limits.getPosition().x){
this.setPosition(new Vector2D(limits.getPosition().x + r.getWidth()/2,this.getPosition().y));
//this.velocity.thisBounceNormal(new Vector2D(1,0));
this.velocity.thisScale(0.1f);
}
if(vertices[1].x>limits.getPosition().x+limits.getWidth()){
this.setPosition(new Vector2D(limits.getPosition().x +limits.getWidth()-r.getWidth()/2,this.getPosition().y));
//this.velocity.thisBounceNormal(new Vector2D(-1,0));
this.velocity.thisScale(0.1f);
}
if(vertices[0].y <limits.getPosition().y){
this.setPosition(new Vector2D(this.getPosition().x,limits.getPosition().y + r.getHeight()/2));
//this.velocity.thisBounceNormal(new Vector2D(0,1));
this.velocity.thisScale(0.1f);
}
if(vertices[2].y>limits.getPosition().y+limits.getHeight()){
this.setPosition(new Vector2D(this.getPosition().x,limits.getPosition().y+limits.getHeight() - r.getHeight()/2));
//this.velocity.thisBounceNormal(new Vector2D(0,-1));
this.velocity.thisScale(0.1f);
}
this.setPosition(this.getPosition().add(velocity.scale(delta)));
this.velocity.thisScale((float)Math.pow(0.7f, delta));
if(velocity.length()>maxSpeed){
velocity = velocity.normalize().scale(maxSpeed);
}
} |
7d947835-bddb-4905-ade4-acaceb62a50d | 3 | public static boolean vectorCompare(double[] v, double[] w) {
if (v.length != w.length)
return false;
for (int i = 0; i < v.length; i++)
if (Math.abs(v[i] - w[i]) > eps)
return false;
return true;
} |
489dab0c-0f1f-432c-9b56-bbdf8809f2ab | 1 | public void showField() {
for (int i = 0; i < fieldSize; i++) {
showLine(i);
System.out.println();
}
} |
4c45c5d3-7ed5-4c2f-83fa-a196ffae0d3f | 6 | public static boolean checkSumUsingSort(int[] A, int x) { // Time complexity - O(nlog(n))
if(A == null || A.length < 2)
return false;
int i, j, flag = 0;
int left = 0, right = A.length - 1;
java.util.Arrays.sort(A);
while(left < right) {
i = A[left];
j = A[right];
if(i + j == x) {
System.out.println("Pair " + i + ", " + j + " has sum " + x);
flag = 1;
left++;
right--;
}
else if(i + j < x)
left++;
else
right--;
}
if(flag == 1)
return true;
return false;
} |
c8ca53e1-f037-4387-8884-958710ee8100 | 3 | @Override
public int addRecipe(Recipe r) {
int recipeId = getNextIdAndIncrement();
try(Connection connection = DriverManager.getConnection(connectionString)){
PreparedStatement statement = connection.prepareStatement("insert into recipe (id, name, numPersons, cookingTime, restingTime, prepTime, steps) values (?,?,?,?,?,?,?)");
statement.setInt(1, recipeId);
statement.setString(2, r.getName());
statement.setInt(3, r.getNumPersons());
statement.setLong(4, r.getCookingTime().getStandardMinutes());
statement.setLong(5, r.getRestTime().getStandardMinutes());
statement.setLong(6, r.getPrepTime().getStandardMinutes());
String steps = "";
for(String step : r.getSteps()){
steps = steps + step + "\n";
}
statement.setString(7, steps);
statement.executeUpdate();
for(Ingredient i : r.getIngredients().keySet()){
statement = connection.prepareStatement("insert into recipeIngredients (idRecipe, idIngredient, unit, numberOfUnits, fuzzy) values (?,?,?,?,?)");
statement.setInt(1, recipeId);
statement.setInt(2, i.getIngredientId());
Quantity q = r.getIngredients().get(i);
statement.setString(3, q.getUnit());
statement.setBigDecimal(4, q.getNumberOfUnits());
statement.setBoolean(5, q.isFuzzy());
statement.executeUpdate();
}
connection.close();
return recipeId;
}
catch(SQLException ex){
ex.printStackTrace();
return -1;
}
} |
ab351407-5b07-42ba-a86e-cd35393094ed | 7 | public static OggAudioStreamHeaders create(OggPacket firstPacket) {
if (firstPacket.isBeginningOfStream() &&
firstPacket.getData() != null &&
firstPacket.getData().length > 10) {
int sid = firstPacket.getSid();
if (VorbisPacketFactory.isVorbisStream(firstPacket)) {
return new OggAudioStreamHeaders(sid,
OggStreamIdentifier.OGG_VORBIS,
(VorbisInfo)VorbisPacketFactory.create(firstPacket));
}
if (SpeexPacketFactory.isSpeexStream(firstPacket)) {
return new OggAudioStreamHeaders(sid,
OggStreamIdentifier.SPEEX_AUDIO,
(SpeexInfo)SpeexPacketFactory.create(firstPacket));
}
if (OpusPacketFactory.isOpusStream(firstPacket)) {
return new OggAudioStreamHeaders(sid,
OggStreamIdentifier.OPUS_AUDIO,
(OpusInfo)OpusPacketFactory.create(firstPacket));
}
if (FlacFirstOggPacket.isFlacStream(firstPacket)) {
FlacFirstOggPacket flac = new FlacFirstOggPacket(firstPacket);
return new OggAudioStreamHeaders(sid,
OggStreamIdentifier.OGG_FLAC,
flac.getInfo());
}
throw new IllegalArgumentException("Unsupported stream of type " + OggStreamIdentifier.identifyType(firstPacket));
} else {
throw new IllegalArgumentException("May only be called for the first packet in a stream, with data");
}
} |
4aa22512-9f77-437d-82eb-f54c7a5e8302 | 9 | private boolean r_mark_suffix_with_optional_y_consonant() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
// (, line 153
// or, line 155
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 154
// (, line 154
// test, line 154
v_2 = limit - cursor;
// literal, line 154
if (!(eq_s_b(1, "y")))
{
break lab1;
}
cursor = limit - v_2;
// next, line 154
if (cursor <= limit_backward)
{
break lab1;
}
cursor--;
// (, line 154
// test, line 154
v_3 = limit - cursor;
if (!(in_grouping_b(g_vowel, 97, 305)))
{
break lab1;
}
cursor = limit - v_3;
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 156
// (, line 156
// not, line 156
{
v_4 = limit - cursor;
lab2: do {
// (, line 156
// test, line 156
v_5 = limit - cursor;
// literal, line 156
if (!(eq_s_b(1, "y")))
{
break lab2;
}
cursor = limit - v_5;
return false;
} while (false);
cursor = limit - v_4;
}
// test, line 156
v_6 = limit - cursor;
// (, line 156
// next, line 156
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// (, line 156
// test, line 156
v_7 = limit - cursor;
if (!(in_grouping_b(g_vowel, 97, 305)))
{
return false;
}
cursor = limit - v_7;
cursor = limit - v_6;
} while (false);
return true;
} |
a376142f-b374-4615-ab2e-68756ab36da0 | 3 | public boolean leapYear(int year){
boolean test = false;
if(year%4 != 0){
test = false;
}
else{
if(year%400 == 0){
test=true;
}
else{
if(year%100 == 0){
test=false;
}
else{
test=true;
}
}
}
return test;
} |
384e403a-25d5-4a3b-9e96-a303e5ce844d | 4 | private static GridResource createGridResource(String name, double baud_rate,
double delay, int MTU, int totalPE, int totalMachine,
int rating, String sched_alg)
{
// Here are the steps needed to create a Grid resource:
// 1. We need to create an object of MachineList to store one or more
// Machines
MachineList mList = new MachineList();
for (int i = 0; i < totalMachine; i++)
{
// 2. Create one Machine with its id and list of PEs or CPUs
mList.add(new Machine(i, totalPE, rating));
}
// 3. Create a ResourceCharacteristics object that stores the
// properties of a Grid resource: architecture, OS, list of
// Machines, allocation policy: time- or space-shared, time zone
// and its price (G$/PE time unit).
String arch = "Sun Ultra"; // system architecture
String os = "Solaris"; // operating system
double time_zone = 9.0; // time zone this resource located
double cost = 3.0; // the cost of using this resource
int scheduling_alg = 0; // space_shared or time_shared
if (sched_alg.equals("SPACE"))
{
scheduling_alg = ResourceCharacteristics.SPACE_SHARED;
}
else if (sched_alg.equals("TIME"))
{
scheduling_alg = ResourceCharacteristics.TIME_SHARED;
}
ResourceCharacteristics resConfig = new ResourceCharacteristics(arch, os,
mList, scheduling_alg, time_zone, cost);
// 4. Finally, we need to create a GridResource object.
long seed = 11L * 13 * 17 * 19 * 23 + 1;
double peakLoad = 0.0; // the resource load during peak hour
double offPeakLoad = 0.0; // the resource load during off-peak hr
double holidayLoad = 0.0; // the resource load during holiday
// incorporates weekends so the grid resource is on 7 days a week
LinkedList Weekends = new LinkedList();
Weekends.add(new Integer(Calendar.SATURDAY));
Weekends.add(new Integer(Calendar.SUNDAY));
// incorporates holidays. However, no holidays are set in this example
LinkedList Holidays = new LinkedList();
GridResource gridRes = null;
try
{
// creates a GridResource with a link
gridRes = new GridResource(name,
new SimpleLink(name + "_link", baud_rate, delay, MTU),
seed, resConfig, peakLoad, offPeakLoad, holidayLoad, Weekends, Holidays);
}
catch (Exception e)
{
e.printStackTrace();
}
return gridRes;
} |
d66570f9-24f2-4072-892a-a66b85cc0df9 | 1 | public void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
} |
59aab5f1-fdb8-4fa8-b15d-66d929493ecd | 0 | public void setEvent(Event event) {
this.event = event;
event.getParticipants().add(this);
} |
b629ab2f-98ac-44df-91d3-9be924a4488b | 4 | public void mouseUp(MouseEvent e, int x, int y) {
if ( isCheckerFigure(draggedFigure) ) {
Location from = Convert.xy2Location(originalPt.x, originalPt.y);
Location to = Convert.xy2Location(e.getX(), e.getY());
draggedFigure.moveBy(originalPt.x - e.getX(), originalPt.y - e.getY());
if( isLocation(to) && isLocation(from) ){
if(game.move(from, to)){
Point pTo = Convert.locationAndCount2xy(to, (game.getCount(to) - 1));
Point pFrom = Convert.locationAndCount2xy(from, game.getCount(from));
draggedFigure.moveBy(pTo.x - pFrom.x, pTo.y - pFrom.y);
}
}
}
fChild.mouseUp(e, x, y);
fChild = cachedNullTool;
draggedFigure = null;
} |
7b4ec3c3-1615-4a5f-9535-797071f59dd1 | 2 | public void setIndex(int i) {
if (i < 0) {
idx = 0;
} else if (i > len) {
idx = len;
} else {
idx = i;
}
} |
0838373d-6a3b-4a17-ad92-054d17c81902 | 3 | @EventHandler
public void onTeleport(PlayerTeleportEvent e) {
Player p = e.getPlayer();
World world = e.getFrom().getWorld();
if (utils.isValidWorld(p)) {
ConfigurationSection section = plugin.getConfig().getConfigurationSection(world.getName());
if (section == null)
return;
int newHunger = p.getFoodLevel() - section.getInt("teleport-penalty");
p.setFoodLevel(newHunger < 0 ? 0 : newHunger);
}
} |
d5f347ab-09fb-433e-ac2f-efec11d2d6a6 | 2 | @Override
public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) {
return request.getFieldValue( "WebSocket-Origin" ).equals( response.getFieldValue( "Origin" ) ) && basicAccept( response ) ? HandshakeState.MATCHED : HandshakeState.NOT_MATCHED;
} |
71e61f56-222c-44dc-afd9-eb580c738229 | 5 | @Test public void ImageTest() {
// Test to make sure that it can't load a none existent image
boolean exceptionThrown = false;
Image img;
try {
img = new Image("not_an_image");
} catch (Exception e) {
exceptionThrown = true;
}
Assert.assertTrue(exceptionThrown);
// Test to make sure that fire.jpg can be loaded
exceptionThrown = false;
try {
img = new Image("fire.jpg");
} catch (Exception e) {
exceptionThrown = true;
}
Assert.assertFalse(exceptionThrown);
// Test to make sure that cartoon_castle.jpg can be loaded
exceptionThrown = false;
try {
img = new Image("cartoon_castle.jpg");
} catch (Exception e) {
exceptionThrown = true;
}
// Test to make sure slingShot.jpg can be loaded
exceptionThrown = false;
try {
img = new Image("slingShot.jpg");
} catch (Exception e) {
exceptionThrown = true;
}
Assert.assertFalse(exceptionThrown);
// Test to make sure that sunshine.jpg can be loaded
exceptionThrown = false;
try {
img = new Image("sunshine.jpg");
} catch (Exception e) {
exceptionThrown = true;
}
Assert.assertFalse(exceptionThrown);
} |
613e25ca-09b4-497d-843a-b20ea8704c16 | 0 | public void setActiveActivies(ActiveActivities activeActivies) {
this.activeActivity = activeActivies;
} |
91636346-fe19-41c1-a343-a10e4d18e547 | 4 | public boolean peutPrendreEnCharge(Navire n) {
//vérifie le type
if(prendEnCharge(n.getTypeMachandise())) {
//Vérifie qu'il y a assez de place pour le prendre
if(_naviresAQuai.isEmpty()) {
if(_longueurMetre>=n.getLongueurMetre()) {
return true;
}
} else {
// Collections.sort(_naviresAQuai);
// int indice = 0;
int longueurTotale = 0;
for(Navire navireAQuai:_naviresAQuai) {
longueurTotale+=navireAQuai.getLongueurMetre();
// int position = navireAQuai.getPositionAQuai();
// if(position-indice>=n.getTempsPriseEnCharge()) {
// return true;
// }
// indice = position+navireAQuai.getTempsPriseEnCharge();
}
return longueurTotale<=_longueurMetre;
}
}
return false;
} |
6db7371e-86a6-4832-9aa0-b8e9f0daca1b | 3 | @Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e))
{
if (sfap.hand == 1)
{
NewMapDialog dialog = new NewMapDialog();
int result = JOptionPane.showConfirmDialog(null, dialog, "Select", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
sfap.objSize = new Dimension(dialog.getHSelectorValue(), dialog.getWSelectorValue());
}
}
}
} |
bea7ced4-3f23-494c-b36a-4568cba6dbaf | 3 | private Tree parameterListPro(){
Symbol identifier = null;
Tree identifiers = null;
if((identifier = accept(Symbol.Id.IDENTIFIER_NAME))!=null){
if(accept(Symbol.Id.PUNCTUATORS,",")!=null){
if((identifiers = parameterListPro())!=null){
return new ParameterList(identifier, identifiers);
}
return null;
}
return new ParameterList(identifier);
}
return null;
} |
d9146d34-bd60-4987-a7d8-c6fe0b4045ea | 4 | private Boolean checkData(String name,String surname,String pass,String pass2){
/*
* elegxei an einai swsta ta dedomena pou dothikan kai epistrefei to katalilo mnm an den einai
*/
if(name.length()<3){
JOptionPane.showMessageDialog(null, "Dwste egkiro onoma!");
return false;
}else if(surname.length()<3){
JOptionPane.showMessageDialog(null, "Dwste egkiro epwnimo!");
return false;
}else if(pass.length()<5){
JOptionPane.showMessageDialog(null, "O kwdikos prepei na einai megaliteros apo 4 xaraktires!");
return false;
}else if(!pass.equals(pass2)){
JOptionPane.showMessageDialog(null, "Oi kwdikoi den teriazoun!");
return false;
}else{
return true;
}
} |
3f7e196e-259c-4de6-ad2e-1597060a87f2 | 0 | @Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
calculateEnabledState((OutlinerDocument) e.getDocument());
} |
c959518b-c16c-4209-8124-4587df33c9e6 | 9 | public RebalanceInfo(JsonObject obj) throws RestApiException {
JsonElement e = obj.get("status");
if (e == null || e.isJsonPrimitive() == false) {
throw new RestApiException("Expected status string", obj);
}
String sStatus = e.getAsString();
if (sStatus.equals("none")) {
completed = true;
} else if (sStatus.equals("running")) {
for (Entry<String,JsonElement> ent : obj.entrySet()) {
if (ent.getKey().equals("status")) {
continue;
}
JsonObject progressObj;
if (ent.getValue().isJsonObject() == false) {
throw new RestApiException("Expected object", ent.getValue());
}
progressObj = ent.getValue().getAsJsonObject();
JsonElement progressNum = progressObj.get("progress");
if (progressNum.isJsonPrimitive() == false ||
progressNum.getAsJsonPrimitive().isNumber() == false) {
throw new RestApiException("Expected 'progress' to be number",
progressNum);
}
details.put(ent.getKey(), progressNum.getAsNumber().floatValue() * 100);
}
}
} |
442d955b-a9ee-49b1-9403-e4fe129db59a | 3 | @Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
User user = (User) session.get("User");
Campaign camp;
// camp=(Campaign) session.get("campa");
// Long camp1id=camp.getCampaignId();
lc = (Long) Long.parseLong(campaid);
System.out.println("campaignlong id is" + getLc());
camp=(Campaign)myDao.getDbsession().get(Campaign.class, lc);
camp.setCampaignId(Long.parseLong(campaid));
camp.setCampaignName(campaignname);
camp.setStartDate(startdate);
camp.setEndDate(enddate);
camp.setDialyBudget(dailybdgt);
camp.setDeliveryMethod(deliverytype);
// camp.setPromoType(promotype);
camp.setNote(note);
getMyDao().getDbsession().update(camp);
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 Updated");
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";
}
} |
e36d811e-9327-4a31-b8a1-4cb4fa7437b2 | 9 | @Override
public void valueUpdated(Setting s, Value v) {
try {
if (s.getName().equals(_RefVisibible)) {
if (switch_ != null)
switch_.setReferenceVisible(v.getBoolean());
} else if (s.getName().equals(_Reference)) {
if (switch_ != null)
switch_.setReference(v.getBoolean());
} else if (s.getName().equals(_Value)) {
if (switch_ != null) {
if (switch_.isSelected() != v.getBoolean()) {
switch_.setSelected(v.getBoolean());
if (getMode().isExec()) {
output_.trigger(v);
}
}
}
}
super.valueUpdated(s, v);
} catch (Exception e) {
e.printStackTrace();
}
} |
8a1b9866-c4ba-4344-919e-d26c57855c8c | 4 | public com.novativa.www.ws.streamsterapi.Bar[] getBars(java.lang.String instrument, java.lang.String period, java.lang.String options) throws java.rmi.RemoteException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[10]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("GetBars");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("", "GetBars"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {instrument, period, options});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.novativa.www.ws.streamsterapi.Bar[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.novativa.www.ws.streamsterapi.Bar[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.novativa.www.ws.streamsterapi.Bar[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
throw axisFaultException;
}
} |
a9d10ed0-1f76-40e9-ac6d-804bef769016 | 7 | private int nthPrime(int n) {
while (primes.size() <= n) {
int candidate;
if (primes.size() == 0) {
candidate = 1;
} else {
candidate = primes.get(primes.size() - 1);
}
boolean isPrime;
do {
candidate = candidate + 1;
isPrime = true;
int i = 0;
while (isPrime && i < primes.size()) {
int prime = primes.get(i);
if (prime > (int)Math.sqrt(candidate)) {
break;
}
if (candidate % prime == 0) {
isPrime = false;
}
++i;
}
} while (!isPrime);
primes.add(candidate);
}
return primes.get(n);
} |
6cb78832-d7ff-41a8-bbee-932bc1798a6d | 6 | public static int[] getPixels(BufferedImage img,
int x, int y, int w, int h, int[] pixels) {
if (w == 0 || h == 0) {
return new int[0];
}
if (pixels == null) {
pixels = new int[w * h];
} else if (pixels.length < w * h) {
throw new IllegalArgumentException("pixels array must have a length" +
" >= w*h");
}
int imageType = img.getType();
if (imageType == BufferedImage.TYPE_INT_ARGB ||
imageType == BufferedImage.TYPE_INT_RGB) {
Raster raster = img.getRaster();
return (int[]) raster.getDataElements(x, y, w, h, pixels);
}
// Unmanages the image
return img.getRGB(x, y, w, h, pixels, 0, w);
} |
dd3218ec-1408-44cd-829a-2b8805d281c9 | 8 | void animationMode() throws ScriptException {
float startDelay = 1, endDelay = 1;
if (statementLength < 3 || statementLength > 5)
badArgumentCount();
int animationMode = 0;
switch (statement[2].tok) {
case Token.loop:
++animationMode;
break;
case Token.identifier:
String cmd = (String) statement[2].value;
if (cmd.equalsIgnoreCase("once")) {
startDelay = endDelay = 0;
break;
}
if (cmd.equalsIgnoreCase("palindrome")) {
animationMode = 2;
break;
}
unrecognizedSubcommand(cmd);
}
if (statementLength >= 4) {
startDelay = endDelay = floatParameter(3);
if (statementLength == 5)
endDelay = floatParameter(4);
}
viewer.setAnimationReplayMode(animationMode, startDelay, endDelay);
} |
ff2012d7-0f93-4f7e-8c4f-28f424da5992 | 6 | public static boolean considerOffense(Card card, Duelist duelist) {
int c;
if (MonsterCard.class.isInstance(card)) {
MonsterCard mc = MonsterCard.class.cast(card);
MonsterCard mc2 = null;
for (c = 0; c < duelist.opponent.field.monsterzones.length; c++) {
if (duelist.opponent.field.monsterzones[c].isOpen()) {
continue;
} else {
mc2 = MonsterCard.class.cast(duelist.opponent.field.monsterzones[c].card);
if (mc2.position == MonsterPosition.ATTACK) {
if (mc.atk > mc2.atk)
return true;
} else {
if (mc.atk > mc2.def)
return true;
}
}
}
}
return false;
} |
c8374149-1503-4d0f-b2c6-a3072971975f | 6 | @Override
protected Boolean doInBackground() {
if (debugVerbose) { Logger.logInfo(debugTag + "Loading MC assets..."); }
setStatus("Downloading jars...");
if (!loadJarURLs()) {
return false;
}
if (!binDir.exists()) {
if (debugVerbose) { Logger.logWarn(debugTag + "binDir not found, creating: " + binDir.getPath()); }
binDir.mkdirs();
}
Logger.logInfo("Downloading Jars");
if (!downloadJars()) {
Logger.logError("Download Failed");
return false;
}
setStatus("Extracting files...");
Logger.logInfo("Extracting Files");
if (!extractNatives()) {
Logger.logError("Extraction Failed");
return false;
}
return true;
} |
a417daf5-065a-4db3-8f49-44c7dbd1cfed | 0 | private void swapElementsByIndex(int firstIndex, int secondIndex) {
E firstKey = heap.get(firstIndex);
E secondKey = heap.get(secondIndex);
heap.set(firstIndex, secondKey);
heap.set(secondIndex, firstKey);
} |
d95e0eb6-7aa9-4889-9964-224271062be5 | 9 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CategoryDataset)) {
return false;
}
CategoryDataset that = (CategoryDataset) obj;
if (!getRowKeys().equals(that.getRowKeys())) {
return false;
}
if (!getColumnKeys().equals(that.getColumnKeys())) {
return false;
}
int rowCount = getRowCount();
int colCount = getColumnCount();
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < colCount; c++) {
Number v1 = getValue(r, c);
Number v2 = that.getValue(r, c);
if (v1 == null) {
if (v2 != null) {
return false;
}
}
else if (!v1.equals(v2)) {
return false;
}
}
}
return true;
} |
190cb520-1c38-4d70-b0c6-3f476b856537 | 0 | public void setAnt(Ant ant) {
// Update Ant on this cell
this.ant = ant;
} |
615aef40-ff88-452a-9144-f96f3f0473a9 | 5 | public static void puzzleReady() {
boolean isWin = true;
for (SlidingPuzzlePiece thisPiece
: SlidingPuzzlePiece.getPuzzlePiece()) {
if (thisPiece.getField().getFieldCoordX() != thisPiece.getRootX()) {
isWin = false;
}
if (thisPiece.getField().getFieldCoordY() == thisPiece.getRootY()) {
isWin = false;
}
}
if (isWin) {
System.out.println("Game won.");
try {
SlidingPuzzleHighscore.readXML();
new SlidingPuzzleHighscore(userName, String.valueOf(moveCount));
SlidingPuzzleHighscore.writeXML();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.