text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static boolean discoverMissingValues(ArrayList<LearningObject> learningSet, ArrayList<Attribute> attributes, ArrayList<ClassCategory> classes){
//apply algorithm if and only in only one attribute has missing values in learning set
//let the class become ordinary attribute
//new classes from attribute that has an unknown
//the position of the unknown attribute
int pos = -2;
//do algorithm to build tree;
Nod nod = new Nod();
//Find missing attribute
for(int i=0;i<learningSet.size();i++){
for(int j=0; j<learningSet.get(i).values.size(); j++){
if(learningSet.get(i).values.get(j).isUndefined()){
pos = j;
break;
}
}
}
if(pos >= 0){
ArrayList<LearningObject> undefinedSet = new ArrayList<LearningObject>();
ArrayList<LearningObject> definedSet = new ArrayList<LearningObject>();
for(int j=0;j<learningSet.size();j++){
if(learningSet.get(j).values.get(pos).isUndefined()){
//for the sets that have there value undefineD classify it
undefinedSet.add(learningSet.get(j));
}
else
definedSet.add(learningSet.get(j));
}
System.out.println("Pos : " + pos);
//create new sets
ArrayList<Attribute> newAttributes = createNewAttributeSet(pos, attributes, classes);
ArrayList<ClassCategory> newClasses = createNewClasses(attributes.get(pos), definedSet);
ArrayList<LearningObject> newLearningSet = createNewLearningSet(pos, definedSet);
ArrayList<LearningObject> findValuesSet = createNewLearningSet(pos, undefinedSet);
//discretizare atribute
discretizeNumericAttributesProcessClass(newLearningSet, newAttributes);
//do algorithm
algorithm(newLearningSet, newAttributes, newClasses, nod);
//String display = "";
//printClassificationRules(nod, 0, display);
//System.out.println("Rules should have been showned");
//find out values by classifying learnObject that has undefined value
ArrayList<String> missingValues = classifySet(nod, findValuesSet);
for(int j=0;j<missingValues.size(); j++){
System.out.println(" Discovered missing value :" + missingValues.get(j) + ": ");
undefinedSet.get(j).values.get(pos).setValue(missingValues.get(j));
}
return true;
}
return false;
} | 7 |
private static boolean onlyDigits(String s) {
if (s == null || s.length() == 0) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
} | 5 |
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
} | 3 |
public void uimsg(String msg, Object... args) {
if(msg == "p") {
text = Text.renderf(FlowerMenu.pink, "%d%%", (Integer)args[0]);
} else {
super.uimsg(msg, args);
}
} | 1 |
public void writeTwoBools(boolean[] tree, boolean[] message) throws IOException {
LinkedList<Boolean> boolList = new LinkedList<Boolean>();
for(boolean b : tree)
boolList.add(b);
for(boolean b : message)
boolList.add(b);
ArrayList<Byte> byteBuffer = new ArrayList<Byte>();
int length = tree.length + message.length;
// Create left-padded first byte
byte firstByte = 0;
for(int i = 0; i < length % 8; i++) {
firstByte <<= 1;
if (boolList.removeFirst())
firstByte |= 1;
}
byteBuffer.add(firstByte);
while(!boolList.isEmpty()) {
byte thisByte = 0;
for(int i = 0; i < 8; i++) {
thisByte <<= 1;
if (boolList.removeFirst())
thisByte |= 1;
}
byteBuffer.add(thisByte);
}
byte[] bytes = new byte[byteBuffer.size()];
for(int i = 0; i < byteBuffer.size(); i++) {
bytes[i] = byteBuffer.get(i);
}
super.write(bytes);
} | 8 |
public void mousePressed() {
Marker hitMarker = map.getFirstHitMarker(mouseX, mouseY);
if (hitMarker != null) {
pointedState = hitMarker.getProperties().get("NAME").toString();
for (int i = 0; i < climateArray.length; i++) {
if (hitMarker.getProperties().get("NAME").toString()
.equalsIgnoreCase(climateArray[i].getState())) {
temp = climateArray[i].getTempC();
totalViolent = totalViolentCrime(pointedState);
totalProperty = totalPropertyCrime(pointedState);
totalMurder = totalMurderCrime(pointedState);
totalRape = totalRape(pointedState);
totalRobbery = totalRobbery(pointedState);
totalAssault = totalAggravatedAssault(pointedState);
totalBurglary = totalBurglary(pointedState);
totalTheft = totalTheft(pointedState);
totalVehicleTheft = totalVehicleTheft(pointedState);
}
}
for (int i = 0; i < popArray.length; i++) {
if (hitMarker.getProperties().get("NAME").toString()
.equalsIgnoreCase(popArray[i].getState())) {
population = popArray[i].getAverage();
// if (selectedYear.equalsIgnoreCase("2000"))
// population = popArray[i].getP0();
// else if (selectedYear.equalsIgnoreCase("2001"))
// population = popArray[i].getP1();
// else if (selectedYear.equalsIgnoreCase("2002"))
// population = popArray[i].getP2();
// else if (selectedYear.equalsIgnoreCase("2003"))
// population = popArray[i].getP3();
// else if (selectedYear.equalsIgnoreCase("2004"))
// population = popArray[i].getP4();
// else if (selectedYear.equalsIgnoreCase("2005"))
// population = popArray[i].getP5();
}
}
hitMarker.setSelected(true);
}
// else {
// for (Marker marker : map.getMarkers()) {
// marker.setSelected(false);
// }
// }
} | 5 |
public static void main(String[] args)
{
if (args.length == 1)
{
try
{
chargenTCP(args[0]);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
else if (args.length == 2 && args[0].equals("-udp"))
{
try
{
chargenUDP(args[1]);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
else
{
System.err.println("Usage: chargen [-udp] <hostname>");
System.exit(1);
}
} | 5 |
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
String redirectUrl = obtainRedercitUrl(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
//自定义回调URL,若存在则放入Session
if(redirectUrl != null && !"".equals(redirectUrl)){
request.getSession().setAttribute("callCustomRediretUrl", redirectUrl);
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
} | 6 |
public void go()
{
do
{
play();
} while(check());
turnInfo();
gameInfo();
} | 1 |
private static Class getClassMatchingAllChildren(OgnlContext context, Node[] _children) {
Class[] cc = getChildrenClasses(context, _children);
Class componentType = null;
for (int j = 0; j < cc.length; j++) {
Class ic = cc[j];
if (ic == null) {
componentType = Object.class; // fall back to object...
break;
} else {
if (componentType == null) {
componentType = ic;
} else {
if (!componentType.isAssignableFrom(ic)) {
if (ic.isAssignableFrom(componentType)) {
componentType = ic; // just swap... ic is more generic...
} else {
Class pc;
while ((pc = componentType.getSuperclass()) != null) { // TODO hmm - it could also be that an interface matches...
if (pc.isAssignableFrom(ic)) {
componentType = pc; // use this matching parent class
break;
}
}
if (!componentType.isAssignableFrom(ic)) {
// parents didn't match. the types might be primitives. Fall back to object.
componentType = Object.class;
break;
}
}
}
}
}
}
if (componentType == null)
componentType = Object.class;
return componentType;
} | 9 |
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((buildingI!=null)&&(!aborted))
{
amountMaking=amountMaking*(baseYield()+abilityCode());
if(messedUp)
commonEmote(mob,L("<S-NAME> ruin(s) @x1!",buildingI.name()));
else
for(int i=0;i<amountMaking;i++)
{
final Item copy=(Item)buildingI.copyOf();
copy.setMiscText(buildingI.text());
copy.recoverPhyStats();
if(!dropAWinner(mob,copy))
break;
}
}
buildingI=null;
}
}
super.unInvoke();
} | 7 |
@EventHandler
public void EnderDragonHarm(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.Harm.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Harm.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getEnderDragonConfig().getInt("EnderDragon.Harm.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Harm.Power")));
}
} | 6 |
public void addEffectsToGrid(List<Effect> effects) {
if (effects == null)
throw new IllegalArgumentException("Effects can't be null!");
for (Effect effect : effects) {
addEffectToGrid(effect);
}
} | 2 |
public void testGet() {
MonthDay test = new MonthDay();
assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
assertEquals(9, test.get(DateTimeFieldType.dayOfMonth()));
try {
test.get(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.get(DateTimeFieldType.year());
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
public double[][] Dmxm(double a[][], double b[][]) {
double w;
double c[][] = new double[3][3];
TRACE("Dmxm");
/* Multiply into scratch matrix */
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
w = 0.0;
for (int k = 0; k < 3; k++) {
w += a[i][k] * b[k][j];
}
c[i][j] = w;
}
}
ENDTRACE("Dmxm");
return c;
} | 3 |
public void getBytes(int len, int off, byte buf[]) { // readBytes
for (int i = off; i < off + len; i++) {
buf[i] = payload[offset++];
}
} | 1 |
public static void main(String[] args) {
if(args.length != 2) {
System.err.println("Syntax: RemoteControl <target IP> <command>");
System.exit(1);
}
String ip = args[0];
String cmd = args[1];
checkIP(ip);
// Send the command to the other side.
try {
Socket sock = new Socket(ip, 42000);
OutputStream out = sock.getOutputStream();
out.write(cmd.getBytes());
out.flush();
final InputStream in = sock.getInputStream();
if(cmd.replaceAll("music ", "").equals("monitor")) {
new Thread(new Runnable() {
public void run() {
try {
while(true) {
byte[] buf = new byte[256];
in.read(buf);
String s = new String(buf).trim();
if(s.equals("CLOSETHREAD")) {
break;
}
if(!s.isEmpty()) {
String[] commands = new String[]{"/usr/local/bin/growlnotify", "-t", "New song", "-m", s};
Process child = Runtime.getRuntime().exec(commands);
}
}
} catch (UnknownHostException ex) {
System.err.println("Unknown Host!");
ex.printStackTrace();
} catch (IOException ex) {
System.err.println("IO Exception!");
ex.printStackTrace();
}
}
}).start();
}
} catch (UnknownHostException ex) {
System.err.println("Unknown Host!");
} catch (IOException ex) {
System.err.println("IO Exception!");
}
} | 9 |
public String stSendEmailWithCaptcha(int dataId,int ExpVal,String flow )
{
int actVal=1000;
String returnVal=null;
hm.clear();
hm=STFunctionLibrary.stMakeData(dataId, "Email");
String action = hm.get("Action");
STCommonLibrary comLib=new STCommonLibrary();
Vector<String> xPath=new Vector<String>();
Vector<String> errorMsg=new Vector<String>();
String successmsg = null;
String captchatext = null;
try {
xPath.add(EMAIL_CANCEL_BUTTON);
errorMsg.add("Cancel button is not present");
xPath.add(EMAIL_SEND_BUTTON);
errorMsg.add("Send Button is not present");
comLib.stVerifyObjects(xPath, errorMsg, "STOP");
xPath.clear();
errorMsg.clear();
Block:
{
/*Click on Send or Cancel Button*/
if ("Send".equalsIgnoreCase(action))
{
comLib.stClick(EMAIL_SEND_BUTTON, "Send Button is not present", "STOP");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
xPath.add(EMAIL_CAPTCHA);
errorMsg.add("Captcha is not present");
xPath.add(EMAIL_CAPTCHA_TEXT);
errorMsg.add("Captcha text is not present");
xPath.add(EMAIL_CAPTCHA_INSERT_FIELD);
errorMsg.add("Captcha field is not present");
comLib.stVerifyObjects(xPath, errorMsg, "STOP");
xPath.clear();
errorMsg.clear();
/*Checking if Error msg occurs*/
captchatext = browser.getText(EMAIL_CAPTCHA_TEXT);
System.out.println("Text : "+ captchatext);
browser.type(EMAIL_CAPTCHA_INSERT_FIELD, captchatext);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*IF no Error Occurs*/
if (browser.isElementPresent(EMAIL_CAPTCHA_SUBMIT_BUTTON))
{
comLib.stClick(EMAIL_SEND_BUTTON, "Send Button is not present", "STOP");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
comLib.stWaitForElement(EMAIL_SUCCESS_MSG, 20);
successmsg = browser.getText(EMAIL_SUCCESS_MSG);
if(successmsg.contains("Your message was successfully shared!"))
{
actVal= 0; /*Email send successfully with Captcha.*/
break Block;
}
else
{
actVal= 2; /*Failed to Send email with Captcha.*/
break Block;
}
}
}
else if ("Cancel".equalsIgnoreCase(action))
{
comLib.stClick(EMAIL_CANCEL_BUTTON, "Cancel Button is not present", "STOP");
{
actVal= 1; /*Email Cancel successfully.*/
break Block;
}
}
}
}
catch (SeleniumException sexp)
{
Reporter.log(sexp.getMessage());
}
returnVal=STFunctionLibrary.stRetValDes(ExpVal, actVal, "stSendEmailWithCaptcha",flow, hm);
if(flow.contains("STOP")){
assertEquals("PASS",returnVal);
}
return returnVal;
} | 9 |
public String getFromDate() {
return fromDate;
} | 0 |
public void download() {
// This is the core web/download i/o code...
InputStream input = null;
StringBuilder contents = null;
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
// Set connect() to throw an IOException
// if connection does not succeed in this many msecs.
connection.setConnectTimeout(5000);
connection.connect();
input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
char[] array = new char[1000];
int len;
contents = new StringBuilder(1000);
while ((len = reader.read(array, 0, array.length)) > 0) {
contents.append(array, 0, len);
Thread.sleep(100);
}
bytes = contents.length();
// System.out.println("Nice!");
t_end = System.currentTimeMillis();
String dwnStr = "";
dwnStr += getTime() + " ";
dwnStr += getElapsed() + " ms ";
dwnStr += bytes + " bytes";
updateModel(dwnStr);
// Successful download if we get here
}
// Otherwise control jumps to a catch...
catch(MalformedURLException ignored) {
// System.out.println("Malformed Address");
updateModel("err: malformed address");
}
catch(InterruptedException exception) {
// deal with interruption
updateModel("interrupted");
}
catch(IOException ignored) {
// System.out.println("Website does not exist");
updateModel("err: website does not exist");
}
// "finally" clause, to close the input stream
// in any case
finally {
try{
if (input != null) input.close();
}
catch(IOException ignored) {}
}
} | 6 |
@Override
public String execute() {
if (databaseContext.table == null) {
return "no table";
}
try {
Storeable storeable = ((DataBase) databaseContext.table).putStoreable(arguments.get(1), jsonStr);
if (storeable == null) {
return "new";
} else {
return "overwrote \n" + databaseContext.provider.serialize(databaseContext.table, storeable);
}
} catch (ParseException e) {
return "Wrong type " + e.getMessage();
}
} | 3 |
@Override
public void initializeEdge() {
// TODO Auto-generated method stub
super.initializeEdge();
double dist = startNode.getPosition().distanceTo(endNode.getPosition());
//System.out.println("Distancia na edge: "+dist);
if(dist < 399){
setParam(0.001f, 0.24f, 11.f);
return;
}
if(dist >= 399 && dist < 531){
setParam(0.25f, 0.49f, 5.5f);
return;
}
if(dist >= 531 && dist < 669){
setParam(0.50f, 0.74f, 2.f);
return;
}
if(dist >= 669 && dist <= 796){
setParam(0.75f, 0.99f, 1.f);
return;
}
} | 7 |
public static Texture2D load2DTexture(URI uri) {
BufferedInputStream bis = null;
ByteBuffer texCoords = null;
try {
File file = new File(uri);
//Idiot checking
if(!file.exists() || !file.isFile()) {
System.err.println("File doesn't exist or was not a File, aborting!");
return null;
}
//Set up the BufferedInputStream
bis = new BufferedInputStream(new FileInputStream(file)); //get the InputStream
//Set up the ByteBuffer
texCoords = BufferUtils.createByteBuffer(12); //The default is 12, use an overloaded method to custom define this default
texCoords.put(new byte[] {0,0, 1,0, 1,1, 1,1, 0,1, 0,0}).flip(); //The default. Again, Overloaded Constructor to deine this
return new Texture2D(bis, texCoords); //Set up the Texture
} catch(Exception e) {
System.err.println("An Exception was thrown while loading the Texture!");
e.printStackTrace();
return null;
}
} | 3 |
public static void shop(Character character, Scanner console) throws FileNotFoundException {
System.out.println();
character.getInventoryManager().printInventory(); //////////
System.out.println("Welcome to the shop. Feel free to browse.");
System.out.print("Would you like to buy, sell, or exit? ");
Scanner num = new Scanner(System.in);
String response = console.nextLine();
System.out.println();
if(response.toLowerCase().startsWith("buy")) {
System.out.println("Here's what we have in stock right now.");
Shop shop = new Shop(character.getLevel());
shop.printShop();
System.out.println("Your current Money: " + character.getMoney());
System.out.print("What would you like to buy? Please enter the number corresponding with the item's index: ");
int index = num.nextInt();
if(index <= shop.getMerchandise().length && index > -1) {
if(character.buy(shop.getMerchandise()[index - 1]) == true) {
System.out.println("Ah! A fine choice!");
character.getInventoryManager().addItem(shop.getMerchandise()[index - 1]);
System.out.println("Anything else for today?");
shop(character, console);
} else {
System.out.println("I'm sorry. You dont seem to have enough money for that item.");
shop(character, console);
}
} else {
System.out.println("There's nothing there, fool.");
shop(character, console);
}
} else if(response.toLowerCase().startsWith("sel")) {
System.out.println("Here's what ya got on you. ");
character.getInventoryManager().printInventory();
System.out.println();
if (character.getInventoryManager().getInventory()[0] != null) {
System.out.print("What item would you like to sell? Enter an index: ");
int sell = num.nextInt();
if(sell >= character.getInventoryManager().getInventory().length) {
if(character.getInventoryManager().getInventory()[sell - 1] != null) {
character.sellItem(character.getInventoryManager().getInventory()[sell - 1], sell);
System.out.println("Thank you. Someone else will want this.");
System.out.println("You now have $" + character.getMoney());
System.out.println("Can I do anything else for you?");
shop(character, console);
} else {
System.out.println("That index seems to be empty.");
shop(character, console);
}
} else {
System.out.println("There's nothing there, fool.");
shop(character, console);
}
} else {
shop(character, console);
}
} else if(response.toLowerCase().startsWith("exi")) {
System.out.println("Stop in again soon. Next time bring your friends.");
town(character, console);
} else {
System.out.println("Sorry, I dont understand. What do you want to do?");
shop(character, console);
}
} | 9 |
public void windowClosed(WindowEvent e) {
System.out.println("Die Anwendung wurde geschlossen...");
} | 0 |
public static void main(String[] args) {
ArrayList<Card> cardsAvalible = addCards();
ArrayList<Card> randDeck;
double trials = 500;
double avgTurns;
double bestAvgTurns = 20;
while(true){
Deck d1 = new Deck();
d1.randomDeck((ArrayList<Card>) cardsAvalible.clone());
randDeck = d1.getCardList();
avgTurns = simulateDeck(randDeck, trials);
if(avgTurns < bestAvgTurns){
System.out.println("\nNew Best Deck Found! Average Win " + avgTurns + " Turns!");
bestAvgTurns = avgTurns;
Collections.sort(randDeck);
for(Card c : randDeck)
System.out.print(c.toString() + ", ");
}
}
} | 3 |
protected void writeData(XMLStreamWriter writer, Grid<?> s) throws XMLStreamException {
writer.writeStartDocument();
writer.writeStartElement("VTKFile");
writer.writeAttribute("type", "ImageData");
writer.writeStartElement("ImageData");
writer.writeAttribute("WholeExtent", "0 " + (s.getRange(0)) + " 0 " + (s.getRange(1)) + " 0 1");
writer.writeAttribute("Origin", "0 0 0");
writer.writeAttribute("Spacing", "1 1 1");
writer.writeStartElement("Piece");
writer.writeAttribute("Extent", "0 " + (s.getRange(0)) + " 0 " + (s.getRange(1)) + " 0 1");
writer.writeStartElement("PointData");
writer.writeEndElement();
writer.writeStartElement("CellData");
writer.writeStartElement("DataArray");
writer.writeAttribute("Name", "CellState");
writer.writeAttribute("type", "Int8");
writer.writeAttribute("name", "cells");
writer.writeAttribute("format", "ascii");
for (int i = 0; i < s.getRange(1); i++) {
for (int j = 0; j < s.getRange(0); j++) {
if (s.getCell(new CellPos(j, i)) instanceof DiscreteCell<?>) {
writer.writeCharacters((((DiscreteCell<?>) (s.getCell(new CellPos(j, i)))).get()+1) + " ");
}
else if (s.getCell(new CellPos(j, i)) instanceof RealCell<?>) {
writer.writeCharacters((((RealCell<?>) (s.getCell(new CellPos(j, i)))).get()+1) + " ");
}
}
writer.writeCharacters("\n");
}
writer.writeEndDocument();
} | 9 |
public Measurement[] getModelMeasurements() {
List<Measurement> measurementList = new LinkedList<Measurement>();
measurementList.add(new Measurement("model training instances",
trainingWeightSeenByModel()));
measurementList.add(new Measurement("model serialized size (bytes)",
measureByteSize()));
Measurement[] modelMeasurements = getModelMeasurementsImpl();
if (modelMeasurements != null) {
for (Measurement measurement : modelMeasurements) {
measurementList.add(measurement);
}
}
// add average of sub-model measurements
Clusterer[] subModels = getSubClusterers();
if ((subModels != null) && (subModels.length > 0)) {
List<Measurement[]> subMeasurements = new LinkedList<Measurement[]>();
for (Clusterer subModel : subModels) {
if (subModel != null) {
subMeasurements.add(subModel.getModelMeasurements());
}
}
Measurement[] avgMeasurements = Measurement
.averageMeasurements(subMeasurements
.toArray(new Measurement[subMeasurements.size()][]));
for (Measurement measurement : avgMeasurements) {
measurementList.add(measurement);
}
}
return measurementList.toArray(new Measurement[measurementList.size()]);
} | 7 |
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
Editor e = new Editor();
if (!(txCodigo.getText().equals("")) || (txCodigo.getText().equals(null))){
e.setId_editor(Integer.parseInt(txCodigo.getText()));
}
if (txNome.getText().equals("") || txNome.getText().equals(null)){
JOptionPane.showMessageDialog(null,"Informe um nome antes de salvar!");
//btSalvarActionPerformed();
}
e.setNome(txNome.getText());
e.setEmail(txEmail.getText());
e.setUrl(txUrl.getText());
e.setEndereco(txEndereco.getText());
e.setCidade(txCidade.getText());
EditorController ec = new EditorController();
if (e.getId_editor() == 0){
int id = ec.salvar(e);
if(id > 0){
modelo.addRow(new Object[]{id, e.getNome(), e.getEmail(), e.getUrl(), e.getEndereco(), e.getCidade()});
JOptionPane.showMessageDialog(null,"Editor cadastrado com sucesso!");
}
}else{
int id = ec.salvar(e);
if(id > 0){
modelo.removeRow(linhaSelecionada);
modelo.addRow(new Object[]{id, e.getNome(), e.getEmail(), e.getUrl(), e.getEndereco(), e.getCidade()});
JOptionPane.showMessageDialog(null, "Editor atualizado com sucesso!");
}
}
dispose();
}//GEN-LAST:event_btSalvarActionPerformed | 7 |
public String command(final CommandSender sender, Command command, String[] args) {
sender.sendMessage(Formatting.replaceAmpersand(plugin.getString(Language.IMPORT_LOADING)));
try {
BufferedReader banlist = new BufferedReader(new FileReader("banned-players.txt"));
String p;
while ((p = banlist.readLine()) != null) {
if (!p.contains("#") && p.length() > 0) {
g(p);
}
}
banlist.close();
BufferedReader bannedIP = new BufferedReader(new FileReader("banned-ips.txt"));
String ip;
while ((ip = bannedIP.readLine()) != null) {
if (!ip.contains("#") && ip.length() > 0) {
String[] args1 = ip.split("\\|");
String name = args1[0].trim();
String cknullIP = plugin.getUBDatabase().getName(name);
if (cknullIP == null)
name = "imported";
plugin.getAPI().ipbanPlayer(name, ip, "imported", sender.getName());
}
}
bannedIP.close();
} catch (IOException e) {
String msg = Formatting.replaceAmpersand(plugin.getString(Language.IMPORT_FAILED));
sender.sendMessage(msg);
plugin.log(msg);
}
String msg = Formatting.replaceAmpersand(plugin.getString(Language.IMPORT_COMPLETED));
plugin.log(msg);
return msg;
} | 8 |
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
} | 2 |
public static List<Class<?>> processJarfile(String jarPath) {
List<Class<?>> classes = new ArrayList<Class<?>>();
JarFile jarFile;
try {
jarFile = new JarFile(jarPath);
// get contents of jar file and iterate through them
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
// Get content name from jar file
String entryName = entry.getName();
String className = null;
// If content is a class save class name.
if (entryName.endsWith(".class")) {
className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
}
log("JarEntry '" + entryName + "' => class '" + className + "'");
// If content is a class add class to List
if (className != null) {
classes.add(loadClass(className));
continue;
}
// If jar contains another jar then iterate through it
if (entryName.endsWith(".jar")) {
classes.addAll(processJarfile(entryName));
continue;
}
// If content is a directory
File subdir = new File(entryName);
if (subdir.isDirectory()) {
classes.addAll(processDirectory(subdir));
}
}
jarFile.close();
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException reading JAR File '" + jarPath + "'", e);
}
return classes;
} | 9 |
private double[] calculateSocialVelocity(int particle, double r2) {
double[] socialVelocity = new double[position[particle].length];
int nBest = neighbourhood.neighbourhoodBest(particle);
for(int k = 0; k < socialVelocity.length; k++){
socialVelocity[k] = socialConstant * r2 * (personalBest[nBest][k] - position[particle][k]);
}
return socialVelocity;
} | 1 |
private void timeMove(double voltage, double seconds) {
long milis = (long)(seconds * 1000);
long time = System.currentTimeMillis();
while (System.currentTimeMillis() < time + milis) {
drive.GoForward(voltage);
if (System.currentTimeMillis() - time > 10)
try {
Thread.sleep(10);
} catch (Exception e) {}
}
drive.Stop();
} | 3 |
public void setPrpEstado(String prpEstado) {
this.prpEstado = prpEstado;
} | 0 |
public static void main(String[] args) {
try {
if (args.length > 0) {
List<HashMap> responses = GoEuroClient.getInfo(args[0]);
String csvFileName = "output.csv";
if (args.length > 1)
csvFileName = args[1];
System.out.println("Output file name " + csvFileName);
GoEuroCSVWriter.writeToCSV(csvFileName, responses);
} else {
System.out.println("Please enter the request string.");
System.out.println("Example:");
System.out.println("java -jar testJsonCsv.jar Potsdam");
System.out.println("Example with specified output filename:");
System.out.println("java -jar testJsonCsv.jar Potsdam potsdam.csv");
}
} catch (GoEuroServerException e) {
e.printStackTrace();
}
} | 3 |
public void render(Vector2 pos, Vector2 dim)
{
switch(renderType)
{
case SOLID:
Renderer.drawRect(pos, dim, color, alpha);
break;
case TEX:
if(tex != null)
{
if(tex.isLinearScaling() != linearScaling)
tex.setLinearScaling(linearScaling);
if(tex.isRepeat() != repeat)
tex.setRepeat(repeat);
Renderer.drawRect(pos, dim, uvPos, uvDim, tex, color, alpha);
}
break;
case ANIM:
if(anim != null)
{
if(anim.getTexture().isLinearScaling() != linearScaling)
anim.getTexture().setLinearScaling(linearScaling);
if(anim.getTexture().isRepeat() != repeat)
anim.getTexture().setRepeat(repeat);
anim.render(pos, dim, uvPos, uvDim, color, alpha);
}
break;
}
} | 9 |
public void blinkparticle() {
if (untouchable > 0) {
if (blink > 15 && blink <= 30) {
setImage(invin);
}
else if (blink >= 0 && blink <= 15) {
setImage(empty);
}
}
else if (untouchable == 0) {
getWorld().removeObject(this);
}
} | 6 |
public void makeflavor() {
fo.clear();
Coord c = new Coord(0, 0);
Coord tc = gc.mul(cmaps);
for (c.y = 0; c.y < cmaps.x; c.y++) {
for (c.x = 0; c.x < cmaps.y; c.x++) {
Tileset set = sets[tiles[c.x][c.y]];
if (set.flavobjs.size() > 0) {
Random rnd = mkrandoom(c);
if (rnd.nextInt(set.flavprob) == 0) {
Resource r = set.flavobjs.pick(rnd);
Gob g = new Gob(sess.glob, c.add(tc).mul(tileSize),
-1, 0);
g.setattr(new ResDrawable(g, r));
fo.add(g);
}
}
}
}
if (!regged) {
oc.ladd(fo);
regged = true;
}
} | 5 |
public Osoba getOsoba(int index) {
return data.get(index);
} | 0 |
public <T> Collection<T> filter(Collection<T> collection, Predicate<T> predicate){
ArrayList<T> temp = new ArrayList<T>();
for(T t : collection){
if(predicate.evaluate(t)){
temp.add(t);
}
}
return temp;
} | 2 |
private void startMatrix() {
if (!timer1.isRunning()) {
timer1.start();
timer2.start();
}
} | 1 |
private static void printIt2(ParseResult<Token, DataBlock> v6) {
if(!v6.isSuccess()) {
print("oh noes, parsing failed: ");
print("tokens left: " + v6.getRestTokens().size());
LList<Token> toks = v6.getRestTokens();
int i = 0;
for(Token t : toks) {
if(i > 20) break;
print(t.type + ", " + t.value);
i++;
}
return;
}
print("parse rest: " + v6.getRestTokens().size());
} | 3 |
@Override
public void fetch() {
Thread fetcher = new FetcherThread();
fetcher.start();
} | 0 |
private static <T> T[] toObjectArray(Object array) {
if (!array.getClass().getComponentType().isPrimitive())
return (T[]) array;
int length = Array.getLength(array);
Object[] ret = new Object[length];
for(int i = 0; i < length; i++)
ret[i] = Array.get(array, i);
return (T[]) ret;
} | 2 |
public static String getWebClassesPath() {
String path = WebUtils.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
return path;
} | 0 |
public boolean keyExists(String key) {
try {
return (this.containsKey(key)) ? true : false;
} catch (Exception ex) {
return false;
}
} | 2 |
public static double runATrial(int patientIDToLeaveOut) throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getChinaDir()
+ File.separator + "phylum_taxaAsColumnsLogNorm_WithMetadataNonRare.txt")));
reader.readLine();
File outFile = new File(ConfigReader.getSvmDir() + File.separator +
"trainWithNo" + patientIDToLeaveOut+ ".txt");
outFile.delete();
if(outFile.exists())
throw new Exception("Could not delete " + outFile.getAbsolutePath());
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
for(String s= reader.readLine(); s != null; s = reader.readLine())
{
writeALine(s, writer, false, patientIDToLeaveOut);
}
writer.flush(); writer.close();
File trainFile = new File(ConfigReader.getSvmDir() + File.separator +
"trainedWithout" + patientIDToLeaveOut + ".txt");
trainFile.delete();
if( trainFile.exists())
throw new Exception("No");
// train with svm_learn.exe -z r trainingSet.txt regressModel
String[] args = new String[3];
args[0] = ConfigReader.getSvmDir() + File.separator + "svm_learn.exe";
args[1] = outFile.getAbsolutePath();
args[2] = trainFile.getAbsolutePath();
new ProcessWrapper(args);
if( ! trainFile.exists())
throw new Exception("No");
String leftOut = getLeftOut(patientIDToLeaveOut);
File classifyFile= new File(ConfigReader.getSvmDir() + File.separator +
"toClassify" + patientIDToLeaveOut + ".txt");
classifyFile.delete();
if( classifyFile.exists())
throw new Exception("NO");
BufferedWriter classificationWriter = new BufferedWriter(new FileWriter(classifyFile));
writeALine(leftOut, classificationWriter, true, patientIDToLeaveOut);
classificationWriter.flush(); classificationWriter.close();
File svmOut = new File(ConfigReader.getSvmDir() + File.separator +
"svmResultFor" + patientIDToLeaveOut + ".txt");
svmOut.delete();
if( svmOut.exists())
throw new Exception("no");
// classify with svm_classify setToClassify.txt regressModel svmOut.txt
args = new String[4];
args[0] = ConfigReader.getSvmDir() + File.separator + "svm_classify.exe";
args[1] = classifyFile.getAbsolutePath();
args[2] = trainFile.getAbsolutePath();
args[3] = svmOut.getAbsolutePath();
new ProcessWrapper(args);
BufferedReader scoreReader = new BufferedReader(new FileReader(svmOut));
double val = Double.parseDouble(scoreReader.readLine());
scoreReader.close();
return val;
} | 6 |
public synchronized UUID bind( InetAddress address,
int port,
//Map<String,BasicType> bindSettings
Environment<String,BasicType> bindSettings
)
throws IOException,
GeneralSecurityException {
if( bindSettings.get(Constants.CONFIG_SERVER_PROTOCOL) == null )
bindSettings.put( Constants.CONFIG_SERVER_PROTOCOL, new BasicStringType(Constants.NAME_PROTOCOL_TCP) );
if( bindSettings.get(Constants.CONFIG_SERVER_PROTOCOL).getString(Constants.NAME_PROTOCOL_TCP).equalsIgnoreCase(Constants.NAME_PROTOCOL_TCP) ) {
ServerSocketThread server = new ServerSocketThread( this.getLogger(),
address,
port,
bindSettings,
this // observer
);
// Register server
this.serverSocketThreads.put( server.getUUID(), server );
// Also store ID into settings
bindSettings.put( Constants.CONFIG_SERVER_ADDRESS, new BasicStringType(address.getHostName()) );
bindSettings.put( Constants.CONFIG_SERVER_PORT, new BasicNumberType(port) );
bindSettings.put( Constants.KEY_ID, new BasicUUIDType(server.getUUID()) );
// Tell the listeners about the new server
this.fireServerCreated( server.getUUID() );
// Then start thread
server.start();
// Return the new ID
return server.getUUID();
} else if( bindSettings.get(Constants.KEY_PROTOCOL) != null || bindSettings.get(Constants.KEY_PROTOCOL).getString(Constants.NAME_PROTOCOL_UDP).equalsIgnoreCase(Constants.NAME_PROTOCOL_UDP) ) {
throw new IOException( "Protocol UDP not yet supported, sorry." );
} else {
throw new IOException( "Unknown protocol: " + bindSettings.get(Constants.KEY_PROTOCOL) );
}
} | 4 |
@Override
public FileHandle openFile(String path, boolean read, boolean write)
throws PathNotFoundException, AccessDeniedException, NotAFileException {
File open = getFile(path);
if (!open.exists())
throw new PathNotFoundException(path);
if (!open.isFile())
throw new NotAFileException();
if (write && readOnly)
throw new AccessDeniedException();
FileHandle handle = new FileHandle(path);
String mode = "r";
/*if (read)
mode = "r";*/
if (write)
mode += "w";
try {
handle.setObjHandle(new RandomAccessFile(open, mode));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return handle;
} | 6 |
@Override
public void paint(Graphics g) {
super.paint(g);
player.draw(g);
Font font = new Font("Courier New", Font.PLAIN, 32);
g.setFont(font);
g.setColor(Color.WHITE);
Graphics2D g2d = (Graphics2D) g;
FontRenderContext frc = g2d.getFontRenderContext();
if (loseTimer == -1 && winTimer == 30) {
//If in the game screen
for (Enemy obj : enemies.values()) {
//Draw all the enemies
obj.draw(g);
}
for (Bullet obj : bullets.values()) {
//Draw all the bullets
obj.draw(g);
}
for (Explosion obj : explosions.values()) {
//Draw the exploding enemies
obj.draw(g);
}
for (Wall obj : walls.values()) {
//Draw the wall parts
obj.draw(g);
}
} else if (loseTimer > 0) {
//Lost, write losing message
TextLayout layout = new TextLayout("GAME OVER", font, frc);
g.drawString("GAME OVER", 800 / 2 - (int) layout.getAdvance() / 2, 800 / 2 - 32 / 2);
} else if (enemies.isEmpty()) {
//Won, write victory message
TextLayout layout = new TextLayout("WAVE CLEAR", font, frc);
g.drawString("WAVE CLEAR", 800 / 2 - (int) layout.getAdvance() / 2, 800 / 2 - 32 / 2);
}
//Draw the HUD with score
g.drawString("Score: " + score, 500, 764);
g.drawLine(0, 700, 800, 700);
Toolkit.getDefaultToolkit().sync();
g.dispose();
} | 8 |
public ProtocolSignUp(String username, int port) {
mUserName = username;
mPort = port;
} | 0 |
public static void start() throws Exception {
_poolManger = ServiceManager.getServices().getRequiredService(
ITicketPoolManager.class);
// 在disruptor启动之前打开日志
openJournal();
startDisruptor();
} | 0 |
private Object getAdditionParameterInfo(byte type, String additionalInfo) {
Object returnValue = additionalInfo;
if(type==Query.CONSECUTIVE_MONTH) {
try {
returnValue = Integer.parseInt(additionalInfo);
} catch(NumberFormatException e) {
System.err.println("Illegal parameter for ConsecutiveMonth: " + additionalInfo);
System.exit(-1);
}
} else if(type==Query.PRODUCT_TYPE_RANGE) {
try {
Integer[] params = new Integer[3];
String[] splitString = additionalInfo.split("_");
if(splitString.length<2 || splitString.length>3) {
System.err.println("Illegal parameters for ProductTypeRange: " + additionalInfo);
System.exit(-1);
}
params[0] = Integer.parseInt(splitString[0]);
params[1] = Integer.parseInt(splitString[1]);
// a "lvleq"-suffix means that each level in the product type hierarchy is chosen equally
if(splitString.length==3 && splitString[2].equals("lvleq"))
params[2] = 1;
else
params[2] = 0;
returnValue = params;
} catch(NumberFormatException e) {
System.err.println("Illegal parameters for ProductTypeRange: " + additionalInfo);
System.exit(-1);
}
}
return returnValue;
} | 8 |
public void combine(String IP_PORT,String apiKey){
DBService dbService = new DBService();
HashMap data = null;
if(this.link.contains("tiaoshi")){
PageTiaoshi pageTiaoshi = new PageTiaoshi();
data = pageTiaoshi.getInfo(this.link);
}
FileService fileService = new FileService();
ArrayList<String> bodyTxt = (ArrayList<String>) data.get("content");
ArrayList<String> bodyPic = (ArrayList<String>) data.get("bodyPicPieces");
String title = this.title;
String smalldesc = this.smalldesc.length()>0?this.smalldesc:(String)data.get("smalldesc");
smalldesc = smalldesc.length()>30?smalldesc.substring(0,29):smalldesc;
String source = (String) data.get("source");
String releasetime = this.releasetime.length()>1?this.releasetime:(String) data.get("releasetime");
String curl = this.link;
String createtime = FormatTime.getCurrentFormatTime();
String classify = this.classify;
String smallurl = fileService.uploadPic(this.imgUrl,IP_PORT,apiKey);
String cont = contentMix(bodyTxt,bodyPic,IP_PORT,apiKey,curl);
String contId = fileService.uploadFile(createtime, cont, IP_PORT, apiKey);
MyLog.logINFO("contentId:" + contId);
if(smallurl.length()==0 || (smallurl.length()>33&&smallurl.contains("."))){
Debug.showDebut(this.imgUrl, smallurl);
dbService.insertNews(title, smalldesc, smallurl, source, releasetime, contId, classify, curl, createtime);
}
} | 7 |
public void revive(){
if(this.estaDestruido()){
setDestruido(false);
}
} | 1 |
public void removeDisciplina(String codigo)
throws DisciplinaInexistenteException {
boolean teste = false;
for (Disciplina e : disciplina) {
if (e.getCodigo().equals(codigo)) {
disciplina.remove(e);
teste = true;
break;
}
}
if (teste == false) {
throw new DisciplinaInexistenteException("Remove Disciplina");
}
} | 3 |
public void updateUI(String tableName)
{
if (model != null)
{
table.setName(tableName);
System.out.println("------- TablePanel UpDate Initiated ---------");
/* get the data from the database and load it into the table model */
/* when data is loaded into the data model, it's instantly visible in the table */
model.setDataVector(database.getDisplaySet(tableName,orderby,order), database.getColumnNames());
/* Effectively, hide the columns "FileName", "Duration" by removing them from the table but not the model */
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("FileName")));
table.removeColumn(table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("Duration")));
/* set the desired column sizes */
table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("Year")).setMaxWidth(45);
table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("Time")).setMaxWidth(40);
table.getColumnModel().getColumn(table.getColumnModel().getColumnIndex("Genre")).setMaxWidth(60);
}
maxIndex = table.getRowCount();
int tmp = -1;
/* inserts, deletes and sort can change where the current song is in list */
/* if media player is not null && if media player has a song opened, then find it in table */
if(mplayer!=null && mplayer.getCurrentSong() != null)
{
tmp = getIndexOf(mplayer.getCurrentSong());
if(tmp != -1)currentIndex = tmp;
}
/*[ tmp != -1 ] indicates that song was found in list, set the currentIndex */
System.out.println(this.getClass().toString()+":: updateUI("+tableName+"):: currentIndex = " + currentIndex + ", maxIndex = "+ maxIndex);
/* highlight the currentIndex */
//if(!(maxIndex==0))table.setRowSelectionInterval(currentIndex, currentIndex);
for(int i = 6; i >1; i--)
{
if(!columnState[i-1])table.removeColumn(table.getColumn(table.getColumnName(i)));
}
if(!importing)buildShuffleList();
importing = false;
} | 7 |
public void renderPlayer (int xp, int yp, Sprite sprite) {
xp -= xOffset;
yp -= yOffset;
for (int y = 0; y < 16; y++) {
int ya = y + yp;
for (int x = 0; x < 16; x++) {
int xa = x + xp;
if (xa < -16 || xa >= width || ya < 0 || ya >= height) break;
if (xa < 0) xa = 0;
int col = sprite.pixels[((x * 2) & 31) + ((y * 2) & 31) * sprite.SIZE];
if (col != 0xFFFF00FF) pixels[xa + ya * width] = col;
// }
// }
// }
}
}
} | 8 |
@Override
public Rectangle getCellRect(int row, int column, final boolean includeSpacing) {
final Rectangle sRect = super.getCellRect(row, column, includeSpacing);
if ((row < 0) || (column < 0) || (getRowCount() <= row)
|| (getColumnCount() <= column)) {
return sRect;
}
final CellSpan cellAtt = (CellSpan) ((AttributiveCellTableModel) getModel())
.getCellAttribute();
if (!cellAtt.isVisible(row, column)) {
final int temp_row = row;
final int temp_column = column;
row += cellAtt.getSpan(temp_row, temp_column)[CellSpan.ROW];
column += cellAtt.getSpan(temp_row, temp_column)[CellSpan.COLUMN];
}
final int[] n = cellAtt.getSpan(row, column);
int index = 0;
final int columnMargin = getColumnModel().getColumnMargin();
final Rectangle cellFrame = new Rectangle();
final int aCellHeight = rowHeight + rowMargin;
cellFrame.y = row * aCellHeight;
cellFrame.height = n[CellSpan.ROW] * aCellHeight;
final Enumeration enumeration = getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
final TableColumn aColumn = (TableColumn) enumeration.nextElement();
cellFrame.width = aColumn.getWidth() + columnMargin;
if (index == column) {
break;
}
cellFrame.x += cellFrame.width;
index++;
}
for (int i = 0; i < n[CellSpan.COLUMN] - 1; i++) {
final TableColumn aColumn = (TableColumn) enumeration.nextElement();
cellFrame.width += aColumn.getWidth() + columnMargin;
}
if (!includeSpacing) {
final Dimension spacing = getIntercellSpacing();
cellFrame.setBounds(cellFrame.x + spacing.width / 2, cellFrame.y
+ spacing.height / 2, cellFrame.width - spacing.width,
cellFrame.height - spacing.height);
}
return cellFrame;
} | 9 |
public boolean isSubtype(ConcreteType that) {
if (rawType.desc.equals(RawType.coreBottom))
return true;
SuperType[] myGenericArgsForThat = rawType.superGenerics.get(that.rawType);
if (myGenericArgsForThat == null)
return false; // the raw types don't even fit
// Check each generic argument.
for (int i = 0; i < myGenericArgsForThat.length; ++i) {
ConcreteType myGenericArg = myGenericArgsForThat[i].toConcrete(genericArgs);
ConcreteType requiredGenericArg = that.genericArgs[i];
switch (that.rawType.genericVariances[i]) {
case COVARIANT:
if (!myGenericArg.isSubtype(requiredGenericArg))
return false;
break;
case NONVARIANT:
if (!myGenericArg.equals(requiredGenericArg))
return false;
break;
case CONTRAVARIANT:
if (!requiredGenericArg.isSubtype(myGenericArg))
return false;
break;
}
// TODO: check generic bounds here.
}
// If we got here, the generic arguments all fit.
return true;
} | 9 |
public Item getSpecificItem(Quality q, String name){
ArrayList<ItemInfo> list = null;
if (q == Quality.COMMON){
list = ipx.getListOf(Quality.COMMON);
}
else if (q == Quality.UNCOMMON){
list = ipx.getListOf(Quality.UNCOMMON);
}
else if (q == Quality.RARE){
list = ipx.getListOf(Quality.RARE);
}
else if (q == Quality.LEGENDARY){
list = ipx.getListOf(Quality.LEGENDARY);
}
else if (q == Quality.BASIC){
list = ipx.getListOf(Quality.BASIC);
}
for (int i = 0; i < list.size(); i++){
ItemInfo info = list.get(i);
if (info.getName().equals(name)){
return info.generateItem();
}
}
return null;
} | 7 |
public static void main(String[] args) {
final int value = 1000;
Map<Integer, String> firstDigit = new HashMap(10);
firstDigit.put(0,"");
firstDigit.put(1,"one");
firstDigit.put(2,"two");
firstDigit.put(3,"three");
firstDigit.put(4,"four");
firstDigit.put(5,"five");
firstDigit.put(6,"six");
firstDigit.put(7,"seven");
firstDigit.put(8,"eight");
firstDigit.put(9,"nine");
Map<Integer, String> secondDigitTens = new HashMap(10);
secondDigitTens.put(10,"ten");
secondDigitTens.put(11,"eleven");
secondDigitTens.put(12,"twelve");
secondDigitTens.put(13,"thirteen");
secondDigitTens.put(14,"fourteen");
secondDigitTens.put(15,"fifteen");
secondDigitTens.put(16,"sixteen");
secondDigitTens.put(17,"seventeen");
secondDigitTens.put(18,"eighteen");
secondDigitTens.put(19,"nineteen");
Map<Integer, String> secondDigitNonTens = new HashMap(10);
secondDigitNonTens.put(0,"");
secondDigitNonTens.put(2,"twenty");
secondDigitNonTens.put(3,"thirty");
secondDigitNonTens.put(4,"forty");
secondDigitNonTens.put(5,"fifty");
secondDigitNonTens.put(6,"sixty");
secondDigitNonTens.put(7,"seventy");
secondDigitNonTens.put(8,"eighty");
secondDigitNonTens.put(9,"ninety");
Map<Integer, String> thirdDigit = new HashMap(10);
thirdDigit.put(1,"onehundredand");
thirdDigit.put(2,"twohundredand");
thirdDigit.put(3,"threehundredand");
thirdDigit.put(4,"fourhundredand");
thirdDigit.put(5,"fivehundredand");
thirdDigit.put(6,"sixhundredand");
thirdDigit.put(7,"sevenhundredand");
thirdDigit.put(8,"eighthundredand");
thirdDigit.put(9,"ninehundredand");
String oneThousand = "onethousand";
long count = 0;
for (int i = 1; i <= value; i++) {
String stringValue = Integer.toString(i);
if (stringValue.length() == 4) {
count += oneThousand.length();
}
if (stringValue.length() == 3) {
String leftDigit = stringValue.substring(0,1);
int intValue = Integer.parseInt(leftDigit);
if (stringValue.substring(1).equals("00")) {
count += thirdDigit.get(intValue).replace("and","").length();
} else {
count += thirdDigit.get(intValue).length();
}
stringValue = stringValue.substring(1);
}
if (stringValue.length() == 2) {
if (stringValue.substring(0,1).equals("1")) {
int intValue = Integer.parseInt(stringValue);
count += secondDigitTens.get(intValue).length();
stringValue = "";
} else {
String leftDigit = stringValue.substring(0,1);
int intValue = Integer.parseInt(leftDigit);
count += secondDigitNonTens.get(intValue).length();
stringValue = stringValue.substring(1);
}
}
if (stringValue.length() == 1) {
int intValue = Integer.parseInt(stringValue);
count += firstDigit.get(intValue).length();
}
}
System.out.println(count);
} | 7 |
@Override
public void run(final String... args) {
final CommandLine line = parseArguments(args);
final String destinationFolder = line.getOptionValue(FOLDER_SHORT, System.getProperty("user.dir"));
// FIXME: Have some way to add Mp3Metadata for individual songs/artists
if (line.hasOption(SONG_SHORT)) {
for (final String song : line.getOptionValues(SONG_SHORT)) {
final Downloader downloader = SCUtilFactory.getDownloader(song);
downloader.downloadSong(song, destinationFolder, null);
}
}
if (line.hasOption(ARTIST_SHORT)) {
for (final String artist : line.getOptionValues(ARTIST_SHORT)) {
final Downloader downloader = SCUtilFactory.getDownloader(artist);
downloader.downloadArtist(artist, destinationFolder, null);
}
}
if (line.hasOption(PLAYLIST_SHORT)) {
for (final String playlist : line.getOptionValues(PLAYLIST_SHORT)) {
final Downloader downloader = SCUtilFactory.getDownloader(playlist);
downloader.downloadPlaylist(playlist, destinationFolder, null);
}
}
} | 6 |
protected boolean canChange(int value){
Controller c = gui.getController();
if (centerCause(c.getX1(), c.getX2(), value, c.getY2(), c.getR1(), c.getR2())){
return true;
}
else{
showCenterWarning();
return false;
}
} | 1 |
public void start()
{
synchronized (optOutLock)
{
// Did we opt out?
if (isOptOut())
{
return;
}
// Begin hitting the server with glorious data
taskId = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
private boolean firstPost = true;
public void run()
{
try
{
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock)
{
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && taskId > 0)
{
plugin.getServer().getScheduler().cancelTask(taskId);
taskId = -1;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
}
catch (IOException e)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}, 0, PING_INTERVAL * 1200);
}
} | 4 |
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameLogo frame = new FrameLogo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
Clip sonido = AudioSystem.getClip();
File a = new File("Intro.wav");
sonido.open(AudioSystem.getAudioInputStream(a));
sonido.start();
System.out.println("Reproduciendo 10s. de sonido...");
Thread.sleep(50000); // 50.000 milisegundos (50 segundos)
sonido.close();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} | 5 |
public Emage buildEmage(Timestamp lastEmageCreationTime, long windowSizeMS) {
filterPointQueueByWindow(windowSizeMS);
this.pointQueue.addAll(this.pointStream.getAndClearNewPointsQueue());
Iterator<STTPoint> pointIterator = this.pointQueue.iterator();
GeoParams geoParams = this.pointStream.getGeoParams();
//Initialize grid to correct values
double[][] valueGrid = createEmptyValueGrid(geoParams, this.operator);
//For holding the counts so we can compute the avg of each cell
double[][] avgAssistGrid = createEmptyValueGrid(geoParams, Operator.AVG);
while (pointIterator.hasNext()) {
STTPoint currPoint = pointIterator.next();
int x = getXIndex(geoParams, currPoint);
int y = getYIndex(geoParams, currPoint);
if (x>=0 && y >=0) {
switch (this.operator) {
case MAX:
valueGrid[x][y] = Math.max(valueGrid[x][y], currPoint.getValue());
break;
case MIN:
valueGrid[x][y] = Math.min(valueGrid[x][y], currPoint.getValue());
break;
case SUM:
valueGrid[x][y] += currPoint.getValue();
break;
case COUNT:
System.out.println("x: "+x+", y: "+y);
System.out.println("x size: " + valueGrid.length + "y size: "+ valueGrid[0].length);
System.out.println(currPoint);
valueGrid[x][y]++;
break;
case AVG:
double total = valueGrid[x][y]*avgAssistGrid[x][y];
//Add one to the count from that cell,
valueGrid[x][y] = (total+currPoint.getValue())/++avgAssistGrid[x][y];
break;
}
}
}
return new Emage(valueGrid, lastEmageCreationTime, new Timestamp(System.currentTimeMillis()), this.pointStream.getAuthFields(),
this.pointStream.getWrapperParams(), geoParams);
} | 8 |
@Override
public void run() {//Is called only once with thread.start()
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while(inGame){
repaint();
try {
checkCollision();
} catch (Exception ex) {
Logger.getLogger(GamePanel.class.getName()).log(Level.SEVERE, null, ex);
}
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if(sleep < 0){
sleep = 2;
}
try{
Thread.sleep(sleep);
}catch(InterruptedException e){
System.out.println("ERROR: Thread.sleep()");
}
beforeTime = System.currentTimeMillis();
}
} | 4 |
public static DaysOfWeekEnumerationx fromValue(DayTypeEnumeration v) {
for (DaysOfWeekEnumerationx c: DaysOfWeekEnumerationx.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
} | 2 |
public void run()
{
// システム情報取得
String str = System.getProperty("os.name");
mOSName = str;
str = System.getProperty("os.arch");
mOSArch = str;
str = System.getProperty("os.version");
mOSVersion = str;
str = System.getProperty("user.name");
mUserName = str;
DebugLog("user name:" + str);
DebugLog("os name:" + str);
DebugLog("os arch:" + str);
DebugLog("os version:" + str);
try
{
InetAddress addr = InetAddress.getLocalHost();
mHostName = addr.getHostName();
DebugLog("host name:" + addr.getHostName());
DebugLog("host ip:" + addr.getHostAddress());
}
catch (Exception e)
{
e.printStackTrace();
}
// クリップボード監視の開始。
mClipThread = new ClipboardWatchThread( 500, mPortNum );
mClipThread.start();
try {
// ポート番号は、30000
//ソケットを作成
mServerSoc = new ServerSocket(mPortNum);
//クライアントからの接続を待機するaccept()メソッド。
//accept()は、接続があるまで処理はブロックされる。
//もし、複数のクライアントからの接続を受け付けるようにするには
//スレッドを使う。
//accept()は接続時に新たなsocketを返す。これを使って通信を行なう。
String rcvMsg = null;
Socket socket=null;
BufferedReader reader = null;
while(!mHalt)
{
DebugLog("Waiting for Connection. ");
socket = mServerSoc.accept();
//接続があれば次の命令に移る。
DebugLog("Connect to " + socket.getInetAddress());
mIP = socket.getInetAddress().toString();
if( mIP.charAt(0) == '/' )
{
mIP = mIP.substring( 1, mIP.length());
}
// mPointTouchServer.setIpAddress( mIP );
boolean addIp = mMultiTouchServer.noticeIpAddress( mIP );
if( addIp == true )
{
mClipThread.setIpList( mMultiTouchServer.mIpList );
}
//socketからのデータはInputStreamReaderに送り、さらに
//BufferedReaderによってバッファリングする。
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//読み取ったデータを表示する。
try
{
rcvMsg = reader.readLine();
}
catch( SocketException e )
{
System.out.println("Socket Exceptoin!");
e.printStackTrace();
}
DebugLog("Message from client :" + rcvMsg);
//System.out.println( rcvMsg );
//入力ストリームをクローズする。
reader.close();
reader = null;
//通信用ソケットの接続をクローズする。
socket.close();
socket = null;
//待ち受け用ソケットをクローズする。
if(rcvMsg.matches("end"))
{
mServerSoc.close();
mHalt = true;
System.out.println("Stopped.");
}
char wk = ' ';
String command = "";
for( int i = 0; i< rcvMsg.length(); ++i )
{
wk = rcvMsg.charAt(i);
if( wk == ' ' )
{
// コマンドの区切り文字。
// コマンド実行。
ParthCommand(command);
command = "";
}
else
{
command += wk;
}
}
}
mServerSoc.close();
}
catch (IOException e) {
e.printStackTrace();
}
mClipThread.halt();
}// end of run() | 9 |
public static SettingsWindow getInstance() {
if (instance == null)
instance = new SettingsWindow();
return instance;
} | 1 |
private void calculateMinesTouched(int coordX, int coordY) {
if (cellArray[coordX][coordY].type != Cell.CellType.MINE) {
int startingValueX = -1;
int startingValueY = -1;
int endingValueX = 1;
int endingValueY = 1;
int nbOfMinesTouched = 0;
if (coordX == 0) {
startingValueX = 0;
} else if (coordX == sizeX - 1) {
endingValueX = 0;
}
if (coordY == 0) {
startingValueY = 0;
} else if (coordY == sizeY - 1) {
endingValueY = 0;
}
for (int i = startingValueX; i <= endingValueX; i++) {
for (int j = startingValueY; j <= endingValueY; j++) {
if (cellArray[coordX + i][coordY + j].type == Cell.CellType.MINE) {
nbOfMinesTouched++;
}
}
}
this.cellArray[coordX][coordY].setNbOfMinesTouched(nbOfMinesTouched);
}
} | 8 |
private void configureComponents()
{
minimumSize = new Dimension(100, 60);
preferredSize = new Dimension(200, 60);
maximumSize = new Dimension(3000, 60);
notesButton = new JButton("");
notesButton.setIcon(new ImageIcon("images/Notes.jpg"));
notesButton.setToolTipText("Click this button to add a note to this task.");
taskCheckBox = new CustomCheckBox(task.getName());
taskCheckBox.setToolTipText("<html>Click this checkbox to toggle this task<br>" +
"between complete and incomplete.</html>");
courseLabel = new JLabel(task.getCourse().getName());
courseLabel.setToolTipText("This indicates the course this task is associated with.");
int newX = courseLabel.getPreferredSize().width;
int newY = courseLabel.getPreferredSize().height;
courseLabel.setPreferredSize(new Dimension(newX+10, newY+10));
courseLabel.setHorizontalAlignment(SwingConstants.CENTER);
//System.out.println(newX + " " + newY);
Calendar cal = Calendar.getInstance();
Integer day = cal.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day)
{
case 1: dayString = "Sunday"; break;
case 2: dayString = "Monday"; break;
case 3: dayString = "Tuesday"; break;
case 4: dayString = "Wednesday"; break;
case 5: dayString = "Thursday"; break;
case 6: dayString = "Friday"; break;
case 7: dayString = "Saturday"; break;
default: dayString = "Unknown";
}
dueDate = new JLabel(dayString);
dueDate.setToolTipText("This is the due date for this task.");
setBorder(BorderFactory.createEtchedBorder());
setPreferredSize(preferredSize);
setMaximumSize(maximumSize);
courseLabel.setOpaque(true);
courseLabel.setBackground(task.getCourse().getColor());
courseLabel.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
customTransferHandler = new TransferHandler()
{
};
setTransferHandler(new TransferHandler()
{
});
dragSource = DragSource.getDefaultDragSource();
} | 7 |
public Transferencia(Cuenta destino, String concept, float importe){
super(concept, importe);
this.tipo = "transferencia";
this.destino = destino;
} | 0 |
public boolean loadLastLevel(Component parentComponent, boolean selectMode) {
String str = editorSettings.getLastLevelFileName();
if(!selectMode && (str == null || str.trim().length() == 0)){
return false;
}
if(str == null || str.trim().length() == 0){
return loadLevel(parentComponent);
}
File selectedFile = new File(str);
boolean workIt = false;
try {
if(selectedFile.canRead()) {
workIt = true;
}
} catch (Exception e){
workIt = false;
}
if(workIt){
return loadLevelFromFile(selectedFile);
} else if(selectMode) {
return loadLevel(parentComponent);
} else {
return false;
}
} | 9 |
private void populate()
{
Random rand = Randomizer.getRandom();
field.clear();
int Number_of_foxes = 0;
int Number_of_rabbits = 0;
int Number_of_korenwolfs = 0;
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
if(rand.nextDouble() <= KORENWOLF_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Korenwolf korenwolf = new Korenwolf(true, field, location);
actors.add(korenwolf);
Number_of_korenwolfs++;
}
else if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Fox fox = new Fox(true, field, location);
actors.add(fox);
Number_of_foxes++;
}
else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Rabbit rabbit = new Rabbit(true, field, location);
actors.add(rabbit);
Number_of_rabbits++;
}
else if(rand.nextDouble() <= HUNTER_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Hunter hunter = new Hunter(field, location);
actors.add(hunter);
}
else if(rand.nextDouble() <= 0.03) {
Location location = new Location(row, col);
Grass grass = new Grass(field, location);
actors.add(grass);
}
// else leave the location empty.
}
}
Rabbit.PERFECT_NUMBER_OF_RABBITS = Number_of_rabbits;
Fox.PERFECT_NUMBER_OF_FOXES = Number_of_foxes;
Korenwolf.PERFECT_NUMBER_OF_KORENWOLFS = Number_of_korenwolfs;
} | 7 |
public ArrayList<MatchScheduling> scheduleSemiFinals() throws SQLException
{
ArrayList<MatchScheduling> matches = new ArrayList();
ArrayList<Team> s1Teams = new ArrayList();
ArrayList<Team> s2Teams = new ArrayList();
for (int k = 0; k <= 1; k++)
{
int homeTeamId = getById(listByMatchRound(7).get(k).getId()).getHomeTeamId();
int guestTeamId = getById(listByMatchRound(7).get(k).getId()).getGuestTeamId();
if (getById(listByMatchRound(7).get(k).getId()).getHomeGoals() > getById(listByMatchRound(7).get(k).getId()).getGuestGoals())
{
Team hw = teammgr.getById(homeTeamId);
s1Teams.add(hw);
}
else
{
Team gw = teammgr.getById(guestTeamId);
s1Teams.add(gw);
}
}
for (int k = 2; k <= 3; k++)
{
int homeTeamId = getById(listByMatchRound(7).get(k).getId()).getHomeTeamId();
int guestTeamId = getById(listByMatchRound(7).get(k).getId()).getGuestTeamId();
if (getById(listByMatchRound(7).get(k).getId()).getHomeGoals() > getById(listByMatchRound(7).get(k).getId()).getGuestGoals())
{
Team hw = teammgr.getById(homeTeamId);
s2Teams.add(hw);
}
else
{
Team gw = teammgr.getById(guestTeamId);
s2Teams.add(gw);
}
}
ArrayList<MatchScheduling> semiFinalMatches = new ArrayList();
/*
* Round 8 (Semi finals)
*/
semiFinalMatches.add(new MatchScheduling(8, s1Teams.get(0), s1Teams.get(1)));
semiFinalMatches.add(new MatchScheduling(8, s2Teams.get(0), s2Teams.get(1)));
matches.addAll(semiFinalMatches);
for (MatchScheduling m : semiFinalMatches)
{
db.addMatches(m);
}
return null;
} | 5 |
void compress(int init_bits, OutputStream outs) throws IOException {
int fcode;
int i /* = 0 */;
int c;
int ent;
int disp;
int hsize_reg;
int hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = hsize; fcode < 65536; fcode *= 2)
++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = hsize;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop : while ((c = nextPixel()) != EOF) {
fcode = (c << maxbits) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] == fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) // non-empty slot
{
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i == 0)
disp = 1;
do {
if ((i -= disp) < 0)
i += hsize_reg;
if (htab[i] == fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < maxmaxcode) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else
cl_block(outs);
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
} | 9 |
final public ASTProgram Start() throws ParseException {
/*@bgen(jjtree) Program */
ASTProgram jjtn000 = new ASTProgram(JJTPROGRAM);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
Expression();
jj_consume_token(0);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
{if (true) return jjtn000;}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
throw new Error("Missing return statement in function");
} | 9 |
public PartC getPartC() {
return partC;
} | 0 |
public ArrayList<Prestamos> getById(Prestamos p){
PreparedStatement ps;
ArrayList<Prestamos> rows = new ArrayList<>();
try {
ps = mycon.prepareStatement("SELECT * FROM Prestamos WHERE id=?");
ps.setInt(1, p.getId());
ResultSet rs = ps.executeQuery();
if(rs!=null){
try {
while(rs.next()){
rows.add(
new Prestamos(
rs.getInt("id"),
rs.getDate("fecha"),
rs.getString("estado"),
rs.getString("id_libro"),
rs.getString("id_usuario")
)
);
}
} catch (SQLException ex) {
Logger.getLogger(Prestamos.class.getName()).
log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Total de registros encontrados es: 0");
}
} catch (SQLException ex) {
Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return rows;
} | 4 |
public boolean checkState() throws Exception
{
boolean result = false;
this.input = new FileInputStream(this.device.getAbsolutePath());
this.output = new FileOutputStream(this.device.getAbsolutePath());
this.output.flush();
Thread.sleep(this.MAX_INTERVAL * 3);
System.out.println(input.available());
this.output.write((byte)Sign.REQUEST);
this.output.flush();
Thread.sleep(this.MAX_INTERVAL * 8);
System.out.println(input.available());
Integer c = 0;
input.markSupported();
ArrayList<Integer> list = new ArrayList<Integer>();
if ( input.available() > 0)
{
while ((c = input.read()) != -1)
list.add(c);
if (list.size() > 0)
{
if(list.get(0) == Status.ERROR)
{
byte[] command = new byte[2];
command[0] = (byte)Status.OK;
command[1] = (byte)Sign.REQUEST;
this.output.write(command);
this.output.flush();
result = true;
}
}
}
this.input.close();
this.output.close();
return result;
} | 4 |
public static DatabaseTestHelper getInstance(){
if(instance == null){
instance = new DatabaseTestHelper();
}
return instance;
} | 1 |
@Override
public NewCharNameCheckResult newCharNameCheck(String login, String ipAddress, boolean skipAccountNameCheck)
{
final boolean accountSystemEnabled = CMProps.isUsingAccountSystem();
if(((CMSecurity.isDisabled(CMSecurity.DisFlag.NEWPLAYERS)&&(!accountSystemEnabled))
||(CMSecurity.isDisabled(CMSecurity.DisFlag.NEWCHARACTERS)))
&&(!CMProps.isOnWhiteList(CMProps.WhiteList.NEWPLAYERS, login))
&&(!CMProps.isOnWhiteList(CMProps.WhiteList.NEWPLAYERS, ipAddress)))
return NewCharNameCheckResult.NO_NEW_PLAYERS;
else
if((!isOkName(login,false))
|| (CMLib.players().playerExists(login))
|| (!skipAccountNameCheck && CMLib.players().accountExists(login)))
return NewCharNameCheckResult.BAD_USED_NAME;
else
return finishNameCheck(login,ipAddress);
} | 9 |
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns a large
// set of data and then display it.
String SQL = "SELECT * FROM Sales.SalesOrderDetail;";
stmt = con.createStatement(SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, +
SQLServerResultSet.CONCUR_READ_ONLY);
// Perform a fetch for every row in the result set.
rs = stmt.executeQuery(SQL);
timerTest(1, rs);
rs.close();
// Perform a fetch for every 10th row in the result set.
rs = stmt.executeQuery(SQL);
timerTest(10, rs);
rs.close();
// Perform a fetch for every 100th row in the result set.
rs = stmt.executeQuery(SQL);
timerTest(100, rs);
rs.close();
// Perform a fetch for every 1000th row in the result set.
rs = stmt.executeQuery(SQL);
timerTest(1000, rs);
rs.close();
// Perform a fetch for every 128th row (the default) in the result set.
rs = stmt.executeQuery(SQL);
timerTest(0, rs);
rs.close();
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
} | 7 |
private static DateModel<?> createModelFromValue(Object value) {
if (value instanceof java.util.Calendar) {
return new UtilCalendarModel((Calendar) value);
}
if (value instanceof java.util.Date) {
return new UtilDateModel((java.util.Date) value);
}
if (value instanceof java.sql.Date) {
return new SqlDateModel((java.sql.Date) value);
}
throw new IllegalArgumentException("No model could be constructed from the initial value object.");
} | 4 |
public MyList filter(ListFilter lf) {
MyList newlist = new MyList();
Iterator it = iterator();
while(it.hasNext()) {
Object o = it.next();
if (lf.test(o)) newlist.add(o);
}
return newlist;
} | 2 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Acercade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Acercade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Acercade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Acercade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Acercade().setVisible(true);
}
});
} | 6 |
public static void main(String[] args) throws InterruptedException, IOException{
while (true)
{
System.out.print("Input: ");
BufferedReader getInput = new BufferedReader(new InputStreamReader(System.in));
String Input = getInput.readLine();
if (Input.equals("Ping"))
{
System.out.println("Pong");
}
else
{
if (Input.equals("Pong"))
{
Return("Ping");
}
else
{
if (Input.equals("ping"))
{
Return("Pong");
}
else
{
if (Input.equals("pong"))
{
Return("ping");
}
else
{
Return("Not Ping or Pong");
}
}
}
}
if (Input.equals("password"))
{
System.out.print("Input: ");
Thread.sleep(5000);
Return("");
System.out.print("What is the password?");
BufferedReader pswInput = new BufferedReader(new InputStreamReader(System.in));
String Password = pswInput.readLine();
if (Password.equals("WordPass"))
{
Return("WELCOME");
}
else
{
Return("INCORECT"); }
}
Thread.sleep(500);
}
} | 7 |
@Test
public void testTorbenGusevAlgorithm() throws Exception {
PrintStream out = System.out;// new PrintStream(new File("results.txt"));
// Note: Uncomment opCount and loopCount counters in HistogramBasedMedianFinder class to get statistics
boolean warmUp = false;
// Note: Change nRanges from 2 to 100 with warmUp = true to analyze results with the spreadsheet
for (int nRanges = 1000; nRanges <= 1000; nRanges += (nRanges >= 30 ? 5 : 1)) {
out.println("testTorbenGusevAlgorithm (nRanges = " + nRanges + ")");
if (warmUp) {
System.out.println("Warming up JVM...");
} else {
System.out.println("nRanges = " + nRanges);
}
out.println("n\tmedian\tloops\tops\ttime\tcomps");
Random rand = new Random(42);
// Note: Change max n to 1 million to analyze results with the spreadsheet
for (int n = 2; n <= 2; n += 1) {
double m[] = new double[n];
for (int i = 0; i < n; i++) {
m[i] = rand.nextDouble();
}
TorbenGusevAlgorithm algorithm = new TorbenGusevAlgorithm(nRanges);
long startTime = System.currentTimeMillis();
double torbenGusevMedian = algorithm.search(m);
long endTime = System.currentTimeMillis();
Arrays.sort(m);
double median = n % 2 == 0 ? m[n / 2 - 1] : m[n / 2];
Assert.assertEquals(median, torbenGusevMedian, algorithm.epsilon);
if (!warmUp) {
out.println(n + "\t" + torbenGusevMedian + "\t" + algorithm.getLoopCount() + "\t" + algorithm.getOpCount() + "\t" + (endTime - startTime) + "\t" + algorithm.getCompCount());
}
}
if (warmUp) {
nRanges = nRanges - 1; // next nRanges would be 2 again
warmUp = false;
}
}
out.close();
System.out.println("Done");
} | 8 |
private void jj_rescan_token() {
jj_rescan = true;
for (int i = 0; i < 6; i++) {
JJCalls p = jj_2_rtns[i];
do {
if (p.gen > jj_gen) {
jj_la = p.arg;
jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0:
jj_3_1();
break;
case 1:
jj_3_2();
break;
case 2:
jj_3_3();
break;
case 3:
jj_3_4();
break;
case 4:
jj_3_5();
break;
case 5:
jj_3_6();
break;
}
}
p = p.next;
} while (p != null);
}
jj_rescan = false;
} | 9 |
public Integer[] getSelected() {
ArrayList<Integer> selectedIndex = new ArrayList<Integer>();
for(int i = 0; i < selected.size(); ++i) {
if(selected.get(i)) {
selectedIndex.add(i);
}
}
return (Integer[]) selectedIndex.toArray();
} | 2 |
@Override
public void makePeace(boolean includePlayerFollowers)
{
final MOB myVictim = victim;
setVictim(null);
for (int f = 0; f < numFollowers(); f++)
{
final MOB M = fetchFollower(f);
if ((M != null) && (M.isInCombat()) && (includePlayerFollowers || M.isMonster()))
M.makePeace(true);
}
if (myVictim != null)
{
final MOB oldVictim = myVictim.getVictim();
if (oldVictim == this)
myVictim.makePeace(true);
}
} | 7 |
public Map<Integer, Double> getValueProbsForID(int id, boolean topicCreation) {
Map<Integer, Double> terms = null;
if (id < this.docList.size()) {
terms = new LinkedHashMap<Integer, Double>();
Map<Integer, Double> docVals = this.docList.get(id);
for (Map.Entry<Integer, Double> topic : docVals.entrySet()) { // look at each assigned topic
Set<Entry<Integer, Double>> entrySet = this.topicList.get(topic.getKey()).entrySet();
double topicProb = topic.getValue();
for (Map.Entry<Integer, Double> entry : entrySet) { // and its terms
if (topicCreation) {
if (topicProb > TOPIC_THRESHOLD) {
terms.put(entry.getKey(), topicProb);
break; // only use first tag as topic-name with the topic probability
}
} else {
double wordProb = entry.getValue();
Double val = terms.get(entry.getKey());
terms.put(entry.getKey(), val == null ? wordProb * topicProb : val + wordProb * topicProb);
}
}
}
}
return terms;
} | 6 |
@Override
protected void done() {
try {
//System.out.println("loaded image");
image.setIcon(get());
} catch (InterruptedException ex) {
System.out.println(ex);
} catch (ExecutionException ex) {
System.out.println(ex);
}
} | 2 |
public void actionPerformed(ActionEvent e) {
Locale locale = Locale.getDefault();
Date date = new Date(e.getWhen());
String s = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(date);
if (!model.isEmpty()) {
model.clear();
}
if (e.getID() == ActionEvent.ACTION_PERFORMED) {
model.addElement(" Event Id: ACTION_PERFORMED");
}
model.addElement(" Time: " + s);
String source = e.getSource().getClass().getName();
model.addElement(" Source: " + source);
int mod = e.getModifiers();
StringBuffer buffer = new StringBuffer(" Modifiers: ");
if ((mod & ActionEvent.ALT_MASK) > 0) {
buffer.append("Alt ");
}
if ((mod & ActionEvent.SHIFT_MASK) > 0) {
buffer.append("Shift ");
}
if ((mod & ActionEvent.META_MASK) > 0) {
buffer.append("Meta ");
}
if ((mod & ActionEvent.CTRL_MASK) > 0) {
buffer.append("Ctrl ");
}
model.addElement(buffer);
} | 6 |
@Override
public final void run() {
// Reset, Job Object Data
this.failureObject = null;
this.returnObject = null;
this.finished = false;
this.success = false;
// ---------------------- EXECUTION ---------------------- //
System.out.println("[JOB] Execution of Job -> " + this.jobName);
Object jobFailureReturnObject = null;
try
{
jobFailureReturnObject = this.execute();
}
catch(Throwable e)
{
jobFailureReturnObject = e;
}
this.failureObject = jobFailureReturnObject;
if(jobFailureReturnObject == null)
{
// ---------------------- SUCCESS ---------------------- //
System.out.println("[JOB] Finished Job -> " + this.jobName);
if(this.returnObject != null)
{
System.out.println("[JOB] Job Result: " + this.returnObject);;
}
this.success = true;;
}
else
{
// ---------------------- FAILURE ---------------------- //
if(jobFailureReturnObject instanceof Exception)
{
System.out.println("[JOB] The Job '"+this.jobName+"' failed because of an Exception.");
System.out.println("[JOB] Job Failure Exception -> " + ((Exception) jobFailureReturnObject).getLocalizedMessage());
((Exception) jobFailureReturnObject).printStackTrace();
}
else
{
System.out.println("[JOB] The Job '"+this.jobName+"' failed because it reported a error object.");
System.out.println("[JOB] Job Error Object Class -> " + jobFailureReturnObject.getClass().getName());
System.out.println("[JOB] Job Error Object -> " + jobFailureReturnObject);
}
this.success = false;;
}
this.finished = true;
return;
} | 4 |
public boolean contains(Temporal temporal) {
if (null == temporal) return false;
if (this == temporal) return true;
if (isTimeInstance()) {
return temporal.isTimeInstance() ? startTime == temporal.startTime : false;
} else {
if (temporal.isTimeInstance()) return !(startTime > temporal.startTime || temporal.endTime >= endTime);
return !(startTime > temporal.startTime || temporal.endTime > endTime);
}
} | 7 |
protected static Ptg calcEOMonth( Ptg[] operands )
{
try
{
GregorianCalendar startDate = getDateFromPtg( operands[0] );
int inc = operands[1].getIntVal();
int mm = startDate.get( Calendar.MONTH ) + inc;
int y = startDate.get( Calendar.YEAR );
int d = startDate.get( Calendar.DAY_OF_MONTH );
if( mm < 0 )
{
mm += 12; // 0-based
y--;
}
else if( mm > 11 )
{
mm -= 12;
y++;
}
if( (mm == 3) || (mm == 5) || (mm == 8) || (mm == 10) ) // 0-based
{
d = 30;
}
else if( mm == 1 )
{// february
if( (y % 4) == 0 )
{
d = 29;
}
else
{
d = 28;
}
}
else
{
d = 31;
}
GregorianCalendar resultDate;
resultDate = new GregorianCalendar( y, mm, d );
double retdate = DateConverter.getXLSDateVal( resultDate );
int i = (int) retdate;
return new PtgInt( i );
}
catch( Exception e )
{
}
return new PtgErr( PtgErr.ERROR_NUM );
} | 9 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.