text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean isSimplified(){
if(this.top instanceof Number && this.bottom instanceof Number){
Number top = (Number) this.top;
Number bottom = (Number) this.bottom;
//if they aren't whole numbers or top or bottom is negative
if(top.getDecimal() != null || bottom.getDecimal() != null || !bottom.sign() || !top.sign()) return false;
else{
//make sure bottom is greater than top (i.e., it's not an improper fraction) and they have no common factors
long topNum = Long.parseLong(top.getInteger()), bottomNum = Long.parseLong(bottom.getInteger());
return topNum < bottomNum && Number.GCF(topNum, bottomNum) == 1;
}
}
else return false;
} | 7 |
public double getActionAngle(Instance vision, String angleType) throws Exception {
if (angleType == StringUtil.KICK_ANGLE && kickAngleCls != null) {
return kickAngleCls.classifyInstance(vision);
} else if (angleType == StringUtil.TURN_ANGLE && turnAngleCls != null) {
return turnAngleCls.classifyInstance(vision);
} else if (angleType == StringUtil.CATCH_ANGLE && catchAngleCls != null) {
return catchAngleCls.classifyInstance(vision);
}else {
System.err.println("There is no angle parameter for this action. Use default value 0");
return 0;
}
} | 6 |
public static void main(String[] args) {
if (args.length == 5) {
double totalElapsedTime;
StopWatch programRunning = new StopWatch();
DataLoader dl;
Instances data = null;
try {
dl = new DataLoader(args[0]);
data = dl.instancesLoader();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String resultado = "Cluster jerarquico, por Yuriy Andzheyevskiy y Jonathan Castro.\n\n";
resultado += args[0] + ".\n";
resultado += " - Numero de instancias: " + data.numInstances() + ".\n";
HierarchicalClustering hc;
ClusterTree tree = new ClusterTree(null);
int algorithm = Integer.parseInt(args[1]);
int linkage = Integer.parseInt(args[2]);
int distance = Integer.parseInt(args[3]);
int file = Integer.parseInt(args[4]);
if (linkage == 0) { // Complete-link.
hc = new HierarchicalClustering(0, data);
resultado += " - Linkage utilizado: complete-link.\n";
} else if (linkage == 1) { // Single-link.
hc = new HierarchicalClustering(1, data);
resultado += " - Linkage utilizado: single-link.\n";
} else { // Por defecto, average-link.
hc = new HierarchicalClustering(2, data);
resultado += " - Linkage utilizado: average-link.\n";
}
if (distance == 0) { // Chebyshev.
Distance.getMiDistance().setDistance(0);
resultado += " - Distancia utilizada: Chebyshev.\n";
} else { // Minkowski.
Distance.getMiDistance().setDistance(distance);
resultado += " - Distancia utilizada: Minkowski, con k = " + distance + ".\n";
}
double elapsedTimeAlgorithm;
StopWatch algorithmTime;
if (algorithm == 0) { // Top-down
resultado += " - Algoritmo utilizado: top-down.\n\n";
System.out.println(resultado);
resultado += "=========== Resultado del algoritmo ===========\n\n";
algorithmTime = new StopWatch();
tree = hc.topDown();
elapsedTimeAlgorithm = algorithmTime.elapsedTime();
resultado += tree.toString();
} else { // Por defecto, bottom-up.
resultado += " - Algoritmo utilizado: bottom-up.\n\n";
System.out.println(resultado);
resultado += "=========== Resultado del algoritmo ===========\n\n";
algorithmTime = new StopWatch();
resultado += hc.bottomUp();
elapsedTimeAlgorithm = algorithmTime.elapsedTime();
}
System.out.println("\n\nTiempo que ha tardado en ejecutarse el algoritmo: " + elapsedTimeAlgorithm + "s.");
if (file != 0) { // Si el usuario ha introducido un numero que no sea 0, sacara el resultado de las iteraciones en un fichero.
SaveResults.getSaveResults().SaveFile(args[0], resultado, true, "resultado");
if (algorithm == 0) // Top-down
SaveResults.getSaveResults().SaveFile(args[0], tree.printTree(), false, "arbol");
}
totalElapsedTime = programRunning.elapsedTime();
System.out.println("Tiempo que ha tardado en ejecutarse el prgrama completo: " + totalElapsedTime + "s.");
} else {
System.out.println("El numero de parametros no es el correcto.");
String aviso = "Parametros a introducir:\n";
aviso += " 1. Path del fichero.\n";
aviso += " 2. Tipo de clustering jerarquico: si 0 top-down, sino bottom-up.\n";
aviso += " 3. Tipo distancia intergrupal: si 0 complete-link, si 1 single-link, sino average-link.\n";
aviso += " 4. Distancia: si 0 Chebyshev; sino Minkowski para k igual al parametro introducido.\n";
aviso += " 5. Salida de resultados a fichero: si 0 desactivado, sino activado.";
System.out.println(aviso);
}
} | 9 |
@Override
public void remove(int i) {
for(int j = i; j<=this.size;j++){
this.keys[j] = this.keys[j+1];
}
this.size--;
} | 1 |
@Override
public String toString() {
String lsAttrs = "";
for (int i = 0; caAttributes != null && i < caAttributes.size(); i++) {
lsAttrs += " " + caAttributes.get(i).toString();
}
StringBuilder builder = new StringBuilder();
builder.append("ROOM [attributeid=");
builder.append(csAttributeId);
builder.append(", descr=");
builder.append(csDescr);
builder.append(", lastmodified=");
builder.append(csLastModified);
builder.append(", name=");
builder.append(csName);
builder.append(lsAttrs.equals("") ? "" : "," + lsAttrs);
builder.append("]");
return builder.toString();
} | 3 |
public void insert(String table, String name[], String value[]) {
if(name.length != value.length){
String message = "not the same length";
throw new RangeException((short) 0, message);
}
try {
con = DriverManager.getConnection(url, user, password);
String questionMarkStm = "";
String stm = null;
String tableName = "";
//dynamically concat the tables for the insert statement
for (String tN : name) {
tableName += "," + tN;
}
tableName = tableName.replaceFirst(",","");
//dynamically create the right amount of question marks for the value
for(int i = 0; i<value.length;i++){
questionMarkStm += ", " + "?";
}
questionMarkStm = questionMarkStm.replaceFirst(", ","");
//create statement
stm = "INSERT INTO " + table + "(" + tableName
+ ") VALUES("+ questionMarkStm +")";
pst = con.prepareStatement(stm);
//set values
for(int i = 0; i<value.length; i++){
pst.setString(i+1, value[i]);
}
//execute statement me
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(InsertMethod.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(InsertMethod.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
} | 8 |
public void abort() {
mStarted = 0;
for (File file : mFiles.values()) {
file.delete();
}
mFiles.clear();
} | 1 |
public void setSolIdElemento(Integer solIdElemento) {
this.solIdElemento = solIdElemento;
} | 0 |
@Override
protected void act() {
if(state == State.START) {
Robot.getInstance().getMotion().getPilot().setRotateSpeed(180);
poses.add(new Pose(80, 0, 0));
chaine.add("BlackY");
poses.add(new Pose(30, 0, 0));
chaine.add("BlackY");
poses.add(new Pose(-20, 0, 0));
chaine.add("BlackY");
poses.add(new Pose(-80, 60, 0));
chaine.add("Blue");
poses.add(new Pose(-30, 60, 0));
chaine.add("Blue");
poses.add(new Pose(20, 60, 0));
chaine.add("Blue");
poses.add(new Pose(30, -60, 0));
chaine.add("Green");
poses.add(new Pose(-20, -60, 0));
chaine.add("Green");
doBehavior(new FollowLineBehavior(100, false));
} else if(state == State.PLUCK_BUMPED) {
/*Pose pose = Robot.getInstance().getOdometryPoseProvider().getPose();
System.out.println("X = " + ((int) (pose.getX())));
System.out.println("Y = " + ((int) pose.getY()));
System.out.println("H = " + pose.getHeading());*/
doBehavior(new ScoreBehavior());
} else if(state == State.SCORED) {
if(poses.size() > 0) {
Pose pose = poses.remove(0);
String s = chaine.get(0);
doBehavior(new AlignementToBehavior(pose, s.equals("Blue"), s));
}
else
stop();
} else if(state == State.ONLINE) {
String s = chaine.remove(0);
doBehavior(new FollowLineBehavior(150, s.equals("Green")));
} else if(state == State.PLUCK_BUMPED2) {
doBehavior(new ScoreBehavior());
} else if(state == State.SCORED2) {
stop();
}
} | 7 |
private void initializeEconomy() {
if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) {
throw new IllegalStateException("Vault plugin not found!");
}
RegisteredServiceProvider<Economy> provider =
plugin.getServer().getServicesManager().getRegistration(Economy.class);
if (provider == null) {
throw new IllegalStateException("Service provider not found.");
}
economy = provider.getProvider();
if (economy == null) {
throw new IllegalStateException("Economy can't be initialized.");
}
} | 3 |
final public void setHeader(String firstLine, String... additionalLines) {
header.clear();
header.add(firstLine);
if (additionalLines != null) {
for (String line : additionalLines) {
header.add(line);
}
}
onChange();
} | 2 |
public SerializedCodec(XMLCodec xmlcodec) {
this.xmlcodec = xmlcodec;
} | 0 |
@SuppressWarnings("unused")
private static void checkTime() {
long pre = System.nanoTime();
// 計測対象の処理
for (int i = 0; i < 100; i++) {
System.out.println("hello");
}
long post = System.nanoTime();
NumberFormat nf = NumberFormat.getNumberInstance();
System.out.println("[" + nf.format((post - pre)/1000) + "] μ sec" );
} | 1 |
@Override
public boolean keyDown(int keycode) {
if (keycode == Keys.ESCAPE) {
((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu(
game));
}
switch (keycode) {
case Keys.W:
break;
}
switch (keycode) {
case Keys.S:
break;
}
switch (keycode) {
case Keys.A:
break;
}
switch (keycode) {
case Keys.D:
break;
}
return true;
} | 5 |
private boolean saveFile(String filename) {
boolean success;
String editorString;
FileWriter fwriter;
PrintWriter outputFile;
try {
fwriter = new FileWriter(filename);
outputFile = new PrintWriter(fwriter);
editorString = editorText.getText();
outputFile.print(editorString);
outputFile.close();
success = true;
} catch (IOException e) {
success = false;
}
return success;
} | 1 |
public DefaultMutableTreeNode getTreeList() {
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(Integer.toString(currentId) + " - " + getType(getInterface().id, getInterface().type), true);
treeModel = new DefaultTreeModel(parent);
if (getInterface() != null) {
if (getInterface().children != null) {
for (int index = 0; index < getInterface().children.size(); index++) {
RSInterface rsi_1 = RSInterface.getInterface(getInterface().children.get(index));
DefaultMutableTreeNode child = new DefaultMutableTreeNode(Integer.toString(getInterface().children.get(index)) + " - " + getType(rsi_1.id, rsi_1.type));
treeModel.insertNodeInto(child, parent, index);
if (rsi_1.children != null) {
for (int childIndex = 0; childIndex < rsi_1.children.size(); childIndex++) {
RSInterface rsi_2 = RSInterface.getInterface(rsi_1.children.get(childIndex));
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(Integer.toString(rsi_1.children.get(childIndex)) + " - " + getType(rsi_2.id, rsi_2.type));
treeModel.insertNodeInto(child2, child, childIndex);
}
}
}
}
}
return parent;
} | 5 |
public static void main ( String[] args )
{
// test default constructor
ArrayLinearList<Integer> x = new ArrayLinearList<>( );
// test size
System.out.println( "Initial size is " + x.size( ) );
// test isEmpty
if( x.isEmpty( ) )
System.out.println( "The list is empty" );
else System.out.println( "The list is not empty" );
// test put
x.add( 0, new Integer( 2 ) );
x.add( 1, new Integer( 6 ) );
x.add( 0, new Integer( 1 ) );
x.add( 2, new Integer( 4 ) );
// test toString
System.out.println( "The list is " + x );
// output using an iterator
Iterator<Integer> y = x.iterator( );
while( y.hasNext( ) )
System.out.print( y.next( ) + " " );
System.out.println( );
// test indexOf
int index = x.indexOf( new Integer( 4 ) );
if( index < 0 )
System.out.println( "4 not found" );
else
System.out.println( "The index of 4 is " + index );
index = x.indexOf( new Integer(3) );
if( index < 0 )
System.out.println( "3 not found" );
else
System.out.println( "The index of 3 is " + index );
// test get
System.out.println( "Element at 0 is " + x.get( 0 ) );
System.out.println( "Element at 3 is " + x.get( 3 ) );
// test remove
System.out.println( x.remove( 1 ) + " removed" );
System.out.println( "The list is " + x );
System.out.println( x.remove( 2 ) + " removed" );
System.out.println( "The list is " + x );
if( x.isEmpty( ) )
System.out.println( "The list is empty" );
else System.out.println( "The list is not empty" );
System.out.println( "List size is " + x.size( ) );
} | 5 |
private void checkModelFieldExist(Class<?> queryParamsClass,
Class<?> modelClass) throws Exception {
StringBuilder modelFieldErroMsg = new StringBuilder();
for (Field callField : queryParamsClass.getDeclaredFields()) {
QueryCondition conditionAnno = callField
.getAnnotation(QueryCondition.class);
OrderBy orderByAnno = callField.getAnnotation(OrderBy.class);
if (conditionAnno == null && orderByAnno == null) {
continue;
}
String fieldName = "";
if (conditionAnno != null && orderByAnno == null) {
fieldName = conditionAnno.field();
} else if (orderByAnno != null) {
fieldName = orderByAnno.field();
}
modelFieldErroMsg.append(this
.checkFieldExist(fieldName, modelClass));
}
if (!modelFieldErroMsg.toString().isEmpty()) {
throw new Exception(modelFieldErroMsg.toString());
}
} | 9 |
@Override
public void collideWith(Element e) {
super.collideWith(e);
if (e instanceof IdentityDisc)
dropFlagOnAdjacentPosition(getGrid().getElementPosition(this));
} | 1 |
public static int[] convert(String s,int len){
//a = 97, A = 65, difference = 32
int defaul[] = {62};
int st[] = new int[len];
for(int i = 0; i < len; i++){
int val = (int)(s.charAt(0));
int value = 0;
if(val>= 65){
if(val < 91);
else if(val < 97){
return defaul;
}
else if(val <= 97+25){
val = val-32;
}
}
else
return defaul;
val = getNote((char)(val));
value = val;
if(s.charAt(1)=='S'||s.charAt(1)=='s'){
value++;
}
else
if(s.charAt(1)=='f'||s.charAt(1)=='F'){
value--;
}
int n = Integer.parseInt(s.substring(2,s.indexOf(';')));
System.out.println(n);
value += n*12;
st[i] = value;
s = s.substring(s.indexOf('.')+1,s.length());
System.out.println(st[i]);
}
return st;
} | 9 |
boolean checkValidFeedback(String feedback){
try {
check(feedback.length() == 4);
check(feedback.charAt(1) == 'b');
check(feedback.charAt(3) == 'w');
int b = feedback.charAt(0) - '0';
int w = feedback.charAt(2) -'0';
check(b <= CL && b >= 0);
check(w <= CL && w >= 0);
check(b+w <=CL && b+w >= 0);
} catch (Exception e) {
return false;
}
return true;
} | 4 |
public MyList ownees(String player) {
MyList ownees = new MyList();
if (!(player == null || player.equals("red") || player.equals("blue") ))
return null;
// Iterate over all Hexpos's
Set set = owner.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Hexpos hp = (Hexpos) it.next();
if (owner.containsKey(hp) && owner.get(hp) == player)
ownees.add(hp);
}
return ownees;
} | 6 |
public int longestConsecutive(int[] num) {
int n = num.length;
if (n<=1){
return n;
}
HashMap<Integer,Integer> checkBox = new HashMap<Integer,Integer>();
for (int i = 0;i<n;i++) {
checkBox.put(num[i],1);
}
int result = 1;
for (int i = 0;i<n;i++) {
if(checkBox.containsKey(num[i])){
int findKey = num[i]+1;
while (checkBox.containsKey(findKey)){
checkBox.put(num[i],checkBox.get(num[i])+1);
checkBox.remove(findKey);
findKey++;
}
findKey = num[i]-1;
while (checkBox.containsKey(findKey)){
checkBox.put(num[i],checkBox.get(num[i])+1);
checkBox.remove(findKey);
findKey--;
}
if (checkBox.get(num[i])>result){
result = checkBox.get(num[i]);
}
}
}
return result;
} | 7 |
private static <T> ArrayList<T> newArrayList(List<T> values) {
if (values != null) {
return new ArrayList<T>(values) ;
}
else {
return new ArrayList<T>();
}
} | 1 |
@Override
public void handle(SocketConnection connection, String[] params, PrintWriter printWriter)
{
try {
int id = Integer.parseInt(params[1]);
if(ServerCore.instance().connections.get(id) != null)
{
printWriter.println("Information on user " + id + ":");
printWriter.println("Username: " + (ServerCore.instance().connections.get(id).isAuthenticated() ? ServerCore.instance().connections.get(id).user.username : "unknown"));
printWriter.println("Logged messages:");
printWriter.println("----------------");
if(ServerCore.instance().connections.get(id).isAuthenticated())
{
if(ServerCore.instance().connections.get(id).user.messages.size() != 0)
{
for(String message : ServerCore.instance().connections.get(id).user.messages)
{
printWriter.println(message);
}
}
else {
printWriter.println("No messages found for this user.");
}
}
else {
if(ServerCore.instance().connections.get(id).tempMessages.size() != 0)
{
for(String message : ServerCore.instance().connections.get(id).tempMessages)
{
printWriter.println(message);
}
}
else {
printWriter.println("No messages found for this user.");
}
}
printWriter.println("----------------");
}
} catch(Exception e) {
printWriter.println("Invalid command usage.");
}
} | 8 |
public boolean startNewTourn(final GUI g) {
if (gameTask != null) {
gameTask.cancel(true);
}
gameTask = gameExecutor.submit(new Runnable() {
@Override
public void run() {
winners = runTournament(g);
}
});
return true;
} | 1 |
private Double rankDiffSwapThreeCards() {
Double rankdiff = 0.0;
int bestcardoneindex = 0;
int bestcardtwoindex = 0;
int bestcardthreeindex = 0;
Card bestcardtoswapcardone;
Card bestcardtoswapcardtwo;
Card bestcardtoswapcardthree;
for (int i = 0; i < hand.size() - 2 ; i++)
for (int j = i+1; j < hand.size() - 1 ; j++ )
for (int k = j+1; k < hand.size(); k++){
Double temprankdiff = rankDiffIfSwapped(i, j, k);
if (rankdiff < temprankdiff){
rankdiff = temprankdiff;
bestcardoneindex = i;
bestcardtwoindex = j;
bestcardthreeindex = k;
}
}
bestcardtoswapcardone = hand.get(bestcardoneindex);
bestcardtoswapcardtwo = hand.get(bestcardtwoindex);
bestcardtoswapcardthree = hand.get(bestcardthreeindex);
swapcardsthreecards.add(bestcardtoswapcardone);
swapcardsthreecards.add(bestcardtoswapcardtwo);
swapcardsthreecards.add(bestcardtoswapcardthree);
return rankdiff;
} | 4 |
private CodeRunResult runExecuteMethod(Object object, Method method) {
CodeRunResult result = new CodeRunResult();
Runnable runnable = () -> {
try {
result.setFailedTestMessages((List<String>) method.invoke(object));
result.setCompleted(true);
} catch (Exception e) {
if (e.getCause() != null) {
result.setExceptionMessage(e.getCause().toString());
} else {
result.setExceptionMessage(e.toString());
}
}
};
Thread thread = new Thread(runnable);
thread.start();
try {
thread.join(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!result.isCompleted() && result.getExceptionMessage() == null) {
result.setExceptionMessage("Submission took too long to run");
}
return result;
} | 5 |
protected FlacAudioSubFrame(int predictorOrder, int channelNumber, FlacAudioFrame audioFrame) {
this.predictorOrder = predictorOrder;
this.audioFrame = audioFrame;
this.blockSize = audioFrame.getBlockSize();
// Adjust sample size for channel number, if needed
// TODO Is this the right adjustment amount?
int sampleSizeBits = audioFrame.getBitsPerSample();
if (audioFrame.getChannelType() == FlacAudioFrame.CHANNEL_TYPE_LEFT && channelNumber == 1) {
sampleSizeBits++;
}
if (audioFrame.getChannelType() == FlacAudioFrame.CHANNEL_TYPE_RIGHT && channelNumber == 0) {
sampleSizeBits++;
}
if (audioFrame.getChannelType() == FlacAudioFrame.CHANNEL_TYPE_MID && channelNumber == 1) {
sampleSizeBits++;
}
this.sampleSizeBits = sampleSizeBits;
} | 6 |
public boolean deleteTracking(Tracking tracking)
throws AftershipAPIException,IOException,ParseException,JSONException{
String parametersExtra = "";
if(tracking.getId()!=null && !(tracking.getId().compareTo("")==0)){
parametersExtra = tracking.getId();
}else {
String paramRequiredFields = tracking.getQueryRequiredFields().replaceFirst("&", "?");
parametersExtra = tracking.getSlug()+ "/"+tracking.getTrackingNumber()+paramRequiredFields;
}
JSONObject response = this.request("DELETE","/trackings/"+parametersExtra,null);
if (response.getJSONObject("meta").getInt("code")==200)
return true;
else
return false;
} | 3 |
@Override
public boolean hasNext()
{
try
{
if (!resultSet.isLast())
{
return true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return false;
} | 2 |
public static int climbStairs(int n) {
if (n < 2) return n;
int[] ways = new int[n + 1];
for (int i = 0; i <= n; i++) {
if (i < 2) {
ways[i] = 1;
} else {
ways[i] = ways[i - 1] + ways[i - 2];
}
}
return ways[n];
} | 3 |
public static List<PDBStructure> reloadStructures(CyNetwork network,
CyIdentifiable id, List<CDDHit> hits) {
List<String> structures = getStructures(network, id);
if (structures == null || structures.size() == 0)
return null;
List<PDBStructure> structureList = new ArrayList<PDBStructure>();
Map<String, PDBStructure> structureMap = new HashMap<String, PDBStructure>();
// We actually use the CDDHit information to reload our structures because
// this is where the validated information gets stored
for (CDDHit hit: hits) {
String proteinId = hit.getProteinId();
String[] structChain = proteinId.split("\\.");
if (structChain.length == 2) {
if (!structureMap.containsKey(structChain[0])) {
PDBStructure s = new PDBStructure(structChain[0], null);
structureMap.put(structChain[0], s);
structureList.add(s);
}
structureMap.get(structChain[0]).addChain(structChain[1]);
}
}
if (structureList.size() == 0)
return null;
return structureList;
} | 6 |
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
} | 1 |
public static SSLContext setupClientSSL(String cert_path, String cert_password, boolean trustAll)
throws SSLConfigurationException {
SSLContext sslContext=null;
try {
kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = p12ToKeyStore(cert_path, cert_password);
kmf.init(ks, cert_password.toCharArray());
sslContext=getSSLContext(kmf.getKeyManagers(), trustAll);
} catch (NoSuchAlgorithmException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (KeyStoreException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (UnrecoverableKeyException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (CertificateException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (NoSuchProviderException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (IOException e) {
throw new SSLConfigurationException(e.getMessage(), e);
}
return sslContext;
} | 6 |
public SaltAndPepperDialog(final Panel panel) {
setTitle("Salt and pepper");
setBounds(1, 1, 250, 150);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width / 3 - getWidth() / 3, size.height / 3
- getHeight() / 3);
this.setResizable(false);
setLayout(null);
JPanel paramPanel = new JPanel();
paramPanel.setBorder(BorderFactory.createTitledBorder("Probabilities"));
paramPanel.setBounds(0, 0, 250, 75);
JLabel minLabel = new JLabel("Min = %");
final JTextField minTextField = new JTextField("1");
minTextField.setColumns(3);
JLabel maxLabel = new JLabel("Max = %");
final JTextField maxTextField = new JTextField("99");
maxTextField.setColumns(3);
JButton okButton = new JButton("OK");
okButton.setSize(250, 40);
okButton.setBounds(0, 75, 250, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double minP = 0;
double maxP = 0;
try {
minP = Double.valueOf(minTextField.getText());
maxP = Double.valueOf(maxTextField.getText());
} catch (NumberFormatException ex) {
new MessageFrame("Invalid values");
return;
}
if (minP > maxP || minP < 0 || minP > 100 || maxP < 0 || maxP > 100) {
new MessageFrame("Invalid values");
return;
}
Image image = panel.getImage();
panel.setImage(NoiseUtils.saltAndPepper(image, minP * 0.01, maxP * 0.01));
panel.repaint();
dispose();
}
});
paramPanel.add(minLabel);
paramPanel.add(minTextField);
paramPanel.add(maxLabel);
paramPanel.add(maxTextField);
this.add(paramPanel);
this.add(okButton);
} | 6 |
public void addRestrictionToEvent(String eventIdentifier, String restrictionIdentifier)
{
//Get that restriction
Restriction restrictionToAdd = null;
for(Restriction r: restrictions){
if(r.getIdentifier().equals(restrictionIdentifier))
restrictionToAdd = r;
}
//Check that it exists
if(restrictionToAdd == null)
throw new IllegalArgumentException("There's no restriction with the identifier '"+restrictionIdentifier+"'.");
for(Event e: events){
if(e.getIdentifier().equals(eventIdentifier))
{
//We check if the restriction is already there
for(Restriction r: e.getRestrictions()){
if(r.getIdentifier().equals(restrictionIdentifier))
throw new IllegalArgumentException("There's already a restriction with that identifier. Identifiers need to be unique.");
}
//If not, just add it
e.getRestrictions().add(restrictionToAdd);
return;
}
}
throw new IllegalArgumentException("There's no event with the identifier '"+eventIdentifier+"'.");
} | 7 |
public static TableModel createTableModel(final CSTable src) {
final List<String[]> rows = new ArrayList<String[]>();
for (String[] row : src.rows()) {
rows.add(row);
}
return new TableModel() {
@Override
public int getColumnCount() {
return src.getColumnCount();
}
@Override
public String getColumnName(int column) {
return src.getColumnName(column);
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rows.get(rowIndex)[columnIndex];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// rows.get(rowIndex)[columnIndex] = (String) aValue;
}
@Override
public void addTableModelListener(TableModelListener l) {
}
@Override
public void removeTableModelListener(TableModelListener l) {
}
};
} | 2 |
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.hasPermission("CreeperWarning.warn")) {
if (args.length >= 2) {
String prefix = CreeperWarningMain.chat.getPlayerPrefix((Player) sender);
prefix = CreeperWarningMain.replaceChatColors(prefix);
plugin.toPlayer = args[0];
this.toPlayer = plugin.toPlayer;
String[] alltheargs = args;
StringBuilder reason = new StringBuilder();
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + NAME + "This command my only be run as a player!");
} else {
if (!(args.length <= 1)) {
for (String s : alltheargs) {
if (s.equalsIgnoreCase(toPlayer)) {
s.equals("");
continue;
}
reason.append(s);
reason.append(" ");
}
int test = plugin.lookUp(toPlayer);
if (Bukkit.getPlayer(toPlayer) != null) {
if (test == 0) {
WarnLevel.addPlayer(Bukkit.getPlayer(toPlayer));
} else {
double added = Math.floor(Math.round((WarnLevel.getPoints(Bukkit.getPlayer(toPlayer)) / 2) + 5) * Math.sin(Math.PI / Math.sqrt(1)) * 10000000000000000d);
WarnLevel.addPointsToLevel(Bukkit.getPlayer(toPlayer), Math.floor(Math.round((WarnLevel.getPoints(Bukkit.getPlayer(toPlayer)) / 2) + 5) * ((Math.sin(Math.PI / Math.sqrt(1)))) * 10000000000000000d));
double totalPoints = WarnLevel.getPoints(Bukkit.getPlayer(toPlayer));
// Bukkit.broadcastMessage("Player: " + toPlayer
// + " Has had "+ added
// +" points added! Total Points: " +
// totalPoints);
pds.editDataLevel(toPlayer, (double) totalPoints);
}
// if((WarnLevel.getPoints(Bukkit.getPlayer(toPlayer))
// >= 50) &&
// (WarnLevel.getPoints(Bukkit.getPlayer(toPlayer))
// <= 100)){
// Bukkit.getPlayer(toPlayer).kickPlayer("You have gained too many damn points, last warning: "
// + reason);
// }
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + plugin.getConfig().getString("customMessageLineOne"));
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + plugin.getConfig().getString("customMessageLineTwo"));
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + plugin.getConfig().getString("customMessageLineThree") + ": " + reason);
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + plugin.getConfig().getString("customMessageLineFour") + ": " + prefix + sender.getName());
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + "" + ChatColor.BOLD + plugin.getConfig().getString("customMessageLineFive") + ": " + dateNow);
Bukkit.getServer().getPlayer(toPlayer).sendMessage(ChatColor.DARK_RED + plugin.getConfig().getString("customMessageLineSix"));
plugin.lookUpPlayerWarns(toPlayer, sender);
plugin.getLogger().info(ChatColor.GREEN + NAME + sender.getName() + " has warned " + toPlayer + " for " + reason);
sender.sendMessage(ChatColor.RED + NAME + ChatColor.GREEN + "Player " + toPlayer + " has been warned!");
plugin.logToFile(toPlayer + "|" + reason.toString() + "|" + sender.getName() + "|" + dateNow);
} else {
sender.sendMessage(CreeperWarningMain.NAME + ChatColor.RED + "Player not found!");
}
}
}
} else {
sender.sendMessage("The correct command is /warn <Player> <Reason>");
}
}
return false;
} | 8 |
public AnObject(int aField1, long aField2, Object internalObject) {
this.aField1 = aField1;
this.aField2 = aField2;
this.internalObject = internalObject;
} | 0 |
public static Language load(String lang) throws FileNotFoundException, IOException, InvalidConfigurationException, IllegalArgumentException, IllegalAccessException
{
//Create the new language file that will be returned.
Language l = new Language();
//Get the lines of the
String[] lines = readFile(getLanguageFileName(lang), Language.class.getFields().length-1, lang);
//Load for each field
for (Field f : Language.class.getFields())
{
//Make sure we can access it
f.setAccessible(true);
//Skip the languages field that lists the current languages.
if (!f.getName().equalsIgnoreCase("Languages"))
f.set(l, getVal(lines, f.getName()));
}
//Return the loaded language.
return l;
} | 2 |
private static int applySpecialScore(String passwd)
{
int specials = 0;
// SPECIAL CHAR
Matcher m = Pattern.compile(".??[:,!,@,#,$,%,^,&,*,?,_,~]").matcher(passwd);
while (m.find()) // [verified] at least one special character
{
specials += 1;
}
if (specials == 1)
{
log.debug("5 points for 1 special character.");
return 5;
}
if (specials > 1)
{
log.debug("10 points for at least 2 special characters.");
return 10;
}
return 0;
} | 3 |
public boolean newRun()
{
Field f, f2;
if(this.newVal > 0)
{
return false;
}
else{
for(int i = this.fieldSize; i < this.finishindex; i++)
{
f = pole.get(i);
if(f.playerColor == player && f.figure != null)
{
f2 = pole.get(f.figure.startFieldId);
if(f2.figure != null && f2.figure.playerId == this.player)
{
return false;
}
if(f2.figure == null || f2.figure.playerId != this.player)
{
if(f2.figure != null)
{
Field f3;
f3 = pole.get(f2.figure.startFieldId);
f3.figure = f2.figure;
f3.figure.position = -1;
Icon icon = f3.figureLabel.getIcon();
f3.figureLabel.setIcon(f2.figureLabel.getIcon());
f2.figure = f.figure;
f2.figure.position = 0;
f2.figureLabel.setIcon(f.figureLabel.getIcon());
f.figure = null;
f.figureLabel.setIcon(icon);
this.pole.set(f.id,f);
this.pole.set(f2.id,f2);
this.pole.set(f3.id,f3);
return true;
}
else
{
f2.figure = f.figure;
f2.figure.position = 0;
Icon icon;
icon = f2.figureLabel.getIcon();
f2.figureLabel.setIcon(f.figureLabel.getIcon());
f.figure = null;
f.figureLabel.setIcon(icon);
this.pole.set(f.id,f);
this.pole.set(f2.id,f2);
return true;
}
}
}
}
}
return false;
} | 9 |
public BigDecimal getBigDecimal(BigDecimal defaultValue) {
try {
if (isNull()) {
return defaultValue;
}
if (data instanceof Double) {
return BigDecimal.valueOf((Double) data);
}
if (data instanceof Long) {
return BigDecimal.valueOf((Long) data);
}
if (data instanceof Integer) {
return BigDecimal.valueOf((Integer) data);
}
if (data instanceof Long) {
return BigDecimal.valueOf((Long) data);
}
return new BigDecimal(asString("").replace(",", "."),
MathContext.UNLIMITED);
} catch (NumberFormatException e) {
return defaultValue;
}
} | 6 |
public static void f() throws MyException {
System.out.println("Throwing MyException from f()");
throw new MyException();
} | 0 |
public config(){
String settings = fileHandler.readFile("config.jShare");
ArrayList<String> config = new ArrayList<String>();
if(!settings.isEmpty()){
Matcher m = Pattern.compile("\\{([^}]+)\\}").matcher(settings);
while(m.find()) {
config.add(m.group(1));
}
if(config.get(0).contains("\\|"))
addresses = config.get(0).split("\\|");
if(config.get(1).contains("\\|"))
ports = config.get(1).split("\\|");
address = (addresses == null ? config.get(0) : addresses[0]);
port = (ports == null ? config.get(1) : ports[0]);
if(config.size() > 2)
userEmail = (config.get(2));
if(config.size() > 3){
theme = themeNames.valueOf(config.get(3));
}
_Theme = new themes(theme);
} else {
address = "jshare.ddns.net";
port = "25984";
userEmail = "email@email.com";
theme = themeNames.DarkTheme;
_Theme = new themes(theme);
this.Save();
}
try {
ipAddress = InetAddress.getByName(address).getHostAddress();
} catch(Exception e){
System.err.println(e.getMessage());
}
} | 9 |
public void mergeList(int a[], int start1, int end1, int start2, int end2) {
int temp[] = new int[end1 - start1 + end2 - start2 + 2];
int ptr1 = start1, ptr2 = start2, ptrmain = 0;
while (ptr1 <= end1 && ptr2 <= end2) {
if (a[ptr1] < a[ptr2]) {
temp[ptrmain++] = a[ptr1++];
} else {
temp[ptrmain++] = a[ptr2++];
}
}
while (ptr1 <= end1) {
temp[ptrmain++] = a[ptr1++];
}
while (ptr2 <= end2) {
temp[ptrmain++] = a[ptr2++];
}
ptrmain = 0;
for (int i = start1; i <= end1; i++) {
a[i] = temp[ptrmain++];
}
for (int i = start2; i <= end2; i++) {
a[i] = temp[ptrmain++];
}
} | 7 |
public String escape(String in) {
if (in==null) {
return "";
}
CharSequence collapsed = Whitespace.collapseWhitespace(in);
StringBuffer sb = new StringBuffer(collapsed.length() + 10);
for (int i=0; i<collapsed.length(); i++) {
char c = collapsed.charAt(i);
if (c=='<') {
sb.append("<");
} else if (c=='>') {
sb.append(">");
} else if (c=='&') {
sb.append("&");
} else if (c=='\"') {
sb.append(""");
} else if (c=='\n') {
sb.append("
");
} else if (c=='\r') {
sb.append("
");
} else if (c=='\t') {
sb.append("	");
} else {
sb.append(c);
}
}
return sb.toString();
} | 9 |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String genVer : this) {
String name = nameByVersion.get(genVer).replace('_', ' ');
String ref = referenceByVersion.get(genVer);
sb.append("\t" + genVer);
sb.append("\t" + name);
if (ref != null) sb.append("\t" + ref);
sb.append("\n");
}
return sb.toString();
} | 2 |
public String toDiffString(String jobId) {
String f1 = "%1$-3.0f";
String f2 = "%1$-3.1f";
float mOUdf = exOU - rmOU;
float xOUdf = exOU - rxOU;
float mNGUdf = exNGU - rmNGU;
float xNGUdf = exNGU - rxNGU;
float xHeapUdf = exHeapU - rxHeapU;
float RSSdf = exHeapU - rxRSS;
float mOUrt = rmOU == 0 ? 100 : Math.abs(mOUdf) * 100 / rmOU;
float xOUrt = rxOU == 0 ? 100 : Math.abs(xOUdf) * 100 / rxOU;
float mNGUrt = rmNGU == 0 ? 100 : Math.abs(mNGUdf) * 100 / rmNGU;
float xNGUrt = rxNGU == 0 ? 100 : Math.abs(xNGUdf) * 100 / rxNGU;
float xHeapUrt = rxHeapU == 0 ? 100 : Math.abs(xHeapUdf) * 100 / rxHeapU;
float RSSrt = rxRSS == 0 ? 100 : Math.abs(RSSdf) * 100 / rxRSS;
return xmx + "\t" + xms + "\t" + ismb + "\t" + RN + "\t"
+ String.format(f1, mOUdf) + "\t" + String.format(f1, xOUdf) + "\t"
+ String.format(f1, mNGUdf) + "\t" + String.format(f1, xNGUdf) + "\t"
+ String.format(f1, xHeapUdf) + "\t" + String.format(f1, RSSdf) + "\t"
+ String.format(f2, mOUrt) + "\t" + String.format(f2, xOUrt) + "\t"
+ String.format(f2, mNGUrt) + "\t" + String.format(f2, xNGUrt) + "\t"
+ String.format(f2, xHeapUrt) + "\t" + String.format(f2, RSSrt) + "\t"
+ jobId + "\t" + rJobId + "\t"
+ String.format(f1, rmOU) + "\t" + String.format(f1, rxOU) + "\t" + String.format(f1, exOU) + "\t"
+ String.format(f1, rmNGU) + "\t" + String.format(f1, rxNGU) + "\t" + String.format(f1, exNGU) + "\t"
+ String.format(f1, rxHeapU) + "\t" + String.format("%1$-3d", rxRSS) + "\t" + String.format(f1, exHeapU);
} | 6 |
*/
void wordExtendBackwards( Variant v )
{
char pc;
int index = v.startIndex;
int offset = v.startOffset;
Pair p = pairs.get( index );
do
{
offset--;
while ( offset < 0 || p.length() == 0 )
{
index = previous( index,(short)v.versions.nextSetBit(1) );
if ( index >= 0 )
{
p = pairs.get( index );
offset = p.length()-1;
}
else
break;
}
// offset points to the previous character
pc = p.getChars()[offset];
if ( Character.isWhitespace((char)pc)||isPunctuation(pc) )
break;
else
{
v.startIndex = index;
v.startOffset = offset;
v.length++;
}
}
while ( index >= 0 );
} | 6 |
protected Environmental[] makeTalkers(MOB s, Environmental p, Environmental t)
{
final Environmental[] Ms=new Environmental[]{s,p,t};
Ms[0]=getInvisibleMOB();
if(p instanceof MOB)
{
if(p==s)
Ms[1]=Ms[0];
else
Ms[1]=getInvisibleMOB();
}
else
if(p!=null)
{
Ms[1]=getInvisibleItem();
}
if(t instanceof MOB)
{
if(p==s)
Ms[2]=Ms[0];
else
if(p==s)
Ms[2]=Ms[0];
else
Ms[2]=getInvisibleMOB();
}
else
if(t!=null)
{
Ms[2]=getInvisibleItem();
}
return Ms;
} | 7 |
public static void main(String[] args) {
System.out.println("testaticTstatic".intern() == new String("testaticTstatic").intern());
} | 0 |
protected synchronized void doStart()
throws Exception
{
log.info("Version "+Version.getImplVersion());
MultiException mex = new MultiException();
statsReset();
if (log.isDebugEnabled())
{
log.debug("LISTENERS: "+_listeners);
log.debug("HANDLER: "+_virtualHostMap);
}
if (_requestLog!=null && !_requestLog.isStarted())
{
try{
_requestLog.start();
}
catch(Exception e){mex.add(e);}
}
HttpContext[] contexts = getContexts();
for (int i=0;i<contexts.length;i++)
{
HttpContext context=contexts[i];
try{context.start();}catch(Exception e){mex.add(e);}
}
for (int l=0;l<_listeners.size();l++)
{
HttpListener listener =(HttpListener)_listeners.get(l);
listener.setHttpServer(this);
if (!listener.isStarted())
try{listener.start();}catch(Exception e){mex.add(e);}
}
mex.ifExceptionThrowMulti();
} | 9 |
public static void main(String[] args) {
w = new Worker();
} | 0 |
private boolean inside( int posX, int posY ){
if(posX>=this.posX && posX<=this.posX+this.width){
if(posY>=this.posY && posY<=this.posY+this.height){
return true;
}
}
return false;
} | 4 |
private void flushSessions() {
if (flushingSessions.size() == 0)
return;
for (;;) {
DatagramSessionImpl session = flushingSessions.poll();
if (session == null)
break;
session.setScheduledForFlush(false);
try {
boolean flushedAll = flush(session);
if (flushedAll && !session.getWriteRequestQueue().isEmpty() && !session.isScheduledForFlush()) {
scheduleFlush(session);
}
} catch (IOException e) {
session.getFilterChain().fireExceptionCaught(session, e);
}
}
} | 7 |
public void handleRemoveInputAlphabetButton() {
Object alphabet = startView.getInputAlphabetList().getSelectedValue();
if(startView.getInputAlphabetList().getSelectedIndex() != -1){
startView.getInputAlphabetItems().removeElement(alphabet);
if(startView.getTapeAlphabetItems().contains(alphabet)){
startView.getTapeAlphabetItems().removeElement(alphabet);
}
}
if(startView.getInputAlphabetItems().getSize() < 1){
startView.getNextButton().setEnabled(false);
}
} | 3 |
public boolean duplicateEntrySection(int x, int y, String entry) {
boolean duplicate = false;
int sx = (x/size)*size, sy = (y/size)*size;
for (int i=sx; i < sx+size && !duplicate; i++) {
for (int j=sy; j < sy+size && !duplicate; j++) {
duplicate = (sudokuGrid[i][j].equals(entry) ? true : false);
}
}
return duplicate;
} | 5 |
public void updurgency(HWindow wnd, int level) {
if ((wnd == awnd) && vc.c)
level = -1;
if (level == -1) {
if (wnd.urgent == 0)
return;
wnd.urgent = 0;
} else {
if (wnd.urgent >= level)
return;
wnd.urgent = level;
}
Button b = btns.get(wnd);
if (urgcols[wnd.urgent] != null)
b.change(wnd.title, urgcols[wnd.urgent]);
else
b.change(wnd.title);
int max = 0;
for (HWindow w : wnds) {
if (w.urgent > max)
max = w.urgent;
}
fb.urgency = max;
} | 8 |
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] numbers = new int[2][5];
int[] counters = new int[2];
for(int i = 0; i < 15; i++){
int x = s.nextInt();
int ind = Math.abs(x) % 2 == 1 ? 0 : 1;
numbers[ind][counters[ind]] = x;
counters[ind]++;
if(counters[ind] == 5){
counters[ind] = 0;
for(int j = 0; j < 5; j++){
System.out.printf("%s[%d] = %d\n", ind == 1 ? "par" : "impar", j, numbers[ind][j]);
}
}
}
for(int i = 0; i <= 1; i++){
for(int j = 0; j < counters[i]; j++){
System.out.printf("%s[%d] = %d\n", i == 1 ? "par" : "impar", j, numbers[i][j]);
}
}
} | 8 |
public void key(KeyEvent e, int s) {
int Key = e.getKeyCode();
if (s == KEY_PRESS) {
boolean rep = false;
for (int i=0; i <= keys.size()-1; i++) {
if (keys.get(i) == Key) {
rep = true;
}
}
if (keys.size() < max_keys && !rep) {
keys.add(Key);
}
} else if (s == KEY_RELEASE) {
for (int i=0; i <= keys.size()-1; i++) {
if (keys.get(i) == Key) {
keys.remove(i);
}
}
}
} | 8 |
static String toUnsignedHex8String(long pValue)
{
String s = Long.toString(pValue, 16);
//force length to be eight characters
if (s.length() == 0) {return "00000000" + s;}
else
if (s.length() == 1) {return "0000000" + s;}
else
if (s.length() == 2) {return "000000" + s;}
else
if (s.length() == 3) {return "00000" + s;}
else
if (s.length() == 4) {return "0000" + s;}
else
if (s.length() == 5) {return "000" + s;}
else
if (s.length() == 6) {return "00" + s;}
else
if (s.length() == 7) {return "0" + s;}
else{
return s;
}
}//end of Log::toUnsignedHex8String | 8 |
private void subMenu(String sub) {
this.clear();
StringBuilder sb = new StringBuilder();
sb.append(sub.charAt(0)).append(sub.substring(1).toLowerCase());
System.out.println("=========== " + sb + " MENU ============");
System.out.println("\t1. Add " + sb);
System.out.println("\t2. Update " + sb);
System.out.println("\t3. Delete " + sb);
System.out.println("\t4. Search " + sb);
System.out.println("\t5. Back");
System.out.println("Enter your choice: ");
try {
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
if ("student".equals(sub.toLowerCase())) {
StudentController.INSTANCE.createStudent();
} else if ("subject".equals(sub.toLowerCase())) {
SubjectController.INSTANCE.createSubject();
}
case 2:
if ("student".equals(sub.toLowerCase())) {
System.out.println("Enter student id:");
int stuId = scanner.nextInt();
System.out.println("Enter subject id:");
int subId = scanner.nextInt();
System.out.println("Enter score:");
float score = scanner.nextFloat();
StudentController.INSTANCE.addMark(stuId, subId, score);
} else if ("subject".equals(sub.toLowerCase())) {
}
case 5:
this.clear();
this.menu();
break;
default:
this.clear();
this.subMenu(sub);
}
} catch (InputMismatchException ex) {
this.clear();
System.out.println("Your choice is not correct, pls enter 1-5");
this.subMenu(sub);
} catch (NullPointerException ex) {
System.err.println("Sub type is not correct");
}
} | 9 |
@Override
public void run() {
count++;
if(automaticCars < 40) {
Car c = new AutomaticCar(id++);
c.setSpeed(45);
c.setReceiveBehavior(new AutomaticReceive(c));
c.setSendBehavior(new AutomaticSend(c));
towerChannel.registerCar(c);
automaticCars++;
}
if(manualCars < 50) {
Car c = new ManualCar(id++);
c.setSpeed(45);
c.setReceiveBehavior(new ManualReceive(c));
c.setSendBehavior(new ManualSend(c));
towerChannel.registerCar(c);
manualCars++;
}
/*if(automaticCars < 5){
Car c = new AutomaticCar(id++);
c.setSpeed(45);
c.setReceiveBehavior(new ReceiveAdapter(c));
c.setSendBehavior(new SendAdapter(c));
towerChannel.registerCar(c);
automaticCars++;
}*/
List<Car> cars = getRegisteredCars();
for(Car c : cars) {
int delta;
if(c instanceof ManualCar && c.getDisplay().equals("Decrease speed"))
delta = (int)(Math.random()*10) - 10;
else
delta = (int)(Math.random()*10) - 4;
c.setSpeed(c.getSpeed() + delta);
}
if(count == 5) {
if (cars.size() > 0) {
Car c = cars.get((int)(Math.random()*(cars.size()-1)));
c.exit();
}
count = 0;
}
} | 7 |
@Override
public void visitRow(Row row) {
List<UiGlyph> glyphs = row.getUiGlyphs();
for (UiGlyph uiGlyph : glyphs) {
this.uiGlyphs.add(uiGlyph);
uiGlyph.getGlyph().accept(this);
}
/* This checking is required for last word. */
if (this.currentWord.length() > 0) {
this.spellCheck();
}
} | 2 |
public void onAction(String name, boolean isPressed, float tpf) {
if (isPressed) {
if (name.equals(KeyMapper.SHOW_PLAYER_LIST)) {
togglePlayerList(true);
} else if (name.equals(KeyMapper.SHOW_CHAT)) {
if (!chat) {
toggleChat(true);
}
} else if (name.equals(KeyMapper.HIDE_CHAT)) {
if (chat) {
toggleChat(!chat);
} else {
toggleMenu(!menu);
}
}
} else {
if (name.equals(KeyMapper.SHOW_PLAYER_LIST)) {
togglePlayerList(false);
}
}
} | 7 |
public void modificarAudio(int id, ArrayList datos)
{
// Cambiamos todos los datos, que se puedan cambiar, a minúsculas
for(int i = 0 ; i < datos.size() ; i++)
{
try{datos.set(i, datos.get(i).toString().toLowerCase());}
catch(Exception e){}
}
biblioteca.modificarRegistros("audio", id, datos);
} | 2 |
@Override
public boolean placeResearvation(int rowNum, Column column, Passenger passenger) throws ClassCastException, IndexOutOfBoundsException, IllegalArgumentException, NullPointerException {
if (!isInitialized) {
throw new NullPointerException("Passenger List has not been initialized");
}
if (rowNum < 0 || rowNum > passengerList.size()) {
throw new IndexOutOfBoundsException("The row# is out of bound");
}
if (column.index() < 0 || column.index() > passengerList.get(0).size()) {
throw new IndexOutOfBoundsException("The column# is out of bound");
}
List<Passenger> _passenger = passengerList.get(rowNum -1);
if (_passenger.get(column.index() -1) == null) {
_passenger.set(column.index() -1, passenger);
return true;
}else{
throw new IllegalArgumentException("A passenger is already in the list");
}
} | 6 |
private List<Integer> shrinkHeap(List<Integer> list) {
for (int n = list.size() - 1; n >= 0; n--) {
appUtil.swap(list, 0, n);
int parent = 0;
while (true) {
int leftChild = 2 * parent + 1;
if (leftChild >= n) break;
int rightChild = leftChild + 1;
int maxChild = leftChild;
if (rightChild < n && list.get(leftChild).compareTo(list.get(rightChild)) < 0)
maxChild = rightChild;
// swap child & parent if parent < child
if (list.get(parent).compareTo(list.get(maxChild)) < 0) {
appUtil.swap(list, parent, maxChild);
parent = maxChild;
} else {
break;
}
}
}
return list;
} | 6 |
public void keyTyped(KeyEvent e) {
char key = e.getKeyChar();
System.out.println("KEY TYPED: " + key);
switch(key) {
case 's':
//System.out.println("About to smooth!");
if(_wps.getSmoothPath().size() > 2) _wps.smoothWeighted(_tolerance);
update();
repaint();
break;
case 'r':
//System.out.println("About to smooth!");
if(_wps.getSmoothPath().size() > 2) _wps.reset();
update();
repaint();
break;
default:
//System.out.println("Key " + key + " Typed");
}
} | 4 |
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
} | 2 |
public void initSamples() {
for( int ns = 0; ns < numberOfSamples; ns++ )
for( int i = 0; i < n; i++ ) {
samples[ns][i] = i + 1;
rankSum[ns][i] = 0;
}
} | 2 |
public static void startupHttpServerImpl() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/HTTP/SUN", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
Sun.SGT_SUN_HTTP_SERVER_SUN = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("HTTP-SERVER-SUN", null, 1)));
Sun.SYM_SUN_CURRENT_SERVER_PORT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("CURRENT-SERVER-PORT", null, 0)));
Sun.KWD_OK = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("OK", null, 2)));
Sun.SGT_SUN_HTTP_EXCHANGE_SUN = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("HTTP-EXCHANGE-SUN", null, 1)));
Sun.SYM_SUN_RESPONSE_CODE = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("RESPONSE-CODE", null, 0)));
Sun.SYM_SUN_HANDLER_OPTIONS = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("HANDLER-OPTIONS", null, 0)));
Sun.KWD_BLOCK = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("BLOCK", null, 2)));
Sun.KWD_CONTENT_TYPE = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("CONTENT-TYPE", null, 2)));
Sun.KWD_HTML = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("HTML", null, 2)));
Sun.SYM_SUN_STARTUP_HTTP_SERVER_IMPL = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-HTTP-SERVER-IMPL", null, 0)));
Sun.SYM_STELLA_METHOD_STARTUP_CLASSNAME = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("METHOD-STARTUP-CLASSNAME", Stella.getStellaModule("/STELLA", true), 0)));
}
if (Stella.currentStartupTimePhaseP(5)) {
Stella.defineClassFromStringifiedSource("NATIVE-HTTP-SERVER", "(DEFCLASS NATIVE-HTTP-SERVER () :JAVA-NATIVE-TYPE \"com.sun.net.httpserver.HttpServer\")");
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("HTTP-SERVER-SUN", "(DEFCLASS HTTP-SERVER-SUN (HTTP-SERVER) :PUBLIC? TRUE :SLOTS ((CURRENT-SERVER :TYPE NATIVE-HTTP-SERVER) (CURRENT-SERVER-PORT :TYPE INTEGER)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "newHttpServerSun", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "accessHttpServerSunSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.sun.HttpServerSun"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
Stella.defineClassFromStringifiedSource("NATIVE-HTTP-EXCHANGE", "(DEFCLASS NATIVE-HTTP-EXCHANGE () :JAVA-NATIVE-TYPE \"com.sun.net.httpserver.HttpExchange\")");
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("HTTP-EXCHANGE-SUN", "(DEFCLASS HTTP-EXCHANGE-SUN (HTTP-EXCHANGE) :SLOTS ((NATIVE-EXCHANGE :TYPE NATIVE-HTTP-EXCHANGE) (RESPONSE-CODE :TYPE INTEGER :INITIALLY (GET-HTTP-RESPONSE-CODE :OK NULL)) (REPLY-STREAM :TYPE NATIVE-OUTPUT-STREAM) (HANDLER-OPTIONS :TYPE PROPERTY-LIST)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.http.sun.HttpExchangeSun", "newHttpExchangeSun", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.http.sun.HttpExchangeSun", "accessHttpExchangeSunSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.sun.HttpExchangeSun"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
Stella.defineMethodObject("(DEFMETHOD (START-HTTP-SERVER-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (PORT INTEGER)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "startHttpServerImpl", new java.lang.Class [] {java.lang.Integer.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD STOP-HTTP-SERVER-IMPL ((SERVER HTTP-SERVER-SUN)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "stopHttpServerImpl", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-HEADER-VALUE-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE) (KEY KEYWORD)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getHeaderValueImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange"), Native.find_java_class("edu.isi.stella.Keyword")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REPLY-HEADER-VALUE-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE) (KEY KEYWORD)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getReplyHeaderValueImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange"), Native.find_java_class("edu.isi.stella.Keyword")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD SET-REPLY-HEADER-VALUE-IMPL ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE) (KEY KEYWORD) (VALUE STRING)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "setReplyHeaderValueImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange"), Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("java.lang.String")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-URI-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestUriImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-URI-QUERY-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestUriQueryImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-URI-PATH-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestUriPathImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-METHOD-IMPL KEYWORD) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestMethodImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-PROTOCOL-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestProtocolImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-BODY-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestBodyImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-LOCAL-ADDRESS-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestLocalAddressImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REQUEST-REMOTE-ADDRESS-IMPL STRING) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getRequestRemoteAddressImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-REPLY-STREAM-IMPL NATIVE-OUTPUT-STREAM) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getReplyStreamImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD SET-RESPONSE-CODE-IMPL ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE) (CODE KEYWORD)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "setResponseCodeImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange"), Native.find_java_class("edu.isi.stella.Keyword")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD PUBLISH-FILE-IMPL ((SERVER HTTP-SERVER-SUN) (PATH STRING) (FILE STRING) (OPTIONS PROPERTY-LIST)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "publishFileImpl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.PropertyList")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD PUBLISH-DIRECTORY-IMPL ((SERVER HTTP-SERVER-SUN) (PATH STRING) (DIRECTORY STRING) (OPTIONS PROPERTY-LIST)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "publishDirectoryImpl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.PropertyList")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD PUBLISH-HANDLER-IMPL ((SERVER HTTP-SERVER-SUN) (PATH STRING) (HANDLER FUNCTION-CODE) (OPTIONS PROPERTY-LIST)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "publishHandlerImpl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.reflect.Method"), Native.find_java_class("edu.isi.stella.PropertyList")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (GET-HANDLER-OPTIONS-IMPL PROPERTY-LIST) ((SERVER HTTP-SERVER-SUN) (XCHG HTTP-EXCHANGE)))", Native.find_java_method("edu.isi.webtools.http.sun.HttpServerSun", "getHandlerOptionsImpl", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("STARTUP-HTTP-SERVER-IMPL", "(DEFUN STARTUP-HTTP-SERVER-IMPL () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.sun._StartupHttpServerImpl", "startupHttpServerImpl", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Sun.SYM_SUN_STARTUP_HTTP_SERVER_IMPL);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Sun.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupHttpServerImpl"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("HTTP/SUN")))));
if ((Http.$HTTP_SERVER_IMPLEMENTATION$ != null) &&
(!Stella_Object.isaP(Http.$HTTP_SERVER_IMPLEMENTATION$, Sun.SGT_SUN_HTTP_SERVER_SUN))) {
throw ((StellaException)(StellaException.newStellaException("Conflicting HTTP server implementation already loaded").fillInStackTrace()));
}
else {
Http.$HTTP_SERVER_IMPLEMENTATION$ = HttpServerSun.newHttpServerSun();
}
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 8 |
public MapGeneratorOptionsDialog(FreeColClient freeColClient, GUI gui,
OptionGroup mgo, boolean editable,
boolean loadCustomOptions) {
super(freeColClient, gui, editable);
if (editable && loadCustomOptions) {
loadCustomOptions();
}
if (editable) {
JPanel mapPanel = new JPanel();
/*
* TODO: The update should be solved by PropertyEvent.
*/
File mapDirectory = FreeColDirectories.getMapsDirectory();
if (mapDirectory.isDirectory()) {
for (final File file : mapDirectory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".fsg");
}
})) {
String mapName = file.getName().substring(0, file.getName().lastIndexOf('.'));
JButton mapButton = new JButton(mapName);
try {
FreeColSavegameFile savegame = new FreeColSavegameFile(file);
Image thumbnail = ImageIO.read(savegame.getInputStream(FreeColSavegameFile.THUMBNAIL_FILE));
mapButton.setIcon(new ImageIcon(thumbnail));
try {
Properties properties = new Properties();
properties.load(savegame.getInputStream(FreeColSavegameFile.SAVEGAME_PROPERTIES));
mapButton.setToolTipText(properties.getProperty("map.width")
+ "\u00D7"
+ properties.getProperty("map.height"));
} catch(Exception e) {
logger.fine("Unable to load savegame properties.");
}
mapButton.setHorizontalTextPosition(JButton.CENTER);
mapButton.setVerticalTextPosition(JButton.BOTTOM);
} catch(Exception e) {
logger.warning("Failed to read thumbnail.");
}
mapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setFile(file);
}
});
mapPanel.add(mapButton);
}
}
if (mapPanel.getComponentCount() > 0) {
scrollPane = new JScrollPane(mapPanel,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
scrollPane.getViewport().setOpaque(false);
// TODO: find out how to do this properly
scrollPane.setMinimumSize(new Dimension(400, 110));
}
}
initialize(mgo, mgo.getName(), scrollPane);
} | 9 |
@SuppressWarnings("resource")
public static void main(String[] args) {
// Record the starting timestamp and set the thread name for debugging
// purposes
serverStartTime = (new Date()).getTime();
Thread.currentThread().setName("Main Thread");
// Read the port from the command line arguments
if (args.length != 1) {
System.out.println("Usage: <Port>");
System.exit(0);
}
// Open the server socket
ServerSocket parentSocket = null;
try {
int listenBacklog = 50;
// Create the socket. Address 0.0.0.0 indicates that the socket
// will accept connections on any of the interfaces of the server
parentSocket =
new ServerSocket(Integer.parseInt(args[0]), listenBacklog,
InetAddress.getByName("0.0.0.0"));
} catch (IOException e) {
System.out.println("Unable to open server socket: " +
e.getMessage());
System.exit(0);
} catch (NumberFormatException e) {
System.out.println("Invalid port: " + args[0]);
System.exit(0);
} catch (IllegalArgumentException e) {
System.out.println("Port not in range: " + args[0]);
System.exit(0);
}
System.out.println("Server starting...\n");
// Code for testing purposes. These players are not actually playing.
// UNCOMMENT FOR DEBUGGING:
// String sampleNames[] = {"Austin", "Daniel", "Kevin", null};
// lobbyGames.put("Ultimate Showdown", sampleNames);
int totalThreadsCreated = 0; // Counter used for debugging purposes
// Accept connections and start new threads for each connection
while (true) {
try {
Socket childSocket = parentSocket.accept();
// Check whether the maximum number of connections is being used
if (numberConnections.get() < MAX_CONNECTIONS) {
numberConnections.getAndIncrement();
totalThreadsCreated++;
Thread connectionThread =
new Thread(new ServerConnectionHandler(childSocket));
// Set name for debugging purposes
connectionThread.setName("Handler Thread " +
totalThreadsCreated);
connectionThread.start();
} else {
// Notify the client that it cannot be served at this moment
ObjectOutputStream outputStream = new ObjectOutputStream(
childSocket.getOutputStream());
outputStream.writeObject(CONN_LIMIT_MSG);
outputStream.flush();
childSocket.close();
}
} catch (IOException e) {
printServerMsg("Error accepting new connection: " +
e.getMessage());
}
}
} | 7 |
public SaveAsFileMenuItem(FileProtocol protocol) {
setProtocol(protocol);
addActionListener(this);
} | 0 |
public Object getEncodedDestination() {
// write out the destination name
if (namedDestination != null) {
return namedDestination;
}
// build and return a fector of changed valued.
else if (object instanceof Vector) {
Vector<Object> v = new Vector<Object>(7);
if (ref != null) {
v.add(ref);
}
// named dest type
if (type != null) {
v.add(type);
}
// left
if (left != Float.NaN) {
v.add(left);
}
// bottom
if (bottom != Float.NaN) {
v.add(bottom);
}
// right
if (right != Float.NaN) {
v.add(right);
}
// top
if (top != Float.NaN) {
v.add(top);
}
// zoom
if (zoom != Float.NaN) {
v.add(zoom);
}
return v;
}
return null;
} | 9 |
@Override
public boolean equals(Object activity) {
if (this.getName().compareTo(((Activity) activity).getName()) == 0) {
return true;
} else
return false;
} | 1 |
public boolean pass(int[] bowl, int bowlId, int round,
boolean canPick,
boolean musTake) {
int bowlScore = 0;
double expectedScore=0;
if(strategy == 0 || (strategy==1 && round==1)){
//System.out.println("Strategy: "+strategy+"\t"+"Round: "+round);
bowlScore = buildDistribution(bowl,bowlId,round);
scoresSeen.add(bowlScore);
len[round]++;
if(bowlsSeen[0]+bowlsSeen[1]>=x)
{
expectedScore=calcExpectedScore(bowl);
double multiplier=0;
if(round == 0)
{
multiplier = ((double)maxBowls[round]-bowlsSeen[round])/((double)maxBowls[round]-x);
}
else
{
double denominator=0;
if(bowlsSeen[0]>x)
denominator = (double)maxBowls[round];
else
denominator = (double)maxBowls[round]-x+bowlsSeen[0];
multiplier = ((double)maxBowls[round]-bowlsSeen[round])/(denominator);
}
double updated_expectedScore = expectedScore+(multiplier*std_dev);
bowlsSeen[round]++;
//System.out.println("Bowl Score: "+bowlScore);
//System.out.println("Expected Score: "+expectedScore);
//System.out.println("Multiplier: "+multiplier);
//System.out.println("Updated Expected Score: "+updated_expectedScore);
//System.out.println("Bowls Seen: "+bowlsSeen[round]);
return bowlScore >= updated_expectedScore;
// return bowlScore >= expectedScore+(multiplier*std_dev);
}
bowlsSeen[round]++;
return false;
}
if(strategy == 1 && round==0)
{
//System.out.println("Strategy: "+strategy+"\t"+"Round: "+round);
bowlsSeen[round]++;
return optimal(bowl,bowlId,round);
}
if(strategy == 2)
{
//System.out.println("Strategy: "+strategy+"\t"+"Round: "+round);
bowlsSeen[round]++;
return optimal(bowl,bowlId,round);
}
scoresSeen.add(bowlScore);
len[round]++;
//System.out.println("Never reach here..");
return false;
} | 9 |
public void setId(String value) {
this.id = value;
} | 0 |
public static String getMiniIconName(int miniIconNumber)
{
// Hardcoded in MM6.exe file
// These icon names are contained in icon.lod
switch(miniIconNumber)
{
case 0:
return "NO SYMBOL";
case 1:
return "castle";
case 2:
return "dungeon";
case 3:
return "idoor";
case 4:
return "isecdoor";
case 5:
return "istairdn";
case 6:
return "istairup";
case 7:
return "itrap";
case 8:
return "outside";
default:
return null;
}
} | 9 |
@Test
public void testPolar() {
System.out.println("Polar");
assertEquals(Complex.NaN, Complex.Polar(Double.NaN, Double.NaN));
assertEquals(Complex.NaN, Complex.Polar(Double.NaN, 1.0));
assertEquals(Complex.NaN, Complex.Polar(1.0, Double.NaN));
assertEquals(Complex.Infinity, Complex.Polar(Double.POSITIVE_INFINITY, Double.NaN));
assertEquals(Complex.Infinity, Complex.Polar(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
assertEquals(Complex.Infinity, Complex.Polar(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY));
assertEquals(Complex.Infinity, Complex.Polar(Double.POSITIVE_INFINITY, 1.0));
assertEquals(Complex.NaN, Complex.Polar(1.0, Double.POSITIVE_INFINITY));
for (int i = -5; i < 6; i++)
assertTrue("Failed creating of Complex real unit for rotations: " +
Integer.toString(i),
this._numericalComparer.value(
Complex.Cartesian(1.0, 0.0), Complex.Polar(1.0, 2.0*Math.PI*i)));
for (int i = -5; i < 6; i++)
assertTrue("Failed creating of Complex negative real unit for rotations: " +
Integer.toString(i),
this._numericalComparer.value(
Complex.Cartesian(-1.0, 0.0), Complex.Polar(1.0, 2.0*Math.PI*i + Math.PI)));
for (int i = -5; i < 6; i++)
assertTrue("Failed creating of Complex imaginary unit for rotations: " +
Integer.toString(i),
this._numericalComparer.value(
Complex.Cartesian(0.0, 1.0), Complex.Polar(1.0, 2.0*Math.PI*i + Math.PI/2.0)));
for (int i = -5; i < 6; i++)
assertTrue("Failed creating of Complex negative imaginary unit for rotations: " +
Integer.toString(i),
this._numericalComparer.value(
Complex.Cartesian(0.0, -1.0), Complex.Polar(1.0, 2.0*Math.PI*i - Math.PI/2.0)));
Complex tri = Complex.Cartesian(3.0, -4.0);
for (int i = -5; i < 6; i++)
assertTrue("Failed creating of Compex value " + tri.toString() +
" for rotations: " + Integer.toString(i),
this._numericalComparer.value(
tri, Complex.Polar(5.0, -0.9272952180016121 + 2.0*Math.PI*i)));
} | 5 |
private void render(float interpol) {
Graphics2D g = null;
try {
g = (Graphics2D)bs.getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
// Profiler.lapRestart("Obtain Graphics");
draw(g,interpol);
// Profiler.lapRestart("Draw Content");
if (!bs.contentsLost())
bs.show();
// Profiler.lapRestart("Show Content");
// g.dispose();
} finally {
if (g != null)
g.dispose();
// Profiler.lapRestart("Dispose Graphics");
}
} | 2 |
protected Color getHeaderBackground()
{
Color c = UIManager
.getColor("SimpleInternalFrame.activeTitleBackground");
if (c != null)
return c;
if (LookUtils.IS_LAF_WINDOWS_XP_ENABLED)
c = UIManager.getColor("InternalFrame.activeTitleGradient");
return c != null ? c : UIManager
.getColor("InternalFrame.activeTitleBackground");
} | 3 |
private void paintAreasBoundaries(Graphics2D g2d) {
if (drawAreaBoundaries) {
g2d.setColor(Color.GRAY);
final float dash1[] = { 4.0f };
final BasicStroke dashed = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash1,
0.0f);
g2d.setStroke(dashed);
// draw the boundaries of the areas
for (final DrawableArea area : simulationAreas) {
g2d.draw(area.getClip());
}
g2d.setStroke(new BasicStroke());
}
} | 2 |
private void incAsset(String as, int inc){
if ("Pork Bellies".equals(as)){
pb = pb+inc;
}
else if ("Frozen Orange Juice Concentrate".equals(as)){
oj = oj+inc;
}
else if ("Soybeans".equals(as)){
sb = sb+inc;
}else throw new Error("No such asset");
} | 3 |
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null
|| (object instanceof String && ((String) object).length() == 0)) {
return null;
}
if (object instanceof Detallecotizacion) {
Detallecotizacion o = (Detallecotizacion) object;
return getStringKey(o.getIdDetallecotizacion());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Detallecotizacion.class.getName()});
return null;
}
} | 4 |
public static void main(String args[])
{
/*//Trying for perfum
Perfume[] pf = PerfumeFactory.getAllPerfume();
//Setting the training desired value for the class
pf[0].setDesiredValue(1);
for(int i = 1; i < pf.length; i++)
{
pf[i].setDesiredValue(-1);
}
Perceptron<Perfume> p = new Perceptron<Perfume>(pf,1,0.05,false);
System.out.println("Trying to classify each perfum!");
for(int i = 0; i < pf.length; i++)
{
System.out.println("its a " + pf[i].getNome() + "?" + p.predict(pf[i]));
}
System.out.println(pf[0].getNome());
*/
//Trying for Iris
Iris[] irf = IrisFactory.getAllIris();
//Setting the training desired value for the class
for(int i = 0; i < irf.length; i++)
{
if(irf[i].getNome().compareTo(irf[0].getNome()) == 0)
irf[i].setDesiredValue(1);
else
irf[i].setDesiredValue(-1);
}
Perceptron<Iris> ip = new Perceptron<Iris>(irf,0.05,0.05,false);
System.out.println("Trying to classify each perfum!");
for(int i = 0; i < irf.length; i++)
{
System.out.println("its a " + irf[i].getNome() + "?" + ip.predict(irf[i]));
}
System.out.println(irf[0].getNome());
} | 3 |
private String arrayToString(ArrayList<Path> array) {
String s = "";
for(Path path : array)
s += path.toString()+"\n";
return s;
} | 1 |
public static String getExceptionMessage(final Throwable e) {
if (e.getCause() != null) {
String msg = getExceptionMessage(e.getCause());
if (!msg.equalsIgnoreCase(e.getClass().getName())) {
return msg;
}
}
if (e.getLocalizedMessage() != null) {
return e.getLocalizedMessage();
} else if (e.getMessage() != null) {
return e.getMessage();
} else if (e.getClass().getCanonicalName() != null) {
return e.getClass().getCanonicalName();
} else {
return e.getClass().getName();
}
} | 5 |
public void update() {
if(GameManager.getGames().size()!= games)
getInventory();
for(ItemStack item: menu.getContents()) {
if(item!= null && item.getType()!= Material.MAGMA_CREAM) {
ItemMeta im = item.getItemMeta();
String name = ChatColor.stripColor(im.getDisplayName().split(" ")[0]);
Game game = GameManager.getGame(name);
if(game.getState()== State.WAITING || game.getState()== State.STARTING) {
item.setDurability((short) 5);
im.setDisplayName("§a"+game.getName()+" - "+game.getState());
} else if(game.getState()== State.RESTARTING) {
item.setDurability((short) 1);
im.setDisplayName("§6"+game.getName()+" - "+game.getState());
} else {
item.setDurability((short) 14);
im.setDisplayName("§c"+game.getName()+" - "+game.getState());
}
im.setLore(new ArrayList<String>(Arrays.asList("§7Players: "+game.getPlayers().size()+"/"+game.getMaxPlayers(),
"§7Time: "+game.getTimeString(), "§8Right click to close,", "§8Left click to open or", "§8Shift click to restart")));
item.setItemMeta(im);
}
}
} | 7 |
protected void checkSingleParameters(OAuthMessage message) throws IOException, OAuthException {
// Check for repeated oauth_ parameters:
boolean repeated = false;
Map<String, Collection<String>> nameToValues = new HashMap<String, Collection<String>>();
for (Map.Entry<String, String> parameter : message.getParameters()) {
String name = parameter.getKey();
if (SINGLE_PARAMETERS.contains(name)) {
Collection<String> values = nameToValues.get(name);
if (values == null) {
values = new ArrayList<String>();
nameToValues.put(name, values);
} else {
repeated = true;
}
values.add(parameter.getValue());
}
}
if (repeated) {
Collection<OAuth.Parameter> rejected = new ArrayList<OAuth.Parameter>();
for (Map.Entry<String, Collection<String>> p : nameToValues.entrySet()) {
String name = p.getKey();
Collection<String> values = p.getValue();
if (values.size() > 1) {
for (String value : values) {
rejected.add(new OAuth.Parameter(name, value));
}
}
}
OAuthProblemException problem = new OAuthProblemException(OAuth.Problems.PARAMETER_REJECTED);
problem.setParameter(OAuth.Problems.OAUTH_PARAMETERS_REJECTED, OAuth.formEncode(rejected));
throw problem;
}
} | 7 |
public Object getColumnValue(UserColumns column)
{
switch (column)
{
case ID:
return id;
case COMMENT:
return comment;
case CREATE_TIME:
return createTime;
case DN:
return dn;
case INFO:
return info;
case MODIFY_TIME:
return modTime;
case NAME:
return username;
case TYPE:
return type;
case ZONE:
return zone;
default:
throw new RuntimeException("Unhandled column: " + column);
}
} | 9 |
public Medico getMedico() {
return medico;
} | 0 |
private ArrayList<Entry<String, Integer>> sortByValue(TreeMap<String, Integer> keywords){
ArrayList<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(keywords.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
return list;
} | 0 |
public static void main(String[] args) {
IHello hello = new HelloSpeaker();
StaticHelloProxy proxy = new StaticHelloProxy(hello);
proxy.hello("Laud");
} | 0 |
private void createPropertyFile(String fileName, String query, String time, String dbName) {
Properties prop = new Properties();
ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
FileOutputStream out = null;
File file = new File("src/main/resources/properties");
if(!file.exists()) {
file.mkdir();
}
file = new File("src/main/resources/properties/" + fileName);
try {
prop.setProperty(dbName + "~" + time, query);
prop.store(arrayOut, null);
out = new FileOutputStream(file, true);
String string = new String(arrayOut.toByteArray(), "8859_1");
String sep = System.getProperty("line.separator");
String text = string.substring(string.indexOf(sep) + sep.length());
out.write(text.getBytes("8859_1"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 4 |
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
// TODO add your handling code here:
if (jRadioButton1.isSelected()) {
try {
ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from author where AuthorName like '" + jTextField1.getText() + "%' order by AuthorName ASC");
Vector v = new Vector();
while (rs.next()) {
v.add(rs.getString("AuthorName"));
}
jComboBox1.setModel(new DefaultComboBoxModel(v));
} catch (Exception e) {
}
} else if (jRadioButton2.isSelected()) {
try {
ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from author where AuthorID like '" + jTextField1.getText() + "%' order by AuthorID ASC");
Vector v = new Vector();
while (rs.next()) {
v.add(rs.getString("AuthorID"));
}
jComboBox1.setModel(new DefaultComboBoxModel(v));
} catch (Exception e) {
}
}
jComboBox1.showPopup();
}//GEN-LAST:event_jTextField1KeyReleased | 6 |
private File createDataFile(String data) throws IOException {
File tempDir = makeTempDir();
File tempFile = new File(tempDir, "tzdata");
tempFile.deleteOnExit();
InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8"));
FileOutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1000];
int amt;
while ((amt = in.read(buf)) > 0) {
out.write(buf, 0, amt);
}
out.close();
in.close();
return tempDir;
} | 1 |
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.