method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
266acef3-aef0-4f01-ab19-cd4510390d88 | 5 | public Vector<Shift> getShiftsBetween(Calendar start, Calendar end)
{
if(shifts.size() > 0)
{
Vector<Shift> result = new Vector<Shift>();
int x = 0;
//Get to the first date within the specified date
while(x < shifts.size() && shifts.get(x).getStartTime().before(start)) x++;
//Start adding dates while within the range until we exit the range
while(x < shifts.size() && shifts.get(x).getStartTime().before(end))
{
result.add(shifts.get(x));
x++;
}
return result;
}
return null;
} |
b5895982-e793-46db-912e-899e10dba3ed | 9 | public static int findMaxSum(int matrix[][]) {
int rows = matrix.length;
int max = 0;
if (rows > 0) {
int cols = matrix[0].length;
if (cols > 0) {
// i, j will determine the size of the submatrix
for (int i = rows; i > 0; i--) {
for (int j = cols; j > 0; j--) {
// x, y will determine the top left of the submatrix
for (int x = 0; x <= rows - i; x++) {
for (int y = 0; y <= cols - j; y++) {
int sum = 0;
for (int a = x; a < x + i; a++) {
for (int b = y; b < y + j; b++) {
sum += matrix[a][b];
}
}
max = sum > max ? sum : max;
}
}
}
}
}
}
return max;
} |
686bab48-2b1d-4003-987b-a7cc30f13dd4 | 1 | @Override
public void handleResult() throws InvalidRpcDataException {
String result = getStringResult();
if (result.equalsIgnoreCase(STATUS_STRING_OK)) {
EventBusFactory.getDefault().fire(new RemoteDownloadsChangedEvent());
} else {
// TODO: handle
Arietta.handleException(new Exception("Got unexpected result"));
}
} |
03abcd9d-e101-46eb-a2bc-6a53b41552e3 | 1 | private void cancelCheckTask() {
if (checkTask != null)
checkTask.cancel();
} |
3114489d-edae-4446-8526-230ebebf6da6 | 2 | public void readSource(String input)
{
StringBuilder sb = new StringBuilder();
try
{
FileInputStream fis = new FileInputStream(input);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
dis.close();
}
catch (Exception e) {
System.out.println("No file found");
//System.err.println("Error: " + e.getMessage());
}
this.graph = sb;
} |
09d709a3-a31b-448a-9617-83c699d9d078 | 4 | public void setPotionEffects(ArrayList<PotionEffect> effects) {
if(effects.isEmpty()) {
this.compound.remove("ActiveEffects");
if(this.autosave) savePlayerData();
return;
}
NBTTagList activeEffects = new NBTTagList();
for(PotionEffect pe : effects) {
NBTTagCompound eCompound = new NBTTagCompound();
eCompound.setByte("Amplifier", (byte)(pe.getAmplifier()));
eCompound.setByte("Id", (byte)(pe.getType().getId()));
eCompound.setInt("Duration", (int)(pe.getDuration()));
activeEffects.add(eCompound);
}
this.compound.set("ActiveEffects", activeEffects);
if(this.autosave) savePlayerData();
} |
d6be8376-54ad-48b8-b829-fc9976fc54b3 | 5 | public static void main(String[] args) {
try {
BufferedReader in = null;
if (args.length > 0) {
in = new BufferedReader(new FileReader(args[0]));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> input = new ArrayList<String>();
String inp = in.readLine();
while (inp != null) {
input.add(inp);
inp = in.readLine();
}
StringTokenizer st;
StringTokenizer st2;
PriorityQueue<Edge> edges = new PriorityQueue<Edge>();
Vertex[] noder = new Vertex[input.size()];
for (int i = 0; i < input.size(); i++) {
st = new StringTokenizer((String) input.get(i));
Vertex vertex = new Vertex(i);
noder[i] = vertex;
while (st.hasMoreTokens()) {
st2 = new StringTokenizer(st.nextToken(), ":");
int to = Integer.parseInt(st2.nextToken());
int weight = Integer.parseInt(st2.nextToken());
edges.add(new Edge (i,to,weight));
}
}
System.out.println(mst(edges, noder));
} catch (Exception e) {
e.printStackTrace();
}
} |
6626d2a1-93eb-43a6-a28d-1c5b7b7172e5 | 5 | public void testInternal(int effort) throws IOException, InterruptedException {
File tmpDirectory = TestUtil.directoriesToFile("tmp", "SnzOutputStreamTest");
tmpDirectory.mkdirs();
for(File org : testdataDirectory.listFiles()) {
if(org.isFile()) {
System.out.println("compressing " + org.getName());
SnzOutputStream sos = new SnzOutputStream(new FileOutputStream(new File(tmpDirectory, org.getName() + ".snz")));
sos.setCompressionEffort(effort);
FileInputStream fis = new FileInputStream(org);
TestUtil.pipe(fis, sos);
fis.close();
sos.close();
}
}
ProcessBuilder pb = new ProcessBuilder(snzipExecutable, "-d", "*");
pb.directory(tmpDirectory);
pb.redirectErrorStream(true);
Process p = pb.start();
TestUtil.pipe(p.getInputStream(), System.out);
int snzReturnCode = p.waitFor();
if(snzReturnCode != 0) {
Assert.fail("snzip exited with return code " + snzReturnCode);
}
for(File org : testdataDirectory.listFiles()) {
if(org.isFile()) {
System.out.println("comparing " + org.getName());
byte[] originalData = TestUtil.readFully(org);
byte[] processedData = TestUtil.readFully(new File(tmpDirectory, org.getName()));
Assert.assertArrayEquals(originalData, processedData);
}
}
} |
c7b6191c-7603-4c0f-af09-fa174d61b9d7 | 5 | protected void showSelectedCountry(SessionRequestContent request) {
String selected = request.getParameter(JSP_SELECT_ID);
Country currCountry = null;
if (selected != null) {
Integer idCountry = Integer.decode(selected);
if (idCountry != null) {
List<Country> list = (List<Country>) request.getSessionAttribute(JSP_COUNTRY_LIST);
Iterator<Country> it = list.iterator();
while (it.hasNext() && currCountry == null) {
Country country = it.next();
if (Objects.equals(country.getIdCountry(), idCountry)) {
currCountry = country;
request.setAttribute(JSP_CURR_ID_COUNTRY, idCountry);
}
}
}
}
request.setSessionAttribute(JSP_CURRENT_COUNTRY, currCountry);
} |
b7f9f5dd-9f6d-45a3-8419-13ec4e01385d | 7 | public boolean isBranch() {
switch (this) {
case BEQ:
case BGE:
case BGT:
case BLE:
case BLT:
case BNE:
case BSR:
return true;
}
return false;
} |
f7aefc54-b573-42bf-a5f1-7f0bc189df4f | 7 | public void actionPerformed(ActionEvent e)
{
String actioncommand = e.getActionCommand();
if (actioncommand.equals("New Class")) {
ClassRoom newclassroom = new ClassRoom();
String name = (String) JOptionPane.showInputDialog(main, "Enter the new Classroom's name");
if (name != null) {
File file = new File(this.classesDirectory + System.getProperty("file.separator") + name);
if (!file.exists()) {
file.mkdir();
} else {
JOptionPane.showMessageDialog(main, "Classroom already exists! Please use another name");
}
newclassroom.save(file);
main.changeClass(newclassroom);
this.refresh();
}
} else if (actioncommand.equals("Delete Class")) {
/*
* Hack to have an empty entry by default.
*/
if (!this.classSelection.getSelectedItem().toString().equals("-")) {
File deletedClass = new File(((ClassRoom) this.classSelection.getSelectedItem()).getSaveDirectory());
for (File file : deletedClass.listFiles()) {
file.delete();
}
deletedClass.delete();
}
this.refresh();
} else if (actioncommand.equals("Save Class")) {
this.save();
}
} |
bfeeeddb-f3a2-4794-81e5-31fed5b996ef | 1 | public int getMinRange(String minMatch, String maxMatch, int dataContentLength) {
if (minMatch != null) {
return Integer.parseInt(minMatch);
} else {
return dataContentLength - (Integer.parseInt(maxMatch));
}
} |
7604930d-40bf-4eb8-b47b-76d0b5ceb8f8 | 1 | @Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Movie.class.isAssignableFrom(type);
} |
3c104b04-ff75-4b03-b2a2-0408fa21793c | 7 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChannelTeds that = (ChannelTeds) o;
if (!dataConverter.equals(that.dataConverter)) return false;
if (!dataStructure.equals(that.dataStructure)) return false;
if (!identification.equals(that.identification)) return false;
if (!transducer.equals(that.transducer)) return false;
return true;
} |
c2ad3cf6-a132-4f60-8a34-a961ee71c157 | 7 | private RebalanceIndex getRebalanceIndex(Node n) {
//Index der angibt wie die Rebalancierung durchzuführen ist
RebalanceIndex rebalanceIndex = null;
//Balancierungsindex des Root Knotens berechnen
int balanceIndex = getBalanceIndex(n);
if (balanceIndex >= -1 && balanceIndex <= 1) {
//Wenn der balance index zwischen -1 und 1 liegt ist der Subtree der am Knoten hängt ausbalanciert
rebalanceIndex = RebalanceIndex.BALANCED;
} else {
if (balanceIndex == 2) {
//BalanceIndex liegt bei 2. Der Baum benötigt eine Rechtsrotation oder Linksrechtsrotation um ausbalanciert zu werden
if (getBalanceIndex(n.getLft()) == 1 || getBalanceIndex(n.getLft()) == 0) {
//Baum benötigt eine Rechtsrotation zum ausbalancieren
rebalanceIndex = RebalanceIndex.RIGHTRIGHT;
} else {
//Baum benötigt eine Links-Rechtsrotation zum ausbalancieren
rebalanceIndex = RebalanceIndex.LEFTRIGHT;
}
} else {
//BalanceIndex liegt bei -2. Der Baum benötigt eine Linksrotation oder Rechtslinksrotation um ausbalanciert zu werden
if (getBalanceIndex(n.getRgt()) == -1 || getBalanceIndex(n.getRgt()) == 0) {
//Baum benötigt eine Linksrotation
rebalanceIndex = RebalanceIndex.LEFTLEFT;
} else {
//Baum benötigt eine Rechtslinksrotation
rebalanceIndex = RebalanceIndex.RIGHTLEFT;
}
}
}
//Rebalancierungsindex zurückgeben
return rebalanceIndex;
} |
d119a731-8b72-40c5-9da8-6e42e994943d | 6 | public static String buildParameterStr(Collection<Parameter> parameters) {
StringBuilder sb = new StringBuilder("");
if (parameters != null && parameters.size() > 0) {
for (Parameter param : parameters) {
sb.append(param.getKey());
sb.append("=");
try {
sb.append(param.getValue() != null
&& !param.getValue().isEmpty() ? URLEncoder.encode(
param.getValue(), "UTF-8") : "");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
sb.append("");
}
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
} |
0190c0ed-b80a-4fc0-b1f3-981beccd7150 | 7 | @Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (o instanceof UserDTO) {
final UserDTO other = (UserDTO) o;
return Objects.equal(getId(), other.getId())
&& Objects.equal(getUsername(), other.getUsername())
&& Objects.equal(getPassword(), other.getPassword())
&& Objects.equal(getEnabled(), other.getEnabled())
&& Objects.equal(getRoleId(), other.getRoleId());
}
return false;
} |
211f66b9-267c-472c-aa20-188f71c88722 | 5 | public StreamedContent downloadArquivo() {
try {
logger.info(pasta+" Inciando o download......");
FacesContext context = FacesContext.getCurrentInstance();
InputStream stream;
if (verificaTamanho(arquivo.getTmDownload()) == true) {
if ((Data.getHora() < 1200 || Data.getHora() > 1400 && Data.getHora() < 1800)) {
context.addMessage(null, new FacesMessage("Informação", "Arquivo maior que 80 MB realize o download entre"
+ " 12:00 e 14:00 e depois das 18:00....."+Data.getHora()));
} else {
stream = new FileInputStream(arquivo.getDownload());
file = new DefaultStreamedContent(stream, "Imagem/jpg", arquivo.getArquivo());
}
} else {
stream = new FileInputStream(arquivo.getDownload());
file = new DefaultStreamedContent(stream, "Imagem/jpg", arquivo.getArquivo());
}
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
} |
f9c51a79-6729-4e69-bbe8-96d8edfb941c | 1 | @EventHandler
public void scaleHunger(FoodLevelChangeEvent e) {
ScaleHungerEvent event = new ScaleHungerEvent(plugin, (Player) e.getEntity());
plugin.getServer().getPluginManager().callEvent(event);
// Cancel hunger if the custom event is cancelled.
if (event.isCancelled()) {
e.setCancelled(true);
return;
}
} |
b1b55009-1ed4-4961-b1ba-f12787c4934d | 7 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
if (player.hasPermission("GameAPI.join")) {
if (okayNoArgCommands.contains(event.getMessage().toLowerCase()))
return;
if (okayArgCommands.contains(event.getMessage().toLowerCase().split(" ")[0]) || event.getMessage().toLowerCase().startsWith("/ctt kit"))
return;
for (Entry<Integer, Game> en : GameAPIMain.getRunners().entrySet()) {
if (!(en.getValue() instanceof CTTGame))
continue;
CTTGame g = (CTTGame) en.getValue();
if (g.getPlayers().contains(player.getName())) {
player.sendMessage(ChatColor.RED + "You can't use commands while in game! To leave, use /l");
event.setCancelled(true);
CTT.debug(player.getName() + " has been denied the use of the command: " + event.getMessage());
return;
}
}
}
} |
8d327533-ef31-47bd-8d69-fc81cf979242 | 8 | @Override
public String expectedDelivery(String item, String client, String market) {
logger.info("Calculating expected time to delivery. " +
"item " + item + ", client " + client + ", market " + market);
// business rule: delivery date depends of the client first letter
char key = client.toUpperCase().charAt(0);
if ((key >= 'A') && (key <= 'D'))
return "3";
else if ((key >= 'E') && (key <= 'P'))
return "12";
else if ((key >= 'Q') && (key <= 'Z'))
return "24";
else if ((key >= '0') && (key <= '9'))
return "6";
else
return "15";
} |
c43de8e9-f557-4699-978e-4197434c1bfc | 3 | private LinkMatrix getLinkMatrix() {
// erzeuge Matrix
int L[][] = new int[pageCount][pageCount];
for (Page j : pages.values()) {
L[j.nbr][j.nbr] = 1;
for (Page i : j.links)
L[i.nbr][j.nbr] = 1;
}
// stelle Output zusammen
LinkMatrix lm = new LinkMatrix();
lm.L = L;
lm.urls = new String[pageCount];
for (Page p : pages.values())
lm.urls[p.nbr] = p.url;
return lm;
} |
f1b6049f-4df4-4f06-baff-41814d921a9a | 5 | @Test
public void testGetPublisher() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/librarysystem?user=admin&password=123456");
Statement st = conn.createStatement();
ResultSet rs = null;
try {
//Unmatched isbn
ArrayList<Publisher> pubs = bh.getPublishers(0L, st, rs);
assertTrue(pubs.size() == 0);
//Matched isbn with one publisher
pubs = bh.getPublishers(9780545139700L, st, rs);
assertTrue(pubs.size() == 1);
}catch (Exception e) {
fail("Caught exception:" + e.getMessage());
}
finally
{
try {
if(conn != null)
conn.close();
if(st != null)
st.close();
if(rs != null)
rs.close();
} catch (Exception e) { }
}
} |
14b57934-cd7e-4713-8e97-8f0f9b0ecb44 | 4 | public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return description.equals(other.description)
&& partNumber == other.partNumber;
} |
b6d74b63-4664-4a3d-9ded-c83ba91778ab | 2 | @SuppressWarnings("unchecked")
public final JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
} |
a61022f3-6243-4aed-8edd-4cc67231cae3 | 7 | public String getString() {
if (data_ == null)
return "void";
else if (data_ instanceof Void)
return "void";
else if (getType() == ValueType.COLOR)
return Utils.codeColor((Color) data_);
else if (getType() == ValueType.ARRAY) {
@SuppressWarnings("unchecked")
ArrayList<Value> vals = (ArrayList<Value>) data_;
if (vals.size() == 0)
return "[]";
String str = "[" + vals.get(0).getString();
for (int i = 1; i < vals.size(); i++) {
str += ", " + vals.get(i).getString();
}
str += "]";
return str;
} else if (getType() == ValueType.FILE) {
String str = "file:";
str += ((File) data_).getAbsolutePath();
return str;
}
return data_.toString();
} |
f49ab878-05a6-4ef0-93e9-ccb6bc2d666e | 4 | public MuteableURL(String spec) {
String[] parsed_url = parseURL(spec);
// Then store the parts
if (parsed_url != null) {
setProtocol(parsed_url[0]);
setAuthority(parsed_url[1]);
setUserInfo(parsed_url[2]);
setHost(parsed_url[3]);
try {
String port_string = parsed_url[4];
if (port_string != null && port_string.length() > 0) {
setPort(Integer.parseInt(port_string));
} else {
setPort(-1);
}
} catch (NumberFormatException nfe) {
setPort(-1);
nfe.printStackTrace();
}
setPath(parsed_url[5]);
setQuery(parsed_url[6]);
setFragment(parsed_url[7]);
}
/*
System.out.println("protocol: " + this.protocol);
System.out.println("authority: " + this.authority);
System.out.println("user_info: " + this.userInfo);
System.out.println("host: " + this.host);
System.out.println("port: " + this.port);
System.out.println("path: " + this.path);
System.out.println("query: " + this.query);
System.out.println("fragment: " + this.fragment);*/
} |
3aa9b86f-0d10-4368-b978-664d5bfbb249 | 1 | public MenuSaisie() {
initComponents();
for (Entreprise entr : MainProjet.lesEntreprises) {
jComboNomE.addItem(entr.getNom());
}
} |
9a06d586-d686-427a-af59-6f431d50aa8c | 2 | @Override
public boolean isMovingEnabledAt( int x, int y ) {
if( moveableIfSelected ){
SelectableCapability selectable = getCapability( CapabilityName.SELECTABLE );
if( selectable != null ){
return selectable.getSelected().isSelected();
} else {
return false;
}
} else {
return getBoundaries().contains( x, y );
}
} |
6680805c-77f8-4cac-878e-3ade8b2cf077 | 6 | public static Boolean UpdateQuestion(Question QuestionToUpdate)
{
List<String> statements = new ArrayList<String>();
statements.add(String.format("Update Question Set QuestionText = '%s', isValidated = %s, isRejected = %s where QuestionId = %d", QuestionToUpdate.questionText, QuestionToUpdate.isValidated? "TRUE" : "FALSE", QuestionToUpdate.isRejected? "True" : "False", QuestionToUpdate.dbId));
for (Answer A : QuestionToUpdate.answers)
{
if (A.dbId == 0)
{
statements.add (String.format("insert into questionanswer (QuestionId, AnswerId, AnswerText, IsCorrect)values "
+ "(%d, ((select max(AnswerId) from questionanswer where questionid = %d) + 1), '%s', %s)", QuestionToUpdate.dbId, QuestionToUpdate.dbId, A.answerText, A.isCorrect? "TRUE" : "FALSE"));
}
else
{
statements.add(String.format ("update questionanswer set AnswerText = '%s', IsCorrect = %s where QuestionId = %d and AnswerID = %d", A.answerText, A.isCorrect? "TRUE" : "FALSE", QuestionToUpdate.dbId, A.dbId ));
}
}
return runStatementBatch(statements);
} |
fa578bfa-a80e-43aa-b843-f1eac1c9bf3b | 2 | public synchronized void drawImage(AbstractAlgorithm imgGen, double scale) {
BufferedImage toDraw = imgGen.generate();
int scaledWidth = (int) (toDraw.getWidth() * scale);
int scaledHeight = (int) (toDraw.getHeight() * scale);
BufferedImage scaled = new BufferedImage(scaledWidth, scaledHeight,
BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < scaledWidth; i++) {
for (int j = 0; j < scaledHeight; j++) {
scaled.setRGB(i, j, toDraw.getRGB((int)(i / scale),(int) (j / scale)));
}
}
paintImage(scaled);
} |
3b3d5403-9671-4e31-9700-ce7df7e2dd5b | 1 | public void dumpInstruction(TabbedPrintWriter writer)
throws java.io.IOException {
writer.println("continue"
+ (continueLabel == null ? "" : " " + continueLabel) + ";");
} |
9af83bdc-b5a6-41fc-80f6-ff9087e253d8 | 4 | public void close() {
closed = true;
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException exception) {
System.out.println("Error closing stream");
}
isWriter = false;
synchronized (this) {
notify();
}
buffer = null;
} |
237ee591-aed3-4893-8704-ac27a6799460 | 8 | public int experienceLevels(MOB caster, int asLevel)
{
if(caster==null)
return 1;
int adjLevel=1;
final int qualifyingLevel=CMLib.ableMapper().qualifyingLevel(caster,this);
final int lowestQualifyingLevel=CMLib.ableMapper().lowestQualifyingLevel(this.ID());
if(qualifyingLevel>=0)
{
final int qualClassLevel=CMLib.ableMapper().qualifyingClassLevel(caster,this);
if(qualClassLevel>=qualifyingLevel)
adjLevel=(qualClassLevel-qualifyingLevel)+1;
else
if(caster.phyStats().level()>=qualifyingLevel)
adjLevel=(caster.phyStats().level()-qualifyingLevel)+1;
else
if(caster.phyStats().level()>=lowestQualifyingLevel)
adjLevel=(caster.phyStats().level()-lowestQualifyingLevel)+1;
}
else
if(caster.phyStats().level()>=lowestQualifyingLevel)
adjLevel=(caster.phyStats().level()-lowestQualifyingLevel)+1;
if(asLevel>0)
adjLevel=asLevel;
adjLevel += getPersonalLevelAdjustments(caster);
if(adjLevel<1)
return 1;
return adjLevel+getXLEVELLevel(caster);
} |
bfef7d95-3148-4cca-acfe-fe3b190377b5 | 1 | private void labelWebsiteUriMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelWebsiteUriMouseClicked
try {
URI website = new URI(this.websiteUri);
openUriInBrowser(website);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}//GEN-LAST:event_labelWebsiteUriMouseClicked |
6370e793-16c9-4814-b08b-a169b616bbaf | 0 | protected final void resetCurrentFailure() {
this.currentFailure.set(NO_FAILURE);
} |
ef18e6e5-bef6-4b31-b18c-ae59eabe524d | 3 | public char nextClean() throws JSONException {
for (;;) {
char c = next();
if (c == 0 || c > ' ') {
return c;
}
}
} |
8c31a98b-d06f-44ef-8cb8-e8d0aad3f8ed | 1 | public static void main(String[] argsv) {
// Setting op a bank.
Bank christmasBank = new Bank();
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(100)));
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(50), BigInteger.valueOf(-1000)));
// Print the balance of all accounts with a balance not below some threshold.
System.out.print("Enter the threshold for the balance: ");
Scanner inputStreamScanner = new Scanner(System.in);
final BigInteger threshold = BigInteger.valueOf(inputStreamScanner.nextLong());
Set<BankAccount> accountsBalanceNotBelowThreshold =
christmasBank.getAccountsSatisfying
(account -> account.getBalance().compareTo(threshold) >= 0);
for (BankAccount account : accountsBalanceNotBelowThreshold)
System.out.println(account.getBalance());
} |
9b73a88e-0811-4154-988f-f7875ae585df | 9 | private static Member memberForSignature2(String s, boolean isCtor) {
int openPar = s.indexOf('(');
int closePar = s.indexOf(')');
// Verify only one open/close paren, and close paren is last char.
assert openPar == s.lastIndexOf('(') : s;
assert closePar == s.lastIndexOf(')') : s;
assert closePar == s.length() - 1 : s;
String clsAndMethod = s.substring(0, openPar);
int lastDot = clsAndMethod.lastIndexOf('.');
// There should be at least one dot, separating class/method name.
assert lastDot >= 0;
String clsName = clsAndMethod.substring(0, lastDot);
String methodName = clsAndMethod.substring(lastDot + 1);
if (isCtor)
assert methodName.equals("<init>");
String argsOneStr = s.substring(openPar + 1, closePar);
// Extract parameter types.
Class<?>[] argTypes = new Class<?>[0];
if (argsOneStr.trim().length() > 0) {
String[] argsStrs = argsOneStr.split(",");
argTypes = new Class<?>[argsStrs.length];
for (int i = 0; i < argsStrs.length; i++) {
argTypes[i] = classForName(argsStrs[i].trim());
}
}
Class<?> cls = classForName(clsName);
try {
if (isCtor)
return cls.getDeclaredConstructor(argTypes);
else
return cls.getDeclaredMethod(methodName, argTypes);
}
catch (Exception e) {
throw new Error(e);
}
} |
ab572b28-6781-44ab-800b-86014615862e | 4 | private String[] ubahStringKeArray(int batas, int maxBagian, String kata){
String[] temp= new String[maxBagian];
int j = kata.length();
int k;
int banyakBagian = ((j % batas) == 0 ? (j / batas) :Math.round((j / batas) + 0.5f));
for(int i = banyakBagian - 1; i >=0 ; i--){
k = j - batas;
if(k < 0) k = 0;
temp[i]=kata.substring(k,j);
j = k ;
if (j == 0) break;
}
return temp;
} |
16cae805-3811-4d18-a8d3-349344f5bbc3 | 3 | public boolean replace(int index, T newV) {
if (index < 0 || index >= size)
return false;
T oldV = heap.get(index).element();
heap.get(index).setElement(newV);
if (comp.compare(oldV, newV) < 0)
trickleUp(index);
else
trickleDown(index);
return true;
} |
535b42c8-21be-4432-89a7-e70187b0bc51 | 3 | public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
StringBuilder out = new StringBuilder();
while (in.hasNext()) {
int size = in.nextInt();
if (size == 0)
break;
blocks = new Point[size];
for (int i = 0; i < size; i++)
blocks[i] = new Point(in.nextInt(), in.nextInt());
Arrays.sort(blocks, new OrderBlocks());
out.append(findLIS(size) + "\n");
}
System.out.print(out + "*\n");
} |
7b473479-0848-4ce6-b1aa-4b5c84228a0d | 5 | private int subscribeRdfFiles(final File folder) {
int count = 0;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
subscribeRdfFiles(fileEntry);
} else {
String regex = "([^\\s]+(\\.(?i)(ttl|rdf|n3))$)";
if (fileEntry.getName().matches(regex)) {
System.out.println(fileEntry.getName());
String content_type = mimetypes_map
.getContentType(fileEntry);
FileInputStream fis;
try {
fis = new FileInputStream(fileEntry);
String content = IOUtils.toString(fis, "UTF-8");
PostMethod subscription = new PostMethod(url.toString()
+ "/register");
subscription.setRequestEntity(new StringRequestEntity(
content, content_type, "UTF-8"));
client.executeMethod(subscription);
if (subscription.getStatusCode() == 201) {
LOGGER.info(subscription.getStatusCode() + " :"
+ subscription.getStatusText() + " "
+ subscription.getPath());
count++;
} else
LOGGER.error(subscription.getStatusCode() + " :"
+ subscription.getStatusText() + " "
+ subscription.getPath());
subscription.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return count;
} |
18ce5368-4ada-4288-b3fd-72e7a041e597 | 0 | public void setA(int a){
acceleration = a;
} |
e32f4c8a-b158-44be-ac69-362c6a528abf | 6 | public boolean isAccessible(Site other) {
//everything that is accessible, is adjacent
if (!isAdjacent(other)){
//log.info("Is not adacent");
return false;
//check it is standable at the start
} else if (!isWalkable()){
//log.info("Is not walkable");
return false;
//step down
} else if (getZ() < other.getZ()){
//site above target must be empty
if (landscape.isSolid(other.getX(), other.getY(), other.getZ()-1)){
return false;
} else {
return true;
}
//step up
} else if (getZ() > other.getZ()){
//site above self must be empty
if (landscape.isSolid(getX(), getY(), getZ()-1)){
return false;
} else {
return true;
}
//same level
} else {
return true;
}
} |
505e8f53-5df3-4ff6-b81f-d8340dcf983a | 6 | protected void placeC4()
{
if(C4Placed)
{
int n = listElements.size();
Element e;
for(int i = 0; i < n; i++)
{
e = listElements.get(i);
if(e.type == Type.WEAPONS)
pushEvent(e, "C4");
}
}
else if(nbC4 > 0)
{
if(collisionElementList(((int)(x/32.0))*32+16, ((int)(y/32.0))*32+16, Type.WEAPONS, false).isEmpty()
&& collisionElementList(((int)(x/32.0))*32+16, ((int)(y/32.0))*32+16, Type.EXPLOSION, false).isEmpty())
{
C4PosX = ((int)(x/32))*32+16;
C4PosY = ((int)(y/32))*32+16;
C4Placed=true;
listElements.addElement(new C4(((int)(x/32))*32+16,((int)(y/32))*32+16,power,explosionLength, this));
nbC4--;
}
}
} |
de7a4f95-756c-4e71-b045-4d8c19b27593 | 5 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h3>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${adminLogin}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</h3><a href=\"ShowBookList.view\">List</a>|<a href=\"addBook.jsp\">Add</a>|<a href=\"index.jsp\">index</a>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
06d23f1b-79da-487d-b65b-b15f928755dc | 5 | public static StringBuilder Htmlfullticket (Integer integer) {
// Display the selected item
String [] Array = FullTicket.searchFullTicket(integer);
Object [] product = Comp.searchTicketProduct(integer).toArray();
//Set color for ticket status
String color = "red";
if (Array[1].equals("Open")) color = "green";
else if (Array[1].equals("In process")) color = "blue";
for (int i = 0; i < Array.length ; i++) {
if (Array[i] == null || "null".equals(Array [i])) {
Array[i] = "";
}
}
//html formatted text for Fullticket Editor pane
StringBuilder builder = new StringBuilder("<h2>Ticket ID: " + integer +"</h2> "
+"<table border='0'>"
+"<tr>"
+"<td width='140'>"
+ "<font color='#708090'><b>"
+ "Created on:"
+ "</b></font></td><td>"+ StringtoDate(Array[14]) +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Last update:"
+ "</b></font></td><td>"+ StringtoDate(Array[15]) +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Problem Category:"
+ "</b></font></td><td>"+ Array[0] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Ticket Status:"
+ "</b></font></td><td><u><font color="+color+"><b>"+ Array[1] +"</b></font></u></td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Employee ID"
+ "</b></font></td><td>"+ Array[2] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Employee Firstname: "
+ "</b></font></td><td>"+ Array[3] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Employee Lastname: "
+ "</b></font></td><td>"+ Array[4] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Customer ID: "
+ "</b></font></td><td>"+ Array[5] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Customer Firstname:"
+ "</b></font></td><td>"+ Array[6] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Customer Lastname:"
+ "</b></font></td><td>"+ Array[7] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Telephone:"
+ "</b></font></td><td>"+ Array[8] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Email:"
+ "</b></font></td><td>"+ Array[9] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Topic:"
+ "</b></font></td><td>"+ Array[10] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Problem:"
+ "</b></font></td><td>"+ Array[11] +"</td>"
+"</tr><tr>"
+"<td>"
+ "<font color='#708090'><b>"
+ "Note:"
+ "</b></font></td><td>"+ Array[12] +"</td>"
+"</tr><tr>"
+"<td align='left' valign='top'>"
+ "<font color='#708090'><b>"
+ "Involved Product:"
+ "</b></font></td><td>"+ Arrays.toString(product) +"</td>"
+"</tr><tr>"
+"<td align='left' valign='top'>"
+ "<font color='#708090'><b>"
+ "Solution:"
+ "</b></font></td><td>"+ Array[13] +"</td>"
+"</tr>"
);
return builder;
} |
da5aa8cd-8678-4b51-b284-b06a6bd70121 | 5 | public int parse(CharsetDetector det)
{
int b;
boolean ignoreSpace = false;
while ((b = nextByte(det)) >= 0) {
byte mb = byteMap[b];
// TODO: 0x20 might not be a space in all character sets...
if (mb != 0) {
if (!(mb == 0x20 && ignoreSpace)) {
addByte(mb);
}
ignoreSpace = (mb == 0x20);
}
}
// TODO: Is this OK? The buffer could have ended in the middle of a word...
addByte(0x20);
double rawPercent = (double) hitCount / (double) ngramCount;
// if (rawPercent <= 2.0) {
// return 0;
// }
// TODO - This is a bit of a hack to take care of a case
// were we were getting a confidence of 135...
if (rawPercent > 0.33) {
return 98;
}
return (int) (rawPercent * 300.0);
} |
73d95137-0f46-477d-9baf-f1dd3eebf971 | 0 | public String getDesc() {
return desc;
} |
bf3e63fa-bd7f-4ca5-835b-2681d31e3fcd | 6 | public boolean isUserAlreadyExists(String userId) {
Connection connection = new DbConnection().getConnection();
ResultSet resultSet = null;
boolean flag = false;
Statement statement = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(IS_USER_ALREADY_EXISTS + userId);
if (resultSet.next())
flag = true;
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
} finally {
try {
if (connection != null)
connection.close();
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
}
}
return flag;
} |
3a67a753-783d-4752-9750-7b2ed01d244e | 4 | @Override
public void run() {
int run = 1;
while (run == 1) {
String message = "";
// Block and wait for input from the socket
try {
message = socket.readMessage();
if (message==null) {
try {
server.removeSocket(hash);
} catch (IOException e) {
}
} else {
server.handleMessage(message,hash);
}
} catch (IOException e) {
}
}
} |
03cc06b7-5ada-4b96-bdd4-0ed58f54fc09 | 4 | public static String deleteAny(String inString, String charsToDelete) {
if (!hasLength(inString) || !hasLength(charsToDelete)) {
return inString;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
builder.append(c);
}
}
return builder.toString();
} |
0ce06022-dd69-4605-94e6-1b29bbe9f940 | 1 | public void shutdown() {
log.log(Level.INFO,"Starting Shutdown");
if(conLis != null) {
conLis.end();
}
disconnect(ALL());
serverStatus = ServerStatus.SHUTDOWN;
log.log(Level.INFO, "Finished Shutdown");
} |
5508e3eb-4c9d-4455-83f5-550b53570281 | 8 | @SuppressWarnings("unchecked")
@Override
public Object run() {
List<Map<String, Object>> filtered = new ArrayList<Map<String, Object>>();
if(source().containsKey(occurrenceField)) {
List<Map<String, Object>> occurrences = (List<Map<String, Object>>)source().get(occurrenceField);
addParsedOccurrenceFields(occurrences);
Collections.sort(occurrences, new OccurrenceComparator());
boolean isDone = false;
Long startDate = null;
for(Map<String, Object> occurrence : occurrences) {
startDate = (Long)occurrence.get(OccurrenceComparator.PARSED_FIELD);
if(startDate != null) {
for(int i=0; i<intervals.size(); i++) {
UnixTimeInterval interval = intervals.get(i);
if(interval.contains(startDate)) {
occurrence.remove(OccurrenceComparator.PARSED_FIELD);
filtered.add(occurrence);
break;
} else if(i == intervals.size() - 1 && startDate > interval.getStart()) {
isDone = true;
break;
}
}
}
if(isDone) {
break;
}
}
}
return filtered;
} |
bd22cf3c-25c0-463a-822a-8bba663a608d | 4 | void setBytes( String ur, String desc, String tm )
{
try
{
setGrbit();
int pos = 32; // start of description/text input
byte[] blankbytes = new byte[2]; // trailing zero word
byte[] newbytes = new byte[pos];
System.arraycopy( mybytes, 0, newbytes, 0, pos ); // copy old pre-string data into new array
if( hasDescription )
{
// copy char array length (cch) of description + description bytes
byte[] descbytes = desc.getBytes( UNICODEENCODING );
int newcch = descbytes.length;
byte[] newcchbytes = ByteTools.cLongToLEBytes( (newcch / 2) + 1 );
// copy cch of desc in...
newbytes = ByteTools.append( newcchbytes, newbytes );
//copy bytes of description in
newbytes = ByteTools.append( descbytes, newbytes );
// copy trailing dumb str bytes in
newbytes = ByteTools.append( blankbytes, newbytes );
}
/* TODO: Implement target frame right here
if (hasTargetFrame) {
// copy targetFrame bytes + length
// get cch
byte[] tfbytes= tf.getBytes(UNICODEENCODING);
int newcch = tfbytes.length;
byte[] newcchbytes = ByteTools.cLongToLEBytes(newcch/2 +1);
// copy cch of tm in...
newbytes = ByteTools.append(newcchbytes, newbytes);
//copy bytes of tf in
newbytes = ByteTools.append(tfbytes, newbytes);
// copy trailing dumb str bytes in
newbytes = ByteTools.append(blankbytes, newbytes);
}
*/
/* URL Handling */
// copy GUID in - ASSUME URL_GUID since aren't supporting relative FILE_GUIDs!
newbytes = ByteTools.append( URL_GUID, newbytes );
if( isLink )
{
// copy url bytes + length
// get cch (which is different alg. from both description + textmark)
byte[] urlbytes = ur.getBytes( UNICODEENCODING );
int newcch = urlbytes.length;
// copy cch of url in...
byte[] newcchbytes = ByteTools.cLongToLEBytes( newcch + 2 );
newbytes = ByteTools.append( newcchbytes, newbytes );
// copy url bytes in
newbytes = ByteTools.append( urlbytes, newbytes );
// copy trailing dumb str bytes in
newbytes = ByteTools.append( blankbytes, newbytes );
}
if( hasTextMark )
{
// copy textmark bytes + length
// get cch
byte[] tmbytes = tm.getBytes( UNICODEENCODING );
int newcch = tmbytes.length;
byte[] newcchbytes = ByteTools.cLongToLEBytes( (newcch / 2) + 1 );
// copy cch of tm in...
newbytes = ByteTools.append( newcchbytes, newbytes );
//copy bytes of tm in
newbytes = ByteTools.append( tmbytes, newbytes );
// copy trailing dumb str bytes in
newbytes = ByteTools.append( blankbytes, newbytes );
}
mybytes = newbytes;
linktext = desc;
textMark = tm;
url = ur;
}
catch( UnsupportedEncodingException e )
{
log.warn( "Setting URL failed: " + ur + ": " + e );
}
} |
e0726190-8bbe-4e60-9da6-cf20f168343e | 9 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(apertureValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((autoFocus == null) ? 0 : autoFocus.hashCode());
result = prime * result + ((backLight == null) ? 0 : backLight.hashCode());
temp = Double.doubleToLongBits(brightnessValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + cfaPattern;
result = prime * result + ((exifVersion == null) ? 0 : exifVersion.hashCode());
temp = Double.doubleToLongBits(exposeBiasValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(exposureIndex);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((exposureProgram == null) ? 0 : exposureProgram.hashCode());
temp = Double.doubleToLongBits(exposureTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(fNumber);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((flash == null) ? 0 : flash.hashCode());
temp = Double.doubleToLongBits(flashEnergy);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(focalLength);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + isoSpeedRatings;
result = prime * result + ((lightSource == null) ? 0 : lightSource.hashCode());
temp = Double.doubleToLongBits(maxApertureValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((meteringMode == null) ? 0 : meteringMode.hashCode());
temp = Double.doubleToLongBits(oECF);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((sensingMode == null) ? 0 : sensingMode.hashCode());
temp = Double.doubleToLongBits(shutterSpeedValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((spectralSensitivity == null) ? 0 : spectralSensitivity.hashCode());
temp = Double.doubleToLongBits(subjectDistance);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(xPrintAspectRatio);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(yPrintAspectRatio);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
} |
820516a8-e910-43f5-8f9c-1e7d49caae31 | 3 | public static void main(String arg[]) {
// int[] sizes = {4};
// int index = 4;
// int[] indexes = new int[1];
//
//
// for (int foo = 0; foo < 4; foo++) {
// System.out.print(foo);
// MmsParameter.figureOutIndexes(foo, sizes, indexes);
//
// for (int i = 0; i < indexes.length; i++) {
// System.out.print(" " + indexes[i]);
// }
// System.out.println("");
// }
int[] indexes = new int[3];
MmsDimension[] dims = new MmsDimension[3];
dims[0] = new MmsDimension("nlapse", 4);
dims[1] = new MmsDimension("nmonth", 3);
dims[2] = new MmsDimension("foo", 2);
for (int ifoo = 0; ifoo < 2; ifoo++) {
for (int imonth = 0; imonth < 3; imonth++) {
for (int ilapse = 0; ilapse < 4; ilapse++) {
indexes[0] = ilapse;
indexes[1] = imonth;
indexes[2] = ifoo;
System.out.println(MmsParameter.figureOutIndex(dims, indexes) + " " + indexes[0] + " " + indexes[1] + " " + indexes[2]);
}
}
}
} |
37bcaaf2-123a-48b2-807d-921f49e3c027 | 9 | public static void main(String[] args) {
final CircularBuffer<Integer> cb = new CircularBuffer<>(23);
final Random randomizer = new Random();
final int MAX_MARGIN = 120_000;
final CountDownLatch latch = new CountDownLatch(1);
class Producer extends Thread {
private volatile boolean valid = true;
public Producer(String name) {
super(name);
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
while(valid) {
Integer element = randomizer.nextInt(MAX_MARGIN);
try {
cb.addElement(element);
System.out.println(Thread.currentThread().getName() + ": Element " + element + " added. Queue size: " + cb.getSize());
Thread.sleep(randomizer.nextInt(MAX_MARGIN) % 2_000);
} catch (InterruptedException e) {
valid = false;
System.err.println("EXCEPTION HANDLED in Thread " + Thread.currentThread().getName());
}
}
}
}
class Consumer extends Thread {
private volatile boolean valid = true;
public Consumer(String name) {
super(name);
}
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
while (valid) {
Integer element = null;
try {
element = cb.removeElement();
System.out.println(Thread.currentThread().getName() + ": Element " + element + " removed. Queue size: " + cb.getSize());
Thread.sleep(randomizer.nextInt(MAX_MARGIN) % 3_000);
} catch (InterruptedException e) {
valid = false;
System.err.println("EXCEPTION HANDLED in Thread " + Thread.currentThread().getName());
}
}
}
}
Producer[] producers = new Producer[5];
for (int i = 0; i < producers.length; i++) {
producers[i] = new Producer("Producer_" + i);
producers[i].start();
}
Consumer[] consumers = new Consumer[3];
for (int i = 0; i < consumers.length; i++) {
consumers[i] = new Consumer("Consumer_" + i);
consumers[i].start();
}
latch.countDown();
for (int k = 0; k < 4; k++) {
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
System.err.println(e.getCause());
}
producers[k].interrupt();
}
try {
Thread.sleep(15_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (Producer producer : producers) {
if (producer.isAlive())
producer.interrupt();
}
for (Consumer consumer : consumers) {
if (consumer.isAlive())
consumer.interrupt();
}
System.out.println(cb);
} |
7f9481d4-4f54-41d5-b065-9942708f2a69 | 6 | private List<Network> getNetworkDevices(Component component, SoftwareSystem system) {
HardwareSet hardwareSet = null;
List<Network> networkDevices = new LinkedList<>();
for (DeployedComponent deployedComponent : system.getDeploymentAlternative().getDeployedComponents())
if (deployedComponent.getComponent().equals(component))
hardwareSet = deployedComponent.getHardwareSet();
if (!system.getActuallyUsedHardwareSets().contains(hardwareSet))
system.getActuallyUsedHardwareSets().add(hardwareSet);
for (HardwareSetAlternative hardwareSetAlternative : system.getHardwareSystem().getHardwareSetAlternatives())
if (hardwareSetAlternative.getHardwareSet().equals(hardwareSet))
for (HardwareComponent networkDevice : hardwareSetAlternative.getNetworkAlternative().getHardwareComponents())
networkDevices.add((Network) networkDevice);
return networkDevices;
} |
04c53900-6dd0-417b-ac22-4c31f7b0921d | 9 | public void paint(Graphics g) {
//the objects created above are made clickable with the mouseClicked method
super.paint(g);
final Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.white);
g2d.setFont(new Font("Courier", Font.BOLD, 60));
g2d.drawImage(MenuBG, 0, 0, this);
g2d.drawImage(BackImage, 10, 10, this);
g2d.setColor(Color.red);
//checks if the game is single player and prints different things if it is
if (Menu.isSingle()) {
g2d.drawString("You died! Try again!", 200, 380);
g2d.draw(PlayAgain);
g2d.setFont(new Font("Courier", Font.BOLD, 60));
g2d.drawString("Play Again?", PlayAgain.x + 30, PlayAgain.y + 70);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println(me);
//returns to the main menu
if (me.getX() > Back.x && me.getX() < Back.x + Back.width && me.getY() > Back.y && me.getY() < Back.y + Back.height) {
Fighters.newMenu();
tries++;
Fighters.cd.show(Fighters.contentPane, "menu");
}
//re runs single player if the user clicks the button
if (me.getX() > PlayAgain.x && me.getX() < PlayAgain.x + PlayAgain.width && me.getY() > PlayAgain.y && me.getY() < PlayAgain.y + PlayAgain.height) {
Fighters.newGame();
tries++;
Fighters.cd.show(Fighters.contentPane, "game");
}
}
});
}
} |
bf7da58d-adcd-4808-8e77-3387be958f8c | 2 | public void InitGUI() {
cmActionListener listener = new cmActionListener();
Container m_container = getContentPane();
m_container.setLayout(new FlowLayout());
JPanel optionsPanel = new JPanel(new GridLayout(UI_ROW,UI_COL));
m_container.add(optionsPanel);
JLabel dropboxText = new JLabel("Select colour scheme: ");
optionsPanel.add(dropboxText);
String[] colourMaps = new String[MAPCOUNT];
for (int i=0; i<MAPCOUNT; i++) {
colourMaps[i] = GetMap(i).GetMapName();
}
m_mapList = new JComboBox(colourMaps);
m_mapList.setEnabled(true);
m_mapList.setPreferredSize(new Dimension(UI_WIDTH, UI_HEIGHT));
m_mapList.addActionListener(listener);
optionsPanel.add(m_mapList);
JLabel blankLabel1 = new JLabel("");
optionsPanel.add(blankLabel1);
m_previewContainer = new JPanel();
optionsPanel.add(m_previewContainer);
m_previewPanel = DrawSwatches(m_mapList.getSelectedIndex());
m_previewContainer.add(m_previewPanel);
JPanel spacerPanel1 = new JPanel();
spacerPanel1.setSize(new Dimension(CP_WIDTH, CP_HEIGHT));
optionsPanel.add(spacerPanel1);
JPanel spacerPanel2 = new JPanel();
spacerPanel2.setSize(new Dimension(CP_WIDTH, CP_HEIGHT));
optionsPanel.add(spacerPanel2);
m_CustomButton = new JButton("Custom Colours");
m_CustomButton.addActionListener(listener);
spacerPanel2.add(m_CustomButton);
JLabel blankLabel2 = new JLabel("");
optionsPanel.add(blankLabel2);
JPanel buttonPanel = new JPanel(new FlowLayout());
optionsPanel.add(buttonPanel);
m_saveButton = new JButton("OK");
m_saveButton.addActionListener(listener);
buttonPanel.add(m_saveButton);
m_closeButton = new JButton("Cancel");
m_closeButton.addActionListener(listener);
buttonPanel.add(m_closeButton);
pack();
setResizable(false);
setLocationRelativeTo(null);
if (m_cmFirstTimeOpen) {
setVisible(false);
m_cmFirstTimeOpen = false;
} else {
setVisible(true);
}
} |
cd2b8f84-4240-4a6a-ac61-799c89d8d193 | 4 | public void createResources() throws GridSimRunTimeException {
printRuntimeMessage("Creating resouces");
int currentResourceID = 0;
for (GridSimResourceConfig resConfig: _config.getResources()) {
MachineList machines = new MachineList();
int currentMachineID = 0;
for (GridSimMachineConfig mc: resConfig.getMachines()) {
machines.add(new Machine(currentMachineID, mc.getPECount(), mc.getPERating()));
++currentMachineID;
}
ResourceCharacteristics rc = new ResourceCharacteristics(resConfig.getArch(), resConfig.getOS(),
machines, resConfig.getAllocPolicy(), resConfig.getTimeZone(), resConfig.getCostPerSec());
ResourceCalendar calendar = new ResourceCalendar(resConfig.getTimeZone(), RESOURCES_PEAK_LOAD,
RESOURCES_OFFPEAK_LOAD, RESOURCES_HOLIDAY_LOAD, RESOURCES_CALENDAR_WEEKENDS,
RESOURCES_CALENDAR_HOLIDAYS, RESOURCES_CALENDAR_SEED);
for (long i = 0; i < resConfig.getCount(); ++i) {
GridResource resource;
String resName = String.format("Resource_%1$d", currentResourceID);
try {
printRuntimeMessage("Creating resource " + resName);
resource = new GridResource(resName, resConfig.getBaudRate(), rc, calendar);
}
catch (Exception e) {
String desc = "Failed to create resource " + resName + ": " + e.getMessage();
printRuntimeMessage(desc);
throw new GridSimRunTimeException(desc);
}
++currentResourceID;
}
}
printRuntimeMessage("Resouces created");
} |
fc0a986d-f335-40bc-9a81-911439f31857 | 2 | public Object[] GetColumnData(int columnNo){
if(!(columnNo<m_attributeCount)){
JPanel frame = new JPanel();
JOptionPane.showMessageDialog(frame,
"Column Index out of bounds",
"File error",
JOptionPane.ERROR_MESSAGE);
} else {
m_columnData = new Object[m_entryCount];
for(int i = 0; i<m_entryCount; i++){
m_columnData[i] = m_data[i][columnNo];
}
return m_columnData;
}
return null;
} |
b68d619a-1e26-4055-938c-d73016296699 | 3 | private synchronized void insert(Packet np, double time)
{
if ( timeList.isEmpty() )
{
timeList.add( new Double(time) );
pktList.add(np);
return;
}
for (int i = 0; i < timeList.size(); i++)
{
double next = ( (Double) timeList.get(i) ).doubleValue();
if (next > time)
{
timeList.add(i, new Double(time));
pktList.add(i, np);
return;
}
}
// add to end
timeList.add( new Double(time) );
pktList.add(np);
return;
} |
44522244-7a0d-49a1-a188-9dfb41e79347 | 7 | public void receive(Object obj) {
// TODO Parse all possible messages
Event event = (Event)obj;
int port;
switch(event.type) {
case "new game":
port = (int)event.data;
if (port==-1) throw new RuntimeException("could not create game, go back to main menu");
else {
gui.joinGame(port);
}
break;
case "games info":
Vector<GameObject> games = (Vector<GameObject>)event.data;
Helper.log("Received update game event from central server, updated " + games.size() + " games.");
gui.lobby.updateGames(games);
break;
case "join game":
port = (int)event.data;
System.out.println("CONNECTION TO CS: ABOUT TO TELL GUI TO JOIN GAME");
gui.joinGame(port);
break;
case "new profile":
gui.createProfile.createProfileResponse(event);
break;
case "login":
System.out.println("recevied login: " + event);
gui.login.loginResponse(event);
break;
case "stats":
gui.stats.statsResponse(event);
break;
default:
ThinkTankGUI.logger.log(Level.INFO, "Parse error. did not understand message: " + event);
}
} |
76b6a974-a04e-4d2d-a245-6a996621f8b2 | 5 | public static void sendMe(MapleCharacter player, String msg) {
MaplePacket packet;
switch (player.getGMLevel()) {
case 0:
packet = MaplePacketCreator.serverNotice(6, "[Rookie ~ " + player.getName() + "] " + msg);
break;
case 1:
packet = MaplePacketCreator.serverNotice(6, "[Genin ~ " + player.getName() + "] " + msg);
break;
case 2:
packet = MaplePacketCreator.serverNotice(6, "[Chunin ~ " + player.getName() + "] " + msg);
break;
case 3:
packet = MaplePacketCreator.serverNotice(6, "[Jounin ~ " + player.getName() + "] " + msg);
break;
case 4:
packet = MaplePacketCreator.serverNotice(6, "[Sannin ~ " + player.getName() + "] " + msg);
break;
default:
packet = MaplePacketCreator.serverNotice(6, "[Hokage] " + msg);
}
player.getClient().getChannelServer().broadcastPacket(packet);
MainIRC.getInstance().sendIrcMessage(Colors.BOLD + "#ME : " + player.getName() + " - " + Colors.RED + msg);
} |
8a3ee232-18fb-4428-8fc3-34f550b93322 | 7 | private int getDimenMasLargo(){
int dim=0;
LinkedList<Atributo> la=clase.getListaAtributos();
if ( la!=null ){
for ( int i=0 ; i<la.size() ; i++ ) {
Atributo a = la.get(i);
if ( a.toStringGrafico().length()>dim )
dim = a.toStringGrafico().length();
}
}
LinkedList<Metodo> lm=clase.getListaMetodos();
if ( lm!=null ){
for ( int i=0 ; i<lm.size() ; i++ ) {
Metodo m = lm.get(i);
if ( m.toStringGrafico().length()>dim )
dim = m.toStringGrafico().length();
}
}
if ( clase.getNombre().length()>dim )
dim = clase.getNombre().length();
return dim;
} |
6f07f71b-f903-4944-bdd5-1b8080aa74ef | 6 | public static <T extends RestObject> T getRestObject(Class<T> restObject, String url) throws RestfulAPIException {
InputStream stream = null;
try {
URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
stream = conn.getInputStream();
String data = IOUtils.toString(stream, Charsets.UTF_8);
T result = gson.fromJson(data, restObject);
if (result == null) {
throw new RestfulAPIException("Unable to access URL [" + url + "]");
}
if (result.hasError()) {
throw new RestfulAPIException("Error in response: " + result.getError());
}
return result;
} catch (SocketTimeoutException e) {
throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
} catch (MalformedURLException e) {
throw new RestfulAPIException("Invalid URL [" + url + "]", e);
} catch (JsonParseException e) {
throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
} catch (IOException e) {
throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
} finally {
IOUtils.closeQuietly(stream);
}
} |
2da9fc87-3979-4688-b647-a3ff793f31db | 8 | final void method346() {
if (anInt584 == -1) {
anInt584 = 0;
if (anIntArray558 != null && (anIntArray574 == null || anIntArray574[0] == 10)) {
anInt584 = 1;
}
for (int i = 0; i < 5; i++) {
if (actions[i] == null) {
continue;
}
anInt584 = 1;
break;
}
}
if (anInt550 == -1) {
anInt550 = anInt618 != 0 ? 1 : 0;
}
} |
a45979be-9e17-42b5-b901-648a7584156c | 5 | public Object open(final int coordX, final int coordY) {
try {
fr = new BufferedReader(new FileReader(new File(pathToDiagramsLogFile)));
lines = new ArrayList<String>();
String line;
while ((line = fr.readLine()) != null) {
lines.add(line.replaceAll("\t+", " "));
}
parsedLines = parseLines(lines);
} catch (FileNotFoundException e) {
MainWindow.showMessage(Messages.TIME_DIAGRAMS_COULD_NOT_OPEN_LOGFILE + this.pathToDiagramsLogFile, "Error");
e.printStackTrace();
} catch (IOException e1) {
MainWindow.showMessage(Messages.TIME_DIAGRAMS_COULD_NOT_READ_LOGFILE + this.pathToDiagramsLogFile, "Error");
e1.printStackTrace();
}
createContents(coordX, coordY);
timeDiagramsShell.open();
isVisible = true;
MainWindow.status(Messages.TIME_DIAGRAMS_OPEN);
timeDiagramsShell.layout();
Display display = getParent().getDisplay();
while (!timeDiagramsShell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return null;
} |
ca38a2c0-209a-4763-8ed6-808b1a1b9c98 | 1 | public void setTarget( ItemKey<? extends Box> target ) {
this.target = target;
} |
72749605-f204-4935-892e-d6cb69edb468 | 8 | private JPanel createProcessorSettingsPanel()
{
final JPanel jp = new JPanel();
jp.setBorder(default_border);
BoxLayout bl = new BoxLayout(jp, BoxLayout.PAGE_AXIS);
jp.setLayout(bl);
JComponent cp = new JLabel(UIStrings.UI_PROC_NAME_LABEL);
setItemAlignment(cp);
jp.add(cp);
JPanel ip = new JPanel();
bl = new BoxLayout(ip, BoxLayout.LINE_AXIS);
processor_name_selector = new JComboBox();
processor_name_selector.setModel(new DefaultComboBoxModel());
processor_name_selector.setEditable(true);
Dimension d = processor_name_selector.getPreferredSize();
d.width = 160;
processor_name_selector.setPreferredSize(d);
processor_name_selector.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie)
{
int type = ie.getStateChange();
switch(type)
{
case ItemEvent.ITEM_STATE_CHANGED:
{
ExternalProcessor ep = (ExternalProcessor)processor_name_selector.getSelectedItem();
processor_path_field.setText(ep.path);
processor_options_field.setText(ep.options);
break;
}
case ItemEvent.DESELECTED:
{
ExternalProcessor ep2 = (ExternalProcessor)processor_name_selector.getSelectedItem();
ExternalProcessor ep = (ExternalProcessor)ie.getItem();
}
}
}
});
processor_name_selector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
String cmd = ae.getActionCommand();
if(cmd.equals("comboBoxChanged"))
{
ExternalProcessor ep = (ExternalProcessor)processor_name_selector.getSelectedItem();
processor_path_field.setText(ep.path);
processor_options_field.setText(ep.options);
}
}
});
ip.add(processor_name_selector);
JButton b = new JButton("+");
b.setToolTipText(UIStrings.SETTINGS_DIALOG_MARKDOWN_PROCESSOR_ADD);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
ExternalProcessor new_ep = dialog_settings.newProcessor(UIStrings.SETTINGS_DIALOG_DEFAULT_NEW_PROC_VALUES[0]);
new_ep.path = UIStrings.SETTINGS_DIALOG_DEFAULT_NEW_PROC_VALUES[1];
new_ep.options = UIStrings.SETTINGS_DIALOG_DEFAULT_NEW_PROC_VALUES[2];
processor_name_selector.addItem(new_ep);
processor_name_selector.setSelectedItem(new_ep);
processor_name_selector.setEnabled(true);
}
});
// d = b.getPreferredSize();
// d.width = 20;
// b.setPreferredSize(d);
ip.add(b);
b = new JButton("-");
b.setToolTipText(UIStrings.SETTINGS_DIALOG_MARKDOWN_PROCESSOR_REMOVE);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
ExternalProcessor ep = (ExternalProcessor)processor_name_selector.getSelectedItem();
int result = JOptionPane.showConfirmDialog(jp, "Remove Processor: " + ep.name + "?", UIStrings.APPNAME, JOptionPane.YES_NO_OPTION);
if(result == JOptionPane.NO_OPTION)
{
return;
}
processor_name_selector.removeItem(ep);
processor_name_selector.setSelectedIndex(0);
if(processor_name_selector.getItemCount() == 0)
{
processor_name_selector.setEnabled(false);
}
}
});
ip.add(b);
ip.add(Box.createHorizontalGlue());
setItemAlignment(ip);
jp.add(ip);
jp.add(Box.createVerticalStrut(10));
cp = new JLabel(UIStrings.UI_PROC_PATH_LABEL);
setItemAlignment(cp);
jp.add(cp);
ip = new JPanel(new FlowLayout(FlowLayout.LEFT));
processor_path_field = new JTextField(40);
processor_path_field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
ExternalProcessor ep = (ExternalProcessor)processor_name_selector.getSelectedItem();
ep.path = processor_path_field.getText();
}
});
ip.add(processor_path_field);
b = new JButton(folder_icon);
b.setToolTipText(UIStrings.SETTINGS_DIALOG_MARKDOWN_PROCESSOR_BROWSE_TOOLTIP);
b.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
JFileChooser fc = new JFileChooser();
int returnVal = fc.showDialog(null, "Select");
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file.exists() && file.isFile())
{
processor_path_field.setForeground(Color.BLACK);
}
else
{
processor_path_field.setForeground(Color.RED);
processor_path_field.setText(file.getAbsolutePath() + " [" + UIStrings.ERROR_INVALID_PATH + "]");
}
processor_path_field.setText(file.getAbsolutePath());
}
else
{
}
}
});
ip.add(b);
setItemAlignment(ip);
jp.add(ip);
jp.add(Box.createVerticalStrut(10));
cp = new JLabel(UIStrings.UI_PROC_OPTIONS_LABEL);
setItemAlignment(cp);
jp.add(cp);
ip = new JPanel(new FlowLayout(FlowLayout.LEFT));
processor_options_field = new JTextField(40);
processor_options_field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae)
{
ExternalProcessor ep = (ExternalProcessor)processor_name_selector.getSelectedItem();
ep.options = processor_options_field.getText();
}
});
ip.add(processor_options_field);
setItemAlignment(ip);
jp.add(ip);
return jp;
} |
7eb279a6-616a-48b1-ab76-18a6d7f62842 | 6 | private boolean fskFreqHalf (CircularDataBuffer circBuf,WaveData waveData,int pos) {
boolean out;
int sp=(int)samplesPerSymbol/2;
// First half
double early[]=doRTTYHalfSymbolBinRequest(baudRate,circBuf,pos,lowBin,highBin);
// Last half
double late[]=doRTTYHalfSymbolBinRequest(baudRate,circBuf,(pos+sp),lowBin,highBin);
// Feed the early late difference into a buffer
if ((early[0]+late[0])>(early[1]+late[1])) addToAdjBuffer(getPercentageDifference(early[0],late[0]));
else addToAdjBuffer(getPercentageDifference(early[1],late[1]));
// Calculate the symbol timing correction
symbolCounter=adjAdjust();
// Now work out the binary state represented by this symbol
double lowTotal=early[0]+late[0];
double highTotal=early[1]+late[1];
// Calculate the bit value
if (theApp.isInvertSignal()==false) {
if (lowTotal>highTotal) out=true;
else out=false;
}
else {
// If inverted is set invert the bit returned
if (lowTotal>highTotal) out=false;
else out=true;
}
// Is the bit stream being recorded ?
if (theApp.isBitStreamOut()==true) {
if (out==true) theApp.bitStreamWrite("1");
else theApp.bitStreamWrite("0");
}
return out;
} |
1c8efa65-7dc1-48f3-882f-73c7aa571e41 | 1 | public int getPieceCount() {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
return this.pieces.length;
} |
0c374b10-a417-4459-8c7f-f027f5f303dd | 4 | public void keyPressed(KeyEvent ke) {
char keyPressed = ke.getKeyChar();
if(!world.inBattle())
{
world.movePlayer(keyPressed);
world.blockAppear();
if(!world.inBattle())
{
if(world.isInStore()) {
_controlPanel.switchToMenu(ControlPanel.MenuType.ItemShop);
}
else if(world.isInHealingStation()) {
_controlPanel.switchToMenu(ControlPanel.MenuType.HealShop);
}
else {
_controlPanel.switchToMenu(ControlPanel.MenuType.OutOfBattle);
}
}
}
else
{
System.out.println("Player cannot move");
}
} |
2c22ab50-386b-496a-a53c-71b4bc6ad821 | 8 | private void RdesremActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RdesremActionPerformed
vtexto = Ctexto.getText();
DefaultTableModel tr = (DefaultTableModel)tabla.getModel();
try
{
Statement s = cone.getMiConexion().createStatement();
String consul="select * from correpo where edo_reg = 'A' and grupo = '"+Cgrupo+"' and des_rem like '%"+vtexto+"%'";
ResultSet rs = s.executeQuery(consul);
while (rs.next())
{
String var1 = rs.getString("id");
String var2 = (PROCE.verfecha(rs.getString("fecha_rec")));
String var3 = rs.getString("des_rem");
String var4 = rs.getString("codigo");
String var5 = rs.getString("nro_oficio");
tr.addRow(new Object[]{var1, var2, var3, var4, var5,});
tabla.setModel(tr);
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = tabla.getColumnModel().getColumn(i);
if (i == 0) {column.setPreferredWidth(0);}
if (i == 1) {column.setPreferredWidth(15);}
if (i == 2) {column.setPreferredWidth(250);}
if (i == 3) {column.setPreferredWidth(10);}
if (i == 4) {column.setPreferredWidth(10);}
}
}
}
catch (Exception e)
{
}
}//GEN-LAST:event_RdesremActionPerformed |
f4068072-fc12-460b-b70e-1c68defa4ad1 | 3 | public void onEnable()
{
if((citizensPlugin = (CitizensPlugin)Bukkit.getPluginManager().getPlugin("Citizens")) == null)
{
this.getLogger().log(Level.SEVERE, "Citizens not found. Disabling OWHQuests.");
Bukkit.getPluginManager().disablePlugin(this);
}
if((worldGuardPlugin = (WorldGuardPlugin)Bukkit.getPluginManager().getPlugin("WorldGuard")) == null)
{
this.getLogger().log(Level.SEVERE, "WorldGuard not found. Disabling OWHQuests.");
Bukkit.getPluginManager().disablePlugin(this);
}
p = new Permissions(this);
if(p.setupPermissions())
this.getLogger().info("Permissions setup successful.");
else
this.getLogger().warning("Permissions setup failed, falling back to OP-only for any permissions");
questPlugin = new OWHQuests(this);
Bukkit.getPluginManager().registerEvents(new BukkitListener(questPlugin), this);
} |
90526bc3-7bd9-4ac4-9579-0c9632835c6b | 5 | public void cleanNotDamaAvvicinando(){
//Se qualche dama si può avvicinare
//Elimino le mosse che spostano dame lontano da pedine o dame nemiche
if(haveSomeDamaAvvicinando()){
//Recupero il valore minimo di avvicinamento
int min = this.getMossaMinAvvicinando();
for(int i=0;i<desmosse.length;i++)
if(desmosse[i]!=null && desmosse[i].isDama() && desmosse[i].getAvvicinando() != min)
desmosse[i]=null;
}
} |
c8544af1-6c57-4a0c-8664-f7f17944c6fb | 8 | public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0)
return 0;
g=grid;
boolean[][] visited = new boolean[grid.length][grid[0].length];
for (int i=0; i<g.length; i++) {
for (int j=0; j<g[0].length; j++) {
visited[i][j] = false;
}
}
this.visited = visited;
int islands = 0;
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
islands++;
conquer(i,j);
}
}
}
return islands;
} |
f3adb912-a86b-4477-966c-7aa3e08f488c | 7 | public int transform(CtClass clazz, int pos, CodeIterator iterator,
ConstPool cp) throws CannotCompileException
{
int index;
int c = iterator.byteAt(pos);
if (c == NEW) {
index = iterator.u16bitAt(pos + 1);
if (cp.getClassInfo(index).equals(classname)) {
if (iterator.byteAt(pos + 3) != DUP)
throw new CannotCompileException(
"NEW followed by no DUP was found");
iterator.writeByte(NOP, pos);
iterator.writeByte(NOP, pos + 1);
iterator.writeByte(NOP, pos + 2);
iterator.writeByte(NOP, pos + 3);
++nested;
StackMapTable smt
= (StackMapTable)iterator.get().getAttribute(StackMapTable.tag);
if (smt != null)
smt.removeNew(pos);
}
}
else if (c == INVOKESPECIAL) {
index = iterator.u16bitAt(pos + 1);
int typedesc = cp.isConstructor(classname, index);
if (typedesc != 0 && nested > 0) {
int methodref = computeMethodref(typedesc, cp);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(methodref, pos + 1);
--nested;
}
}
return pos;
} |
8f6df1ce-e126-48b3-bbde-12afd29df53a | 0 | public void setPrezzo(Float prezzo) {
this.prezzo = prezzo;
} |
c8bffd8a-a367-4f19-8ff8-9ef5febe37ef | 2 | public void showNotificationsToFile(FileWriter f) throws IOException {
for (TimedPosts post : notifications) {
long elapsedTimeInSec = (endTime - post.getTime()) / 1000000000;
endTime += 1000000000;
if (elapsedTimeInSec < 60) {
int elapsedTime = (int) elapsedTimeInSec;
f.write(post.getPost() + "(" + elapsedTime
+ " seconds ago)\n");
} else {
int elapsedTime = (int) (elapsedTimeInSec / 60);
f.write(post.getPost() + "(" + elapsedTime
+ " minutes ago)\n");
}
}
} |
56dd30c9-bb48-478e-8d3d-ffb40ac24f40 | 4 | public void setData(int row, int col, String data) {
if (row < 0
|| col < 0
|| row > (getRowsCount() - 1)
|| col > (getColsCount() - 1)) {
throw new IndexOutOfBoundsException();
}
Vector theRow = (Vector)m_fileContent.get(row);
theRow.setElementAt(data, col);
} |
302953fe-6157-4571-aed0-b63f42992e3e | 7 | static void mainToOutput(String[] args, PrintWriter output) throws Exception {
if (!parseArgs(args)) {
return;
}
AdaptiveLogisticModelParameters lmp = AdaptiveLogisticModelParameters
.loadFromFile(new File(modelFile));
CsvRecordFactory csv = lmp.getCsvRecordFactory();
csv.setIdName(idColumn);
AdaptiveLogisticRegression lr = lmp.createAdaptiveLogisticRegression();
State<Wrapper, CrossFoldLearner> best = lr.getBest();
if (best == null) {
output.printf("%s\n",
"AdaptiveLogisticRegression has not be trained probably.");
return;
}
CrossFoldLearner learner = best.getPayload().getLearner();
BufferedReader in = TrainAdaptiveLogistic.open(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
out.write(idColumn + ",target,score");
out.newLine();
String line = in.readLine();
csv.firstLine(line);
line = in.readLine();
Map<String, Double> results = new HashMap<String, Double>();
int k = 0;
while (line != null) {
Vector v = new SequentialAccessSparseVector(lmp.getNumFeatures());
csv.processLine(line, v, false);
Vector scores = learner.classifyFull(v);
results.clear();
if (maxScoreOnly) {
results.put(csv.getTargetLabel(scores.maxValueIndex()),
scores.maxValue());
} else {
for (int i = 0; i < scores.size(); i++) {
results.put(csv.getTargetLabel(i), scores.get(i));
}
}
for (Map.Entry<String,Double> entry : results.entrySet()) {
out.write(csv.getIdString(line) + ',' + entry.getKey() + ',' + entry.getValue());
out.newLine();
}
k++;
if (k % 100 == 0) {
output.printf(Locale.ENGLISH, "%d records processed \n", k);
}
line = in.readLine();
}
out.flush();
out.close();
output.printf(Locale.ENGLISH, "%d records processed totally.\n", k);
} |
4083557d-2fd1-49ee-a115-00c8ff782c6f | 9 | public void addNum(int val) {
Node node = new Node(val);
if(!treeSet.add(node)) return;
Node prev = treeSet.lower(node);
Node next = treeSet.higher(node);
if (prev != null) {
node.prev = prev;
prev.next=node;
if (prev.value == val - 1) {
node.seqPrev = prev.seqPrev;
prev.seqPrev.seqNext=node;
if( next!=null && next.value==val+1){
prev.seqPrev.seqNext=next.seqNext;
}
}
}
if (next != null) {
node.next = next;
next.prev=node;
if (next.value == val + 1) {
node.seqNext = next.seqNext;
next.seqNext.seqPrev=node;
if(prev!=null && prev.value==val-1){
next.seqNext.seqPrev=prev.seqPrev;
}
}
}
} |
610b7d94-521f-41d0-bd2a-4a6b94a04e44 | 6 | public byte[] packData() throws IOException {
ExtendedByteArrayOutputStream out = new ExtendedByteArrayOutputStream();
out.putShort(this.indexOffset);
for (ImageBean i : this.imageBeans) {
int[] pixels = i.getPixels();
if (this.packType == 0) {
for (int x = 0; x < pixels.length; x++)
out.write(findPosInMap(pixels[x]));
}
else if (this.packType == 1) {
for (int x = 0; x < i.getWidth(); x++) {
for (int y = 0; y < i.getHeight(); y++) {
out.write(findPosInMap(pixels[(x + y * i.getWidth())]));
}
}
}
}
byte[] ret = out.toByteArray();
out.close();
return ret;
} |
f8d2b488-63c8-49eb-9ee0-897d993cda4d | 0 | public void servere(String message) {
log(Level.SEVERE, message);
} |
41a60d3a-22f1-45d8-840d-5e8ec5d7fc42 | 7 | public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
boolean isPressed = getModel().isPressed();
boolean isRollover = getModel().isRollover();
int width = getWidth();
int height = getHeight();
Color[] tc = AbstractLookAndFeel.getTheme().getThumbColors();
Color c1 = tc[0];
Color c2 = tc[tc.length - 1];
if (isPressed) {
c1 = ColorHelper.darker(c1, 5);
c2 = ColorHelper.darker(c2, 5);
} else if (isRollover) {
c1 = ColorHelper.brighter(c1, 20);
c2 = ColorHelper.brighter(c2, 20);
}
g2D.setPaint(new GradientPaint(0, 0, c1, width, height, c2));
g.fillRect(0, 0, width, height);
g2D.setPaint(null);
g2D.setColor(Color.white);
if (JTattooUtilities.isLeftToRight(this)) {
g2D.drawRect(1, 0, width - 2, height - 1);
} else {
g2D.drawRect(0, 0, width - 2, height - 1);
}
Composite composite = g2D.getComposite();
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2D.setComposite(alpha);
g2D.setColor(c2);
if (JTattooUtilities.isLeftToRight(this)) {
g.drawLine(2, 1, width - 2, 1);
g.drawLine(2, 2, 2, height - 2);
} else {
g.drawLine(1, 1, width - 3, 1);
g.drawLine(1, 2, 1, height - 2);
}
g2D.setComposite(composite);
// paint the icon
Icon icon = LunaIcons.getComboBoxIcon();
int x = (width - icon.getIconWidth()) / 2;
int y = (height - icon.getIconHeight()) / 2;
int dx = (JTattooUtilities.isLeftToRight(this)) ? 0 : -1;
if (getModel().isPressed() && getModel().isArmed()) {
icon.paintIcon(this, g, x + dx + 2, y + 1);
} else {
icon.paintIcon(this, g, x + dx + 1, y);
}
} |
c43601b5-7b61-45f3-86a4-d47117873db9 | 8 | public static void handleEvent(int eventId)
{
// Changes focus to Main Ship Shop Menu
if(eventId == 1)
{
System.out.println("Exit Ship Shop Weapons menu to Main Ship Shop Menu selected");
Main.ShipShopWeaponsMenu.setVisible(false);
Main.ShipShopWeaponsMenu.setEnabled(false);
Main.ShipShopWeaponsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopWeaponsMenu);
Main.mainFrame.add(Main.ShipShopMenu);
Main.ShipShopMenu.setVisible(true);
Main.ShipShopMenu.setEnabled(true);
Main.ShipShopMenu.setFocusable(true);
Main.ShipShopMenu.requestFocusInWindow();
}
// Do nothing because same screen selected
else if(eventId == 2)
{
System.out.println("Exit Ship Shop Weapons menu to Engines Ship Shop Menu selected");
Main.ShipShopWeaponsMenu.setVisible(false);
Main.ShipShopWeaponsMenu.setEnabled(false);
Main.ShipShopWeaponsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopWeaponsMenu);
Main.mainFrame.add(Main.ShipShopEnginesMenu);
Main.ShipShopEnginesMenu.setVisible(true);
Main.ShipShopEnginesMenu.setEnabled(true);
Main.ShipShopEnginesMenu.setFocusable(true);
Main.ShipShopEnginesMenu.requestFocusInWindow();
}
else if(eventId == 3)
{
System.out.println("Exit Ship Shop Weapons menu to Hulls Ship Shop Menu selected");
Main.ShipShopWeaponsMenu.setVisible(false);
Main.ShipShopWeaponsMenu.setEnabled(false);
Main.ShipShopWeaponsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopWeaponsMenu);
Main.mainFrame.add(Main.ShipShopHullsMenu);
Main.ShipShopHullsMenu.setVisible(true);
Main.ShipShopHullsMenu.setEnabled(true);
Main.ShipShopHullsMenu.setFocusable(true);
Main.ShipShopHullsMenu.requestFocusInWindow();
}
else if(eventId == 4)
{
System.out.println("Exit Ship Shop Weapons menu to Thrusters Ship Shop Menu selected");
Main.ShipShopWeaponsMenu.setVisible(false);
Main.ShipShopWeaponsMenu.setEnabled(false);
Main.ShipShopWeaponsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopWeaponsMenu);
Main.mainFrame.add(Main.ShipShopThrustersMenu);
Main.ShipShopThrustersMenu.setVisible(true);
Main.ShipShopThrustersMenu.setEnabled(true);
Main.ShipShopThrustersMenu.setFocusable(true);
Main.ShipShopThrustersMenu.requestFocusInWindow();
}
else if(eventId == 5)
{
}
else if(eventId == 6)
{
}
else if(eventId == 7)
{
}
else if(eventId == 8)
{
System.out.println("Exit Ship Shop Weapons menu to Main Menu selected");
Main.ShipShopWeaponsMenu.setVisible(false);
Main.ShipShopWeaponsMenu.setEnabled(false);
Main.ShipShopWeaponsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopWeaponsMenu);
Main.mainFrame.add(Main.mainMenu);
Main.mainMenu.setVisible(true);
Main.mainMenu.setEnabled(true);
Main.mainMenu.setFocusable(true);
Main.mainMenu.requestFocusInWindow();
}
} |
065c6fd0-b3bf-458a-8acf-d4ef4d1b1799 | 5 | private boolean transaccionBancaria(int cc,double m,Transaccion tp) throws IOException{
if( buscar(cc) ){
rCuentas.readInt();
rCuentas.readUTF();
long pos = rCuentas.getFilePointer();
double s = rCuentas.readDouble();
rCuentas.readLong();
if( tp == Transaccion.RETIRO && s < m ){
System.out.println("Saldos Insuficientes");
return false;
}
if( !rCuentas.readBoolean() ){
addTransaccion(cc,m*0.1, Transaccion.ACTIVACION);
m -= m * 0.1;
}
//depositar o retirar
addTransaccion(cc, m, tp);
//actualizar cuenta
rCuentas.seek(pos);
rCuentas.writeDouble(s + (tp == Transaccion.DEPOSITO ? m : -m));
rCuentas.writeLong( new Date().getTime() );
rCuentas.writeBoolean(true);
return true;
}
return false;
} |
a6e747e6-2475-4578-bdf6-a30ae577ac92 | 6 | private static boolean modifyEmployee(Employee bean, PreparedStatement stmt, String field) throws SQLException{
String sql = "UPDATE employees SET "+field+"= ? WHERE username = ?";
stmt = conn.prepareStatement(sql);
if(field.toLowerCase().equals("pass"))
stmt.setString(1, bean.getPass());
if(field.toLowerCase().equals("phone"))
stmt.setString(1, bean.getPhone());
if(field.toLowerCase().equals("address"))
stmt.setString(1, bean.getAddress());
if(field.toLowerCase().equals("email"))
stmt.setString(1, bean.getEmail());
if(field.toLowerCase().equals("position"))
stmt.setString(1, bean.getPosition());
stmt.setString(2, bean.getUsername());
int affected = stmt.executeUpdate();
if (affected == 1) {
System.out.println("employee info updated");
return true;
} else {
System.out.println("error: no update applied");
return false;
}
} |
d6d14b9d-3629-4801-ba68-b14a3493adfd | 0 | protected Element createStateElement(Document document, State state, Automaton container)
{
// System.out.println("moore create state element called");
Element se = super.createStateElement(document, state, state.getAutomaton());
se.appendChild(createElement(document, STATE_OUTPUT_NAME, null,
((MooreMachine) state.getAutomaton()).getOutput(state)));
return se;
} |
dc3f04ef-eb0d-4817-85b7-b9130d8f4d89 | 8 | public ListNode reverseKGroup(ListNode head, int k) {
if (k <= 1 || head == null || head.getNext() == null) {
return head;
}
ListNode prev = new ListNode(0);
prev.setNext(head);
head = prev;
//find current position
ListNode cur = prev.getNext();
//move k steps
while (cur != null) {
int counter = k;
while (cur != null && counter > 1) {
cur = cur.getNext();
counter--;
}
//if not reach the end
if (cur != null) {
cur = prev.getNext();
counter = k;
//switch
while (counter > 1) {
ListNode temp = cur.getNext();
cur.setNext(temp.getNext());
temp.setNext(prev.getNext());
prev.setNext(temp);
counter--;
}
prev = cur;
cur = prev.getNext();
}
}
return head.getNext();
} |
81a3781f-0314-4880-b7ae-8d87212462d0 | 5 | public static int firstIndexOfSubstring(String s, String p) {
int firstIndex = 0;
int lastIndex = 0;
while(lastIndex < s.length()) {
// If there is an initial match, update firstIndex.
if(s.charAt(lastIndex) == p.charAt(0))
firstIndex = lastIndex;
// If we have searched beyond the length of the pattern
// or the pattern stopped matching, reset firstIndex.
else if(lastIndex-firstIndex >= p.length() || s.charAt(lastIndex) != p.charAt(lastIndex-firstIndex))
firstIndex = -1;
// If everything checks and the last character of the pattern
// is the same as the current string index, we've found
// the first occurence.
else if(s.charAt(lastIndex) == p.charAt(p.length()-1))
return firstIndex;
lastIndex++;
}
return firstIndex;
} |
51c1f286-b30a-43e0-bd39-c9c91a28a1bd | 1 | public void pushBack() {
if (ttype != TT_NOTHING) /* No-op if nextToken() not called */
pushedBack = true;
} |
168de6e1-c1c6-4508-ac4b-a2dabbf48f53 | 1 | public static FileConfiguration getChannels() {
if (Channels == null) {
reloadChannels();
}
return Channels;
} |
2c5c86ca-d596-4375-a4ed-96792ce752da | 8 | public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[4];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 0; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 4; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
} |
d7ad775e-69af-42ff-acf6-eb2ae4c2e2d5 | 7 | @SuppressWarnings("unchecked")
static private void createNextLevel( final RowData rowData, final String path,
final Data data, final SelectionManager selectionManager) {
if(data.isPlain()) {
String value = data.valueToString();
rowData.setValue(value);
}
else {
if( data.isList()) { // kein Array
Iterator it = data.iterator();
while(it.hasNext()) {
Data nextData = (Data)it.next();
final RowData nextRowData = getNextRowData(nextData, path, selectionManager);
rowData.addArrayElement(nextRowData);
}
}
if(data.isArray()) { // ein Array
rowData.setIsArray(true);
Data.Array dataArray = data.asArray();
for(int i = 0, n = dataArray.getLength(); i < n; i++) {
Data nextData = dataArray.getItem(i);
RowSuccessor succ = new RowSuccessor();
String elementPath = path + "[" + i + "]";
succ.setKey(new CellKey(elementPath, false));
if(nextData.isList()) {
Iterator it = nextData.iterator();
while(it.hasNext()) {
Data nextNextData = (Data)it.next();
RowData nextRowData = getNextRowData(nextNextData, elementPath, selectionManager);
succ.addSuccessor(nextRowData);
}
}
else { // keine Liste
final RowData nextRowData = getNextRowData(nextData, path, selectionManager);
succ.addSuccessor(nextRowData);
}
rowData.addArrayElement(succ);
}
}
}
} |
00a6b13e-930b-43a0-b63a-6897ce6acf18 | 6 | public void run() {
byte[] buffer = new byte[5000];
DatagramPacket packet;
try {
//Create a socket
MulticastSocket socket = new MulticastSocket(port+1);
InetAddress address = InetAddress.getByName("224.0.0.31");
socket.joinGroup(address);
while (true) {
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); // Will wait until new packet received - Hence separate thread
if(firstRun) {
firstRun = false;
//Create thread to handle socket send
new ClientSendThread(packet.getAddress(), this, client).start();
}
ByteArrayInputStream bais=new ByteArrayInputStream(buffer);
ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(bais));
Packet pkt = (Packet)ois.readObject();
//Check the packet type - perform action based on this
if(pkt instanceof PointPacket) {
//Send packet to Canvas
canvas.drawPoints((PointPacket)pkt);
}
if(pkt instanceof ChatPacket) {
if(!((ChatPacket)pkt).get_sender().equals("KEEPALIVE")) {
chat.drawMessage((ChatPacket)pkt);
}
}
}
} catch (Exception e) {
System.err.println("Exception");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.