method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
8bc431f0-1087-4dee-a9e6-5c52f03eb913 | 8 | public static void main(String[] args) throws Exception {
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
File schemaLocation = new File("schema/data/data-savedGame.xsd");
Schema schema = factory.newSchema(schemaLocation);
Validator saveGameValidator = schema.newValidator();
List<File> allFiles = new ArrayList<File>();
for (String name : args) {
File file = new File(name);
if (file.exists()) {
if (file.isDirectory()) {
for (File fsg : file.listFiles(fsgFilter)) {
allFiles.add(fsg);
}
} else if (fsgFilter.accept(file)) {
allFiles.add(file);
}
}
}
for (File file : allFiles) {
System.out.println("Processing file " + file.getPath());
try {
FreeColSavegameFile mapFile = new FreeColSavegameFile(file);
saveGameValidator.validate(new StreamSource(mapFile.getSavegameInputStream()));
System.out.println("Successfully validated " + file.getName());
} catch(SAXParseException e) {
System.out.println(e.getMessage()
+ " at line=" + e.getLineNumber()
+ " column=" + e.getColumnNumber());
} catch(Exception e) {
System.out.println("Failed to read " + file.getName());
}
}
} |
81921ba1-d591-4bb4-a874-78d0141ce012 | 6 | public void createLife()
{
Random rand = new Random();
Animals tempA; Plants tempP;
//
if(ratioOfPredatorToAll==0)
{
for(int i=0;i<AmountAn;i++)
{//
tempA = new Animals(rand.nextDouble()*998, rand.nextDouble()*799);
if(tempA.species==1)
anP.add(tempA);
else
anH.add(tempA);
}
//
AmountAnP = anP.size();
AmountAnH = anH.size();
}
else
{
for(int i=0;i<AmountAn*(1-ratioOfPredatorToAll);i++)
{//
tempA = new Animals(rand.nextDouble()*998, rand.nextDouble()*799,0);
anH.add(tempA);
}
for(int i=0;i<AmountAn*ratioOfPredatorToAll;i++)
{//
tempA = new Animals(rand.nextDouble()*998, rand.nextDouble()*799,1);
anP.add(tempA);
}
//
AmountAnP = anP.size();
AmountAnH = anH.size();
}
for(int i=0;i<AmountPl;i++)
{//
tempP = new Plants(rand.nextDouble()*998, rand.nextDouble()*799);
pl.add(tempP);
}
} |
f36823aa-4650-476b-b161-d24a72d0ca8c | 6 | @Override
public void init(GameContainer gc, StateBasedGame arg1) throws SlickException {
//changing resolution
//AppGameContainer apgc = (AppGameContainer)gc;
//apgc.setDisplayMode(482, 600, false);
inGameMenu = new Image("res/inGameMenu.png");
Image [] movementWarrior = {new Image("res/warrior.png"),new Image("res/warrior.png")};
Image [] movementBothlo = {new Image("res/Bothlo.png"), new Image("res/Bothlo.png")};
/*
Image [] movementRogue = {new Image("res/rogue.png"), new Image("res/rogue.png")};
Image [] movementCleric = {new Image("res/cleric.png"),new Image("res/cleric.png")};
*/
grassMap = new TiledMap("res/Starting room.tmx");
int [] duration = {1, 1};
upW = new Animation(movementWarrior, duration, false);
upM = new Animation(movementBothlo, duration, false);
/*
upR = new Animation(movementRogue, duration,false );
upC = new Animation(movementCleric, duration, false);
*/
leftW = new Animation(movementWarrior, duration, false);
leftM = new Animation(movementBothlo, duration, false);
/*
leftR = new Animation(movementCleric, duration, false);
leftC = new Animation(movementCleric, duration, false);
*/
rightW = new Animation(movementWarrior, duration, false);
rightM = new Animation(movementBothlo, duration, false);
/*
rightR = new Animation(movementRogue, duration, false);
rightC = new Animation(movementCleric, duration, false);
*/
downW = new Animation(movementWarrior, duration, false);
downM = new Animation(movementBothlo, duration, false);
/*
downR = new Animation(movementRogue, duration, false);
downC = new Animation(movementCleric, duration, false);
*/
Warrior = downW;
Bothlo = downM;
/*
Rogue = downR;
Cleric = downC;
*/
warps = new boolean[grassMap.getWidth()][grassMap.getHeight()];
traps = new boolean[grassMap.getWidth()][grassMap.getHeight()];
String Layername = grassMap.getLayerProperty(1, "trap", "true");
for (int xAxis=0;xAxis<grassMap.getWidth(); xAxis++)
{
for (int yAxis=0;yAxis<grassMap.getHeight(); yAxis++)
{
int tileID = grassMap.getTileId(xAxis, yAxis,1);
if (tileID!= 0){
traps[xAxis][yAxis] = true;
}
}
}
for (int xAxis=0;xAxis<grassMap.getWidth(); xAxis++)
{
for (int yAxis=0;yAxis<grassMap.getHeight(); yAxis++)
{
int tileID = grassMap.getTileId(xAxis, yAxis,2);
if (tileID!= 0){
warps[xAxis][yAxis] = true;
}
}
}
} |
a93bbdb7-b463-4764-82de-368fa6821913 | 9 | private Object[] mergeSort(Object[] array)
{
if (array.length > 1)
{
int elementsInA1 = array.length/2;
int elementsInA2 = elementsInA1;
if((array.length % 2) == 1)
elementsInA2++;
Object arr1[] = new Object[elementsInA1];
Object arr2[] = new Object[elementsInA2];
for(int i = 0; i < elementsInA1; i++)
arr1[i] = array[i];
for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++)
arr2[i - elementsInA1] = array[i];
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
int i = 0, j = 0, k = 0;
while (arr1.length != j && arr2.length != k)
{
if (arr1[j].toString().compareTo(arr2[k].toString()) < 0)
{
array[i] = arr1[j];
i++;
j++;
}
else
{
array[i] = arr2[k];
i++;
k++;
}
}
while (arr1.length != j)
{
array[i] = arr1[j];
i++;
j++;
}
while (arr2.length != k)
{
array[i] = arr2[k];
i++;
k++;
}
}
return array;
} |
069e428e-90ae-4398-a25d-b4c2f0505eb1 | 6 | public void populateSkillMap() {
Connection connection = new DbConnection().getConnection();
ResultSet resultSet = null;
Statement statement = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(SELECT_ALL_SKILLS);
while (resultSet.next()) {
int skillId = resultSet.getInt("skill_Id");
String skillName = resultSet.getString("skill_name");
skillsMap.put(skillId, skillName);
}
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
} finally {
try {
if (connection != null)
connection.close();
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
}
}
} |
57c794b7-8012-4886-8c61-4c9e695fb6c7 | 5 | private void go()throws InterruptedException{
int i=1;
float dpercent = 0f;
String cc = c[0];
app.setEnabled(false);
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame fFrame = new JFrame("Please wait while updating.");
fFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
app.setEnabled(true);
}
});
fFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
fFrame.setSize(400,125);
//panel.setSize(300,300);
fFrame.getContentPane().add(panel, BorderLayout.CENTER);
JLabel percent = new JLabel();
JLabel message = new JLabel();
message.setText("Updating Currency Code " + cc + ".");
// string format for percentage
percent.setText(String.format("%,.0f%%", dpercent));
panel.add(percent);
fFrame.getContentPane().add(panel2, BorderLayout.SOUTH);
panel2.add(message);
JProgressBar jpb = new JProgressBar(0,90);
panel.add(jpb);
//fFrame.pack();
fFrame.setVisible(true);
if (p<90){
while (p<90){
if (Thread.currentThread().isInterrupted()){
fFrame.dispose();
return;
}
if (kill){
Thread.currentThread().interrupt();
fFrame.dispose();
return;
}
i=getP();
jpb.setValue(i);
dpercent = ((i+1) * 100.0f) / 90;
//System.out.println(i);
cc = c[i];
percent.setText(String.format("%,.0f%%", dpercent));
message.setText("Updating Currency Code " + cc + ".");
jpb.repaint();
try{Thread.sleep(450);} //Sleep 50 milliseconds
catch (InterruptedException err){}
}
}
app.setEnabled(true);
fFrame.dispose();
} |
5f598914-388f-4473-a4b1-8b4c79e70b28 | 3 | private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
if(null != jListExcluir.getSelectedValue()){
if(JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir: "+jListExcluir.getSelectedValue()) == 0){
FachadaSistema.getInstance().excluirContatoPorNome(jListExcluir.getSelectedValue().toString());
jPanelExcluirContato.revalidate();
jPanelExcluirContato.repaint();
DefaultListModel listaExcluir = new DefaultListModel();
List<Contato> listaContatos = FachadaSistema.getInstance().listarContatos();
for(Contato contatoExcluir: listaContatos){
listaExcluir.addElement(contatoExcluir.getNome());
}
jListExcluir.setModel(listaExcluir);
JOptionPane.showMessageDialog(null,"Contato excluido com sucesso");
}
}
else{
JOptionPane.showMessageDialog(null, "Escolha o contato que você deseja excluir");
}
}//GEN-LAST:event_jButton7ActionPerformed |
3e97545d-5116-43ec-bff4-b830ef1595ce | 8 | public static void discretizeNumericAttributesProcessClass(ArrayList<LearningObject> learningSet, ArrayList<Attribute> attributes){
for(int i=0; i<attributes.size();i++){
Attribute attr = attributes.get(i);
if(attr.type == Attribute.NUMERIC){
//apply discretization process
TreeMap<Integer,Association> values = new TreeMap<Integer, Association>();
//total number of values
int totalNo = 0;
//total number of classes
int totalClasses = 0;
//intervals to be split in
ArrayList<Interval> intervals = new ArrayList<Interval>();
for(int j=0;j<learningSet.size();j++){
Association val = values.get(learningSet.get(j).values.get(attr.posInLearningSet).getValue());
if(val == null){
Association assoc = new Association();
assoc.addClass(learningSet.get(j).classValue.name);
values.put((Integer)learningSet.get(j).values.get(attr.posInLearningSet).getValue(),assoc);
totalClasses++;
}
else
val.addClass(learningSet.get(j).classValue.name);
totalNo++;
}
Interval interval = new Interval();
Interval oldInterval;
int index = 0;
String currentClass = "nodInitialized";
while(values.size()>0){
Entry<Integer,Association> entry = values.firstEntry();
if(!currentClass.equals(entry.getValue().getDominantClass())){
//System.out.println("Class change from " + currentClass + " to " + entry.getValue().getDominantClass() + " when changed to" + entry.getKey());
//class change
oldInterval = interval;
oldInterval.highBound = entry.getKey();
interval = new Interval();
interval.lowBound = entry.getKey();
intervals.add(interval);
currentClass = entry.getValue().getDominantClass();
}
if(index == 0){
interval.lowBound = Integer.MIN_VALUE;
}
index++;
values.remove(entry.getKey());
}
interval.highBound = Integer.MAX_VALUE;
//add intervals to attribute
attr.numericIntervalBounds = intervals;
System.out.println("Attribute intervals:"+attr.name);
for(int t=0;t<intervals.size();t++)
System.out.print("[" +intervals.get(t).lowBound+" " + intervals.get(t).highBound+ "]");
}
}
} |
ba566347-3f03-427c-b62c-65d1aad10c03 | 9 | Space[] won() {
int n = numToWin - 1;
if (lastSpaceMoved == null)
return null;
int[] pos = lastSpaceMoved.getPos();
for (int i = 0, rowInd = pos[0]; i <= n; i++, rowInd = pos[0] - i)
for (int j = 0, colInd = pos[1]; j <= n; j++, colInd = pos[1] - j) {
boolean outOfBounds = rowInd < 0 || colInd < 0
|| rowInd + n >= rows || colInd + n >= cols;
if (outOfBounds)
continue;
ExpBoard sub = new ExpBoard(this, rowInd, colInd, new int[] {
i, j });
Space[] winningSet = sub.subWon();
if (winningSet != null) {
for (Space sp : winningSet)
sp.setPos(sp.getRow() + rowInd, sp.getCol() + colInd);
return winningSet;
}
}
return null;
} |
d82d7151-796d-4abb-9f55-eaa22d17f5c4 | 8 | @Override
public double calculateFractalWithoutPeriodicity(Complex pixel) {
iterations = 0;
Complex tempz = new Complex(pertur_val.getPixel(init_val.getPixel(pixel)));
Complex[] complex = new Complex[2];
complex[0] = tempz;//z
complex[1] = new Complex(pixel);//c
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
for(; iterations < max_iterations; iterations++) {
if(bailout_algorithm.escaped(complex[0], zold)) {
Object[] object = {iterations, complex[0], zold};
return out_color_algorithm.getResult(object);
}
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
return in_color_algorithm.getResult(object);
} |
7d0b9ba4-c9cc-4cee-b87f-5bf7b3094b7e | 6 | public void connectGeneral(TreeLinkNode root){
LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
if(root==null) return;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeLinkNode current = queue.poll();
if(current.left!=null) queue.offer(current.left);
if(current.right!=null) queue.offer(current.right);
if(i!=size-1) current.next = queue.peek();
}
}
} |
982e5704-1049-4d0c-9ff2-b0f07f41cbde | 8 | private static Icon getTexture(int textureType) {
Icon texture = null;
switch (textureType) {
case WINDOW_TEXTURE_TYPE: texture = windowTexture; break;
case BACKGROUND_TEXTURE_TYPE: texture = backgroundTexture; break;
case ALTER_BACKGROUND_TEXTURE_TYPE: texture = alterBackgroundTexture; break;
case SELECTED_TEXTURE_TYPE: texture = selectedTexture; break;
case ROLLOVER_TEXTURE_TYPE: texture = rolloverTexture; break;
case PRESSED_TEXTURE_TYPE: texture = pressedTexture; break;
case DISABLED_TEXTURE_TYPE: texture = disabledTexture; break;
case MENUBAR_TEXTURE_TYPE: texture = menubarTexture; break;
}
return texture;
} |
c3d3d191-1c21-45f2-a035-7a248bf38597 | 1 | public GraphProblem(String fileName, int numNodes, int s_Index)
throws IOException {
totalNumNodes = numNodes;
startV = s_Index;
originalGraph = new HashMap<Integer, HashMap<Integer, Integer>>();
exploredNodes = new ArrayList<Integer>(totalNumNodes);
unexploredNodes = new ArrayList<Integer>(totalNumNodes);
shortestPathNum = new int[totalNumNodes];
shortestPath = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < totalNumNodes; i++) {
shortestPathNum[i] = 100000; // by default the +big number
unexploredNodes.add(i + 1); // every node is unexplored at first
}
readFileIntoMemory(fileName);
} |
bc2e8c42-90d0-4ad4-84b0-f0eefa234d16 | 8 | public static void main(String[] args) throws IOException{
formulas = new ArrayList<Vector<Object>>();
System.out.println("Welcome to Formulaic !");
boolean running = true;
br = new BufferedReader(new InputStreamReader(System.in));
String instruction = new String();
while(running){
instruction = br.readLine();
List<String> inst = new ArrayList<String>();
inst.add(instruction);
parseInstruction(inst);
switch (inst.get(0)) {
case "help":
printHelp();
break;
case "store":
storeFormula(inst);
break;
case "evaluate":
System.out.println(evaluateFormula(inst));
break;
case "files":
save();
break;
case "differentiate":
derivate(inst);
break;
case "interface":
@SuppressWarnings("unused")
Window ui = new Window(600,400);
break;
case "exit":
running = false;
break;
default:
break;
}
}
} |
c23e7bbe-d0cf-4a4f-b635-3f7fc0ba6f61 | 2 | @Override
public Object transformMessage(MuleMessage muleMessage, String s) throws TransformerException {
try {
System.out.println(muleMessage.getPayloadAsString());
String payload = muleMessage.getPayloadAsString();
StringTokenizer tokenizer = new StringTokenizer(payload, "/");
List<String> list = new ArrayList<String>();
while (tokenizer.hasMoreElements()) {
list.add(tokenizer.nextToken());
}
String saveTo = list.get(0);
String fileName = list.get(1);
String content = list.get(2);
muleMessage.setPayload(content);
muleMessage.setProperty(SAVE_TO, saveTo, PropertyScope.SESSION);
muleMessage.setProperty(FILE_NAME, fileName, PropertyScope.SESSION);
muleMessage.setPayload(content);
} catch (Exception e) {
e.printStackTrace();
}
return muleMessage;
} |
523c07d9-77d6-4d0c-bba4-3acedf74d69b | 7 | final Class39_Sub2 method1069(byte byte0) {
if (anIntArray1881 == null) {
return null;
}
Class39_Sub2 aclass39_sub2[] = new Class39_Sub2[anIntArray1881.length];
for (int i = 0; ~i > ~anIntArray1881.length; i++) {
aclass39_sub2[i] = Class39_Sub2.method439(TraversalMap.aClass73_969, anIntArray1881[i], 0);
}
Class39_Sub2 class39Sub2;
if (aclass39_sub2.length != 1) {
class39Sub2 = new Class39_Sub2(aclass39_sub2, aclass39_sub2.length);
} else {
class39Sub2 = aclass39_sub2[0];
}
if (aShortArray1867 != null) {
for (int j = 0; aShortArray1867.length > j; j++) {
class39Sub2.method427(aShortArray1867[j], aShortArray1880[j]);
}
}
if (aShortArray1885 != null) {
for (int k = 0; ~aShortArray1885.length < ~k; k++) {
class39Sub2.method418(aShortArray1885[k], aShortArray1872[k]);
}
}
return class39Sub2;
} |
2570e9a2-712b-4ffa-9838-3645e16a1361 | 7 | public static void main(String... args) throws IOException {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
Group[] g = new Group[n];
for (int i = 0; i < n; i++) {
g[i] = new Group(sc.nextInt(), sc.nextInt(), i + 1);
}
Arrays.sort(g, (a, b) -> b.m - a.m);
int m = sc.nextInt();
Pair[] t = new Pair[m];
for (int i = 0; i < m; i++) {
t[i] = new Pair(sc.nextInt(), i+1);
}
Arrays.sort(t, (a,b) -> a.v - b.v);
int req = 0;
int sum = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
Group g1 = g[i];
int table = findTable(t, g1);
if (table != -1) {
while (table < t.length && t[table].v < 0) {
table++;
}
if (table < t.length) {
req++;
sum += g1.m;
t[table].v = -t[table].v;
sb.append(g1.n).append(' ').append(t[table].i).append('\n');
}
}
}
System.out.println(req + " " + sum);
System.out.println(sb.toString());
} |
6adad8f4-cf00-4913-8b86-683e7aeac13c | 9 | @Test
public void test_DefaultConstructor() {
Grid g = new Grid();
// TEST FOR SIZE (SQUARE)
boolean ok = true;
if(g.getBoard().length != 5) {
ok = false;
}
int badSize =5;
int i = 0;
while(ok && (i<g.getBoard().length)) {
if(g.getBoard()[i].length != 5) {
badSize = g.getBoard()[i].length;
ok = false;
}
i++;
}
// TEST FOR CONTENT OF GRID
i = 0;
boolean charac = true;
char badChar = '-';
int j = 0;
while(charac && (i<g.getBoard().length)) {
while(charac && (j<g.getBoard()[i].length)) {
if(g.getBoard()[i][j] != Grid.DEFAULT_CHAR) {
badChar = g.getBoard()[i][j];
charac = false;
}
j++;
}
i++;
}
assertEquals("the Grid should be a square",5,badSize);
assertEquals("the Grid should contain - in each case of the Grid ",'-',badChar);
} |
357264f8-afbf-4b2c-8b15-55bb9bb6b5ba | 5 | public String toString(){
String text = "Consulta de " + getPaciente() + " as " + getData_inicio();
if(getData_fim() != null)
text += " ate " + getData_fim();
if(medicamentos != null){
int size = medicamentos.size();
if(size > 0){
if(size == 1){
text += " com o medicamento: " + medicamentos.get(0);
} else {
text += " com os medicamentos: " + medicamentos.get(0);
for (int i = 1; i < size; i++)
text += ", " + medicamentos.get(i);
}
}
}
return text;
} |
02242f29-f647-4474-af07-e8682f39d1ff | 2 | @Override
public void windowClosing(WindowEvent event) {
if (!hasOwnedWindowsShowing(this)) {
List<Saveable> saveables = new ArrayList<>();
collectSaveables(this, saveables);
if (SaveCommand.attemptSave(saveables)) {
dispose();
}
}
} |
dca8366c-d57b-45bb-9a90-b61f4cf1b61d | 3 | public static void printMap(){
//Makes HashMap Alphabetical
TreeMap<String, String> printMap= new TreeMap();
printMap.putAll(invertedIndex);
try {
PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
// Used To Print Out map
Iterator it = printMap.keySet().iterator();
Object printS;
while (it.hasNext()) {
printS = it.next();
// Print To Console
//System.out.println(printS + " " + printMap.get(printS));
// Print To File
writer.println(printS + " " + printMap.get(printS));
}
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
91adbb3c-65ff-4485-984d-7438efb9abcc | 8 | @Override
public List<Map<String, ?>> lirtar_trabajor_Navidad(String mes) {
List<Map<String, ?>> Lista = new ArrayList<Map<String, ?>>();
try {
this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "SELECT * from RHVD_FILTRO_NAVIDAD ";
sql += (!mes.equals("")) ? "where TIEMPO_TRABAJO='" + mes.trim() + "'" : "";
ResultSet rs = this.conn.query(sql);
while (rs.next()) {
Map<String, Object> rec = new HashMap<String, Object>();
rec.put("aps", rs.getString("CO_APS"));
rec.put("dep", rs.getString("NO_DEP"));
rec.put("are", rs.getString("NO_AREA"));
rec.put("ti_doc", rs.getString("TI_DOC"));
rec.put("nu_doc", rs.getString("NU_DOC"));
rec.put("sec", rs.getString("NO_SECCION"));
rec.put("pue", rs.getString("NO_PUESTO"));
rec.put("pat", rs.getString("AP_PATERNO"));
rec.put("mat", rs.getString("AP_MATERNO"));
rec.put("nom_t", rs.getString("NO_TRABAJADOR"));
rec.put("nom", rs.getString("NOMBRES"));
rec.put("sex", rs.getString("ES_SEXO"));
rec.put("fe_nac", rs.getString("FE_NAC"));
rec.put("des", rs.getString("FE_DESDE"));
rec.put("has", rs.getString("FE_HASTA"));
rec.put("t_tra", rs.getString("TIEMPO_TRABAJO"));
rec.put("ID_TRABAJADOR", rs.getString("ID_TRABAJADOR"));
Lista.add(rec);
}
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("Error!");
} finally {
try {
this.conn.close();
} catch (Exception e) {
}
}
return Lista;
} |
0e29e98d-c329-4540-ac1b-5555c5b2eff1 | 7 | public void buildClassifier(Instances data) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
data = new Instances(data);
data.deleteWithMissingClass();
if (!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ND) &&
!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ClassBalancedND) &&
!(m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)) {
throw new IllegalArgumentException("END only works with ND, ClassBalancedND " +
"or DataNearBalancedND classifier");
}
m_hashtable = new Hashtable();
m_Classifiers = AbstractClassifier.makeCopies(m_Classifier, m_NumIterations);
Random random = data.getRandomNumberGenerator(m_Seed);
for (int j = 0; j < m_Classifiers.length; j++) {
// Set the random number seed for the current classifier.
((Randomizable) m_Classifiers[j]).setSeed(random.nextInt());
// Set the hashtable
if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ND)
((weka.classifiers.meta.nestedDichotomies.ND)m_Classifiers[j]).setHashtable(m_hashtable);
else if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.ClassBalancedND)
((weka.classifiers.meta.nestedDichotomies.ClassBalancedND)m_Classifiers[j]).setHashtable(m_hashtable);
else if (m_Classifier instanceof weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)
((weka.classifiers.meta.nestedDichotomies.DataNearBalancedND)m_Classifiers[j]).
setHashtable(m_hashtable);
// Build the classifier.
m_Classifiers[j].buildClassifier(data);
}
} |
56d1f2c0-e4db-471f-ad95-78f8daaf9e22 | 2 | public void changeCursor(char lettre) {
switch (lettre) {
case 'D':
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
break;
case 'H':
this.setCursor(new Cursor(Cursor.HAND_CURSOR));
break;
}
}//fin de la m�thode changeCursor |
5c7fe2a4-4522-4b62-b059-98573a768e3e | 0 | @Override
public String getDesc() {
return "Default";
} |
ac15f351-6a20-416b-bb2f-6c532a4a6a19 | 2 | @Override
public boolean deleteSkin(Path skinPath) {
if (!FileUtil.control(skinPath)) {
IllegalArgumentException iae = new IllegalArgumentException("The skin is not existing!");
Main.handleUnhandableProblem(iae);
}
boolean ret = FileUtil.deleteFile(skinPath);
if (ret) {
LOGGER.debug("Skin deleted!");
LOGGER.debug(skinPath.toString());
}
return ret;
} |
0a0c26db-c551-4387-8f37-2c3630669adf | 9 | private void extractCircle(XMLEventReader xrd) throws XMLStreamException {
XMLEvent xev = xrd.nextTag();
if (xev.isStartElement() && xev.asStartElement().getName().getLocalPart().toLowerCase().contains("pos")) {
// skip attributes,comments and whitespace
do {
xev = xrd.nextEvent();
} while (xrd.hasNext() && !xev.isCharacters());
// extract center coords
StringBuilder cenRad = new StringBuilder(xev.asCharacters().getData());
// skip to radius
xev = xrd.nextTag();
xev = xrd.nextTag();
if (xev.isStartElement() && xev.asStartElement().getName().getLocalPart().toLowerCase().contains("radius")) {
// skip attributes,comments and whitespace
do {
xev = xrd.nextEvent();
} while (xrd.hasNext() && !xev.isCharacters());
// extract center coords
cenRad.append(' ').append(xev.asCharacters().getData());
}
// store center coords and radius
ArrayList<String> centerRadius = shapeCoordString.get(Shapes.CIRCLE);
// see if there are similar shapes
if (centerRadius == null) {
// no similar shape create list of coords
centerRadius = new ArrayList<>();
shapeCoordString.put(Shapes.CIRCLE, centerRadius);
}
// add coords to list of shape
centerRadius.add(cenRad.toString());
}
} |
cbae0b7f-3885-408f-84c1-edbf84e96445 | 8 | public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
} |
fcd335a3-e86f-4117-977a-9271791c2e1e | 3 | @Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) {
if (!Commands.isPlayer(sender)) return false;
//String arg2 = (args.length > 1 ? args[1] : null);
//String arg3 = (args.length > 2 ? args[2] : null);
Player p = (Player) sender;
ConfigurationSection cs = ChannelsConfig.getChannels().getConfigurationSection("channels");
if (args.length < 1) return false;
if (!cs.contains(args[0])) {
Messenger.tell(p, Msg.CUSTOM_CHANNELS_NULL);
return false;
}
/*
* TODO: FINISH THIS
* if (args.length > 1) {
if (!arg2.equalsIgnoreCase("joinable")) return false;
if (arg3.equalsIgnoreCase("yes")) {
channel.setJoinable(true);
p.sendMessage("INSERT MESSAGE HERE");
}
if (arg3.equalsIgnoreCase("no")) channel.setJoinable(false);
}
if (args.length == 1) {
if (channel.isJoinable())
}*/
return true;
} |
743be63b-e83d-4b84-a08c-85d7748fe110 | 3 | private int[][] createPattern() {
int[][] squares = new int[NCELLS][NCELLS];
int n = RAND.nextInt(NCELLS);
if (RAND.nextBoolean()){ //make a column of ones
for (int i = 0; i < squares.length; i++) {
squares[i][n] = 1;
}
} else { //make a row of ones
for (int i = 0; i < squares.length; i++) {
squares[n][i] = 1;
}
}
return squares;
} |
1d6d5ab9-05f4-4cf9-81d0-c5fc5bfe68fd | 1 | @Override
public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {
xpos = container.getInput().getMouseX();
ypos = container.getInput().getMouseY();
if(mousePress){
enterGameState(sbg);
}
} |
705ab23b-4395-4728-ae30-03ddb2eedd31 | 6 | * @return Proposition
*/
public static Proposition callDefproposition(Cons arguments) {
{ Cons definition = Cons.cons(Logic.SYM_LOGIC_DEFPROPOSITION, arguments.concatenate(Stella.NIL, Stella.NIL));
Symbol name = null;
Cons options = Stella.NIL;
Stella_Object conception = null;
Proposition proposition = null;
TruthValue oldtruthvalue = null;
{ Object old$Termsourcebeingparsed$000 = Logic.$TERMSOURCEBEINGPARSED$.get();
try {
Native.setSpecial(Logic.$TERMSOURCEBEINGPARSED$, Native.stringify(definition));
arguments = Logic.normalizeDefpropositionArguments(arguments);
name = ((Symbol)(arguments.value));
Logic.internLogicObjectSurrogate(name);
conception = Logic.smartUpdateProposition(arguments.rest.value, Logic.KWD_CONCEIVE);
if (conception == null) {
return (null);
}
else if (Stella_Object.consP(conception)) {
proposition = Logic.conjoinPropositions(((Cons)(conception)));
}
else {
proposition = ((Proposition)(conception));
}
options = arguments.rest.rest;
Logic.stringifiedSourceSetter(proposition, ((String)(Logic.$TERMSOURCEBEINGPARSED$.get())));
KeyValueList.setDynamicSlotValue(proposition.dynamicSlots, Logic.SYM_STELLA_BADp, Stella.TRUE_WRAPPER, null);
Logic.bindLogicObjectToSurrogate(name, proposition);
proposition.processDefinitionOptions(options);
if (proposition.kind == Logic.KWD_FORALL) {
{ Proposition satellite = null;
Cons iter000 = proposition.satellitePropositions().theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
satellite = ((Proposition)(iter000.value));
Proposition.destroyProposition(satellite);
}
}
KeyValueList.setDynamicSlotValue(proposition.dynamicSlots, Logic.SYM_LOGIC_SATELLITE_PROPOSITIONS, null, null);
}
oldtruthvalue = ((TruthValue)(Stella_Object.accessInContext(proposition.truthValue, proposition.homeContext, false)));
if (Proposition.lookupAnnotation(proposition, Logic.KWD_CONFIDENCE_LEVEL) == Logic.KWD_DEFAULT) {
Proposition.removeAnnotation(proposition, Logic.KWD_CONFIDENCE_LEVEL);
Proposition.updatePropositionTruthValue(proposition, Logic.KWD_PRESUME_TRUE);
}
else {
Proposition.updatePropositionTruthValue(proposition, Logic.KWD_ASSERT_TRUE);
}
if (oldtruthvalue == ((TruthValue)(Stella_Object.accessInContext(proposition.truthValue, proposition.homeContext, false)))) {
Proposition.runGoesTrueDemons(proposition);
}
KeyValueList.setDynamicSlotValue(proposition.dynamicSlots, Logic.SYM_STELLA_BADp, null, null);
Logic.registerUnfinalizedObject(proposition);
return (proposition);
} finally {
Logic.$TERMSOURCEBEINGPARSED$.set(old$Termsourcebeingparsed$000);
}
}
}
} |
65ecf9f0-d639-4817-b47d-4c4a9d5b5eaa | 9 | public static final int typeIDObject(Object o) {
if (o instanceof java.lang.Boolean) return 0;
if (o instanceof java.lang.Byte) return 1;
if (o instanceof java.lang.Character) return 2;
if (o instanceof java.lang.Short) return 3;
if (o instanceof java.lang.Integer) return 4;
if (o instanceof java.lang.Long) return 5;
if (o instanceof java.lang.Float) return 6;
if (o instanceof java.lang.Double) return 7;
if (o instanceof java.lang.String) return 11;
return 8;
}; |
4a158d28-d82c-402c-bed9-5747d6b5760d | 2 | public void tick() {
if (isPressed) {
for (ButtonListener listener : listeners) {
System.out.println("Handling press");
listener.buttonPressed();
isPressed = false;
}
}
} |
d0191b1b-0102-46f0-ae24-efcf178f78e5 | 8 | public GameLayout(String locationsFile, String connectionsFile, String actionsFile) throws Exception, FileNotFoundException, IOException{
//Locations*************************************************************************************************
BufferedReader reader = new BufferedReader(new FileReader(locationsFile));
locations = new TreeMap<String, LocationDescription>();
while(reader.ready()){
String name = reader.readLine();
int entry = Integer.parseInt(reader.readLine());
String description = reader.readLine();
String item = reader.readLine();
LocationDescription newLocation = new LocationDescription(name, entry, description, item);
locations.put(name, newLocation);
String extra = reader.readLine();
if(!extra.equals("_")){
throw new Exception("The locations file was not set up properly. Found " + extra + " but expected _");
}
}
reader.close();
//Connections************************************************************************************************
BufferedReader readertwo = new BufferedReader(new FileReader(connectionsFile));
connections = new TreeMap<String, ArrayList<String>>();
while(readertwo.ready()){
ArrayList<String> links = new ArrayList<String>();
String name = readertwo.readLine();
int numConnections = Integer.parseInt(readertwo.readLine());
for(int i = 0; i < numConnections; i++){
links.add(readertwo.readLine());
}
String extra = readertwo.readLine();
if(!extra.equals("_")){
throw new Exception("The connections file was not set up properly. Found " + extra + " but expected _");
}
connections.put(name, links);
}
readertwo.close();
//Actions*****************************************************************************************************
BufferedReader readerthree = new BufferedReader(new FileReader(actionsFile));
actions = new TreeMap<String, ArrayList<Action>>();
while(readerthree.ready()){
ArrayList<Action> actionsByLocation = new ArrayList<Action>();
String name = readerthree.readLine();
int numActions = Integer.parseInt(readerthree.readLine());
for(int i = 0; i < numActions; i++){
String actionName = readerthree.readLine();
int power = Integer.parseInt(readerthree.readLine());
double money = Double.parseDouble(readerthree.readLine());
actionsByLocation.add(new Action(actionName, power, money));
}
String extra = readerthree.readLine();
if(!extra.equals("_")){
throw new Exception("The actions file was not set up properly. Found " + extra + " but expected _");
}
actions.put(name, actionsByLocation);
}
readerthree.close();
} |
33fb9264-f8a9-4a49-b5a3-bd6b35ff44f6 | 6 | public static boolean decodeFileToFile( String infile, String outfile )
{
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try{
in = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( infile ) ),
Base64.DECODE );
out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) );
byte[] buffer = new byte[65536]; // 64K
int read = -1;
while( ( read = in.read(buffer) ) >= 0 ){
out.write( buffer,0,read );
} // end while: through file
success = true;
} catch( java.io.IOException exc ){
exc.printStackTrace();
} finally{
try{ if (in != null) in.close(); } catch( Exception exc ){}
try{ if (out != null) out.close(); } catch( Exception exc ){}
} // end finally
return success;
} // end decodeFileToFile |
ae627566-b07c-4f64-a039-6fd9501028d7 | 3 | public static boolean isEmpty(Board board){
boolean result = true;
for(List<Token> row : board.tokens()){
for(Token t : row){
if(t.isAvailable())result = false;
}
}
return result;
} |
81d29970-018d-435b-8adf-a3cbf553cf9d | 4 | public int calculateAttackValue() {
int actualAttackValue = attackValue;
if (Strength > 10) {
actualAttackValue += Strength - 10;
}
if (Agility > 10) {
actualAttackValue += Agility - 10;
}
if (Dexterity > 10) {
actualAttackValue += Dexterity - 10;
}
if (rightWeapon != null) {
actualAttackValue += rightWeapon.getAttackValue();
}
actualAttackValue += RollDice.roll("k100");
return actualAttackValue;
} |
a3370be6-0a81-4677-bb32-92a864fb6362 | 4 | public List<Claim> getCounterClaimList(String oppositeFileName, String teamType) {
List<Claim> claimList = new ArrayList<Claim>();
Element claimE;
Claim claim = null, claimFlag = null;
ClaimDao parentClaim = new ClaimDao(oppositeFileName);
List<Claim> parentClaimList = parentClaim.getClaimAndSubclaimList(teamType);
for (Iterator i = root.elementIterator("counterclaim"); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.element("isDelete").getText().equals("false")) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogState = claimE.elementText("dialogState")
, parentClaimId = claimE.elementText("parentClaimId");
for (int j = 0; j < parentClaimList.size(); j++) {
if (parentClaimList.get(j).getId().equals(parentClaimId)) {
claimFlag = parentClaimList.get(j);
break;
}
}
claim = new Claim(id, title, description, type
, timeAdded, claimFlag, name, debateId, dialogState);
claimList.add(claim);
}
}
return claimList;
} |
c58e47b7-d7c3-469f-a3ae-cb9908b7a0a1 | 8 | protected void updateStatsForClassifier(double [] predictedDistribution,
Instance instance)
throws Exception {
int actualClass = (int)instance.classValue();
if (!instance.classIsMissing()) {
updateMargins(predictedDistribution, actualClass, instance.weight());
// Determine the predicted class (doesn't detect multiple
// classifications)
int predictedClass = -1;
double bestProb = 0.0;
for(int i = 0; i < m_NumClasses; i++) {
if (predictedDistribution[i] > bestProb) {
predictedClass = i;
bestProb = predictedDistribution[i];
}
}
m_WithClass += instance.weight();
// Determine misclassification cost
if (m_CostMatrix != null) {
if (predictedClass < 0) {
// For missing predictions, we assume the worst possible cost.
// This is pretty harsh.
// Perhaps we could take the negative of the cost of a correct
// prediction (-m_CostMatrix.getElement(actualClass,actualClass)),
// although often this will be zero
m_TotalCost += instance.weight()
* m_CostMatrix.getMaxCost(actualClass, instance);
} else {
m_TotalCost += instance.weight()
* m_CostMatrix.getElement(actualClass, predictedClass,
instance);
}
}
// Update counts when no class was predicted
if (predictedClass < 0) {
m_Unclassified += instance.weight();
return;
}
double predictedProb = Math.max(MIN_SF_PROB,
predictedDistribution[actualClass]);
double priorProb = Math.max(MIN_SF_PROB,
m_ClassPriors[actualClass]
/ m_ClassPriorsSum);
if (predictedProb >= priorProb) {
m_SumKBInfo += (Utils.log2(predictedProb) -
Utils.log2(priorProb))
* instance.weight();
} else {
m_SumKBInfo -= (Utils.log2(1.0-predictedProb) -
Utils.log2(1.0-priorProb))
* instance.weight();
}
m_SumSchemeEntropy -= Utils.log2(predictedProb) * instance.weight();
m_SumPriorEntropy -= Utils.log2(priorProb) * instance.weight();
updateNumericScores(predictedDistribution,
makeDistribution(instance.classValue()),
instance.weight());
// Update other stats
m_ConfusionMatrix[actualClass][predictedClass] += instance.weight();
if (predictedClass != actualClass) {
m_Incorrect += instance.weight();
} else {
m_Correct += instance.weight();
}
} else {
m_MissingClass += instance.weight();
}
} |
25376f7b-9cbb-4a23-ae51-ef33247fc553 | 1 | public static void applyDamagePacks(Actor target, ArrayList<DamagePackage> packs) {
for (int c = 0; c < packs.size(); c++) {
DamagePackage pack = packs.get(c);
applyDamage(target, pack.damage, pack.type);
}
} |
6b181e21-141d-4e89-95bf-994eb7f88d52 | 7 | public void drawRespawnMenu(GL2 gl) {
this.gl = gl;
if(isRespawnOpen()) {
start2D();
if(selection == 0) {
respawnMenu = Texture.findOrCreateByName(FIGHTER);
if(respawnMenu != null) {
respawnMenu.bind(gl);
gl.glBegin(GL2.GL_QUADS);
draw(-s / 2, -s / 2, s, s);
gl.glEnd();
}
}
if(selection == 1) {
respawnMenu = Texture.findOrCreateByName(SCOUT);
respawnMenu.bind(gl);
gl.glBegin(GL2.GL_QUADS);
draw(-s / 2, -s / 2, s, s);
gl.glEnd();
}
if(selection == 2) {
respawnMenu = Texture.findOrCreateByName(BOMBER);
respawnMenu.bind(gl);
gl.glBegin(GL2.GL_QUADS);
draw(-s / 2, -s / 2, s, s);
gl.glEnd();
}
if(selection == 3) {
respawnMenu = Texture.findOrCreateByName(SHOTGUNNER);
respawnMenu.bind(gl);
gl.glBegin(GL2.GL_QUADS);
draw(-s / 2, -s / 2, s, s);
gl.glEnd();
}
if(isRespawnOpen() == false) {
unBind();
}
stop2D();
}
} |
825762da-3b48-4e26-978d-afb532237f6e | 0 | public int getNumberPredators() {
return numberPredators;
} |
09776345-2d7b-4d35-b767-e5380962fce8 | 4 | public HealthPill() {
super((Math.random()*Board.getWIDTH()+1), (Math.random()*Board.getHEIGHT()+1), 0.0f);
switch(Board.getTheme()){
case "Desert": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertPill.png"));
break;
case "Forest": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertPill.png"));
break;
case "Spacial": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertPill.png"));
break;
case "Sea": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertPill.png"));
break;
default: ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertPill.png"));
break;
}
this.image = ii.getImage();
this.width = ii.getIconWidth();
this.height = ii.getIconHeight();
this.value = 2;
this.degrees = Math.random()*360 + 1;
} |
1dcc7782-b0f4-4399-9cf5-3cd381221ecd | 5 | private void addHidden(int startIndex) {
// Find out what kind of pieces can move in this delta
int pieceType = ATTACK_ARRAY[move_to - startIndex + 128];
// If rook is one of types, call addSlider with the right delta and rook
// as piece type
// same if bishop is one of the types
switch (pieceType) {
case ATTACK_KQR:
case ATTACK_QR:
addSlider(startIndex, DELTA_ARRAY[startIndex - move_to + 128],
W_ROOK);
break;
case ATTACK_KQBwP:
case ATTACK_KQBbP:
case ATTACK_QB:
addSlider(startIndex, DELTA_ARRAY[startIndex - move_to + 128],
W_BISHOP);
break;
}
} |
ab8fa669-33e1-42bf-8857-25700443b598 | 9 | public static void main(String[] args) throws IOException {
// Create a selector to multiplex listening sockets and connections
Selector selector = Selector.open();
// Create listening socket channel for PORT and register selector
ServerSocketChannel listnChannel = ServerSocketChannel.open();
listnChannel.socket().bind(new InetSocketAddress(PORT));
listnChannel.configureBlocking(false); // must be nonblocking to
// register
// Register selector with channel. The returned key is ignored
listnChannel.register(selector, SelectionKey.OP_ACCEPT);
// }
// Create a handler that will implement the protocol
TCPProtocol protocol = new ProxySelectorProtocol(BUFSIZE);
while (true) { // Run forever, processing available I/O operations
// Wait for some channel to be ready (or timeout)
if (selector.select(TIMEOUT) == 0) { // returns # of ready chans
System.out.print(".");
continue;
}
// Get iterator on set of keys with I/O to process
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while (keyIter.hasNext()) {
SelectionKey key = keyIter.next(); // Key is bit mask
// Server socket channel has pending connection requests?
try{
if (key.isAcceptable()) {
protocol.handleAccept(key);
}
// Client socket channel has pending data?
if (key.isValid() && key.isReadable()) {
protocol.handleRead(key);
}
// Client socket channel is available for writing and
// key is valid (i.e., channel not closed)?
if (key.isValid() && key.isWritable()) {
protocol.handleWrite(key);
}
}catch(CancelledKeyException e){
key.channel().close();System.out.println("cerrando el channel");
}
keyIter.remove(); // remove from set of selected keys
}
}
} |
4201953c-140e-42e7-9b60-8a9be8a77d0f | 6 | @Override
public void mutate() {
Population offspring = new Population();
for (int i = 0; i < population.getSize(); ++i){
double r;
synchronized (rng){
r = rng.nextDouble();
}
if (r < PROBABILITY){
HiffIndividual mutant = new HiffIndividual(population.getIndividual(i));
for (int k = 0; k < mutant.getSize(); ++k){
mutant.set(k, k % 2);
}
offspring.addIndividual(mutant);
} else {
offspring.addIndividual(new HiffIndividual(population.getIndividual(i)));
}
}
double bestOld = population.getFittest();
double bestNew = offspring.getFittest();
if (bestNew > bestOld){
reward = 1;
for (int i = 0; i < population.getSize(); ++i){
population.setIndividual(i, offspring.getIndividual(i));
}
} else if (bestNew == bestOld){
// reward = 0.5;
reward = 0;
} else {
reward = 0;
}
} |
772f35cf-5df5-4707-a526-cd44e0e61b5e | 9 | public static String keyBasedData(String addy, String[] keys) {
for (int i = 0; i < 10; i++) {// try 10 times to get html or else return
if (i > 0)
System.out.println("\nConnection Failure. Trying again: " + i);
String httpdata = getHtml(addy);
String yhdata = "";
String str = httpdata;
if (str.contains("was not found"))
return "#_#_#";
if (str.contains("Recommendation Trends")) {
str = (str.substring(str.indexOf("Recommendation Trends")));
str = str.replaceAll("d><t", "d> <t");
}
for (String key : keys) {
if (str.contains(">" + key)) {
String strx = str.substring(str.indexOf(">" + key) + 1);
if (!strx.contains("</tr>"))
return "#_#_#";
strx = strx.substring(0, strx.indexOf("</tr>"));
if (key.equals("Sector"))
strx = strx.replaceAll(" ", "|");
strx = removeHtml(strx, true).replaceAll("@", " ");// just
// in
// case
if (strx.length() == 0)
strx = "#";// placeholder if data does not exist
yhdata += strx + "_";
} else {
yhdata += "#_";
}
}
// return spacify(yhdata.replaceAll("--", "#"));
return (yhdata.replaceAll("--", "#").replaceAll("_", " ").trim()
.replaceAll(" ", "_"));
}
return "#_#";
} |
8c90eeb5-9b3f-4efe-9649-a84c152c0986 | 6 | private void addPosition(KrakenState state, ArrayList<KrakenMove> list,
XYLocation location, XYLocation kingLocation, XYLocation finalLocation) {
if (state.checkRange(finalLocation)){
if (state.distance(kingLocation, location, finalLocation)){
if (state.isEmpty(finalLocation))
list.add(new KrakenMove(location, finalLocation));
else
if (!state.getValue(finalLocation).getColor().equals(color))
list.add(new KrakenMove(location, finalLocation));
}else
if (state.getValue(finalLocation) != null && !state.getValue(finalLocation).getColor().equals(color))
list.add(new KrakenMove(location, finalLocation));
}
} |
0078fe9e-7182-4c79-88d1-c5eaae15424b | 6 | public void paintComponent(Graphics g){
super.paintComponent(g);
// fill bottom
g.setColor(new Color(238,238,238));
g.fillRect(0, 550, 1000, 150);
//draw state control
g.setColor(Color.black);
g.drawRect(350, 50, 300, 80);
g.setFont(new Font("sans", Font.PLAIN, 30));
g.drawString("State Control",414,103);
// draw tapehead
int tapeHeadX = tapeHeadCell * 30;
g.drawLine(tapeHeadX+16, 180, tapeHeadX+16, 460);
g.drawLine(tapeHeadX+16, 460, tapeHeadX+11, 455);
g.drawLine(tapeHeadX+16, 460, tapeHeadX+21, 455);
g.drawLine(500 , 180, tapeHeadX+16, 180);
g.drawLine(500 , 180, 500, 130);
// draw cells
int a = 0;
for(int i = 0; i < 33; i++){
g.setColor(Color.black);
g.drawRect(1+a, 460, 30, 30);
a = a+30;
}
// draw symbols
a = 12;
for(int i = 0; i<input.size(); i++){
g.setColor(Color.black);
g.setFont(new Font("arial", Font.PLAIN, 18));
String blank = (String)input.get(i);
if((printOrder == 0) && (i == tapeHeadCell)){}
else{
if((blank.equals("")) || (blank.equals(("Blank Symbol")))){
g.drawRect(a-3, 468, 14, 15);
}
else{
g.drawString((String)input.get(i),a,481);
}
}
a = a+30;
}
} |
5347d241-cabe-4ccf-9ba0-68ed2eb1f963 | 5 | public static void main(String[] args) {
// TODO Auto-generated method stub
String id;
String pass;
String type = "student";
user_dao = DaoFactory.getInstance().getUserDAO();
while (true) {
System.out.print("Registration(r) / Login(l) / ChangePassword(c) / clearDb(clear) : ");
String mode = sc.nextLine();
if (mode.equalsIgnoreCase("r")) {
System.out.println("--------- Registration ---------");
System.out.print("Username : ");
id = sc.nextLine();
System.out.print("Password : ");
pass = sc.nextLine();
System.out.println("Process : "+registration(id,pass));
} else if (mode.equalsIgnoreCase("l")) {
System.out.println("--------- Login ---------");
//LOGIN_SUCCESS,name,type,point
System.out.print("Username : ");
id = sc.nextLine();
System.out.print("Password : ");
pass = sc.nextLine();
User user = new User(id,pass,type);
System.out.println("Process : "+login(id,pass));
} else if ( mode.equalsIgnoreCase("clear")) {
List<User> result = user_dao.findAllUser();
Iterator<User> it = result.iterator();
while(it.hasNext()) {
User user = it.next();
System.out.println(user_dao.deleteUser(user.getUsername(), user.getPassword()));
}
}else
break;
}
} |
93f4fbf7-4f9a-4d95-9aa5-8ca1e7b7515f | 8 | static final void method1212(int i, int i_13_, int i_14_, int i_15_) {
anInt2059++;
i = ((Class348_Sub51) BitmapTable.aClass348_Sub51_3959)
.aClass239_Sub26_7260.method1838(-32350) * i >> -1161142392;
if (i_14_ == i_13_ && !EntityPacket.aBoolean1236)
Class104.method960(1);
else if (i_13_ != -1
&& (i_13_ != RequiredElement.anInt3428 || !Class167.method1296(true))
&& i != 0 && !EntityPacket.aBoolean1236) {
Class40.method368(i, 18002, false, i_13_, Class59_Sub2_Sub1.indexLoader6, 0, i_15_);
Class348_Sub40_Sub17_Sub1.method3093(93);
}
if (RequiredElement.anInt3428 != i_13_)
Class209.aClass348_Sub16_Sub3_2718 = null;
RequiredElement.anInt3428 = i_13_;
} |
7b1cae01-8a56-47e8-b203-9923487df8d7 | 4 | @Path("/database")
@GET
@Produces(MediaType.TEXT_HTML)
public String returnDatabaseStatus() throws Exception {
PreparedStatement query = null;
String myString = null;
String returnString = null;
Connection conn = null;
StringBuffer sb = new StringBuffer();
try {
conn = DB_Conn.getConnection();
// conn = DatabaseConn.dataSourceConn().getConnection();
query = conn.prepareStatement("select username from user");
ResultSet rs = query.executeQuery();
sb.append("<h3>Database read usernames from table:</h3> ");
while (rs.next()) {
myString = rs.getString("username");
returnString = "<p>" + myString + "</p>";
sb.append(returnString);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (conn != null)
try {
conn.close();
} catch (SQLException ignore) {
}
}
return sb.toString();
} |
72f513ae-3515-4582-b606-fab293780685 | 3 | private void loadOptions() {
try {
this.musicVolume = this.parseFloat(this.getProperty("music", "1.0"));
this.soundVolume = this.parseFloat(this.getProperty("sound", "1.0"));
this.mouseSensitivity = this.parseFloat(this.getProperty("mouseSensitivity", "0.5"));
this.invertMouse = this.getProperty("invertMouse", "false").equals("true");
this.renderDistance = Integer.parseInt(this.getProperty("renderDistance", "1"));
this.guiScale = Integer.parseInt(this.getProperty("guiScale", "0"));
this.viewBobbing = this.getProperty("viewBobbing", "true").equals("true");
this.anaglyph = this.getProperty("anaglyph", "false").equals("true");
this.advancedOpengl = this.getProperty("advancedOpengl", "false").equals("true");
this.limitFramerate = Integer.parseInt(this.getProperty("limitFramerate", "3"));
Display.setVSyncEnabled(this.limitFramerate == 3);
this.difficulty = Integer.parseInt(this.getProperty("difficulty", "1"));
this.fancyGraphics = this.getProperty("fancyGraphics", "true").equals("true");
this.ambientOcclusion = this.getProperty("ambientOcclusion", "true").equals("true");
this.ofAoLevel = this.ambientOcclusion ? 1.0F : 0.0F;
this.texturepack = this.getProperty("texturepack", "Default");
this.lastServer = this.getProperty("lastServer", "");
this.ofFogFancy = this.getProperty("ofFogFancy", "true").equals("true");
this.ofFogStart = Config.limit(Float.parseFloat(this.getProperty("ofFogStart", "0.4")), 0.2F, 0.8F);
this.ofMipmapLevel = Config.limit(Integer.parseInt(this.getProperty("ofMipmapLevel", "0")), 0, 4);
this.ofMipmapLinear = this.getProperty("ofMipmapLinear", "false").equals("true");
this.ofLoadFar = this.getProperty("ofLoadFar", "false").equals("true");
this.ofPreloadedChunks = Config.limit(Integer.parseInt(this.getProperty("ofPreloadedChunks", "0")), 0, 8);
this.ofOcclusionFancy = this.getProperty("ofOcclusionFancy", "false").equals("true");
this.ofSmoothFps = this.getProperty("ofSmoothFps", "false").equals("true");
this.ofSmoothInput = this.getProperty("ofSmoothInput", "false").equals("true");
this.ofAnimatedFire = this.getProperty("ofAnimatedFire", "true").equals("true");
this.ofAnimatedFlame = this.getProperty("ofAnimatedFlame", "true").equals("true");
this.ofAnimatedPortal = this.getProperty("ofAnimatedPortal", "true").equals("true");
this.ofAnimatedRedstone = this.getProperty("ofAnimatedRedstone", "true").equals("true");
this.ofAnimatedExplosion = this.getProperty("ofAnimatedExplosion", "true").equals("true");
this.ofAnimatedSmoke = this.getProperty("ofAnimatedSmoke", "true").equals("true");
this.ofAnimatedWater = Config.limit(Integer.parseInt(this.getProperty("ofAnimatedWater", "0")), 0, 2);
this.ofAnimatedLava = Config.limit(Integer.parseInt(this.getProperty("ofAnimatedLava", "0")), 0, 2);
this.ofFastDebugInfo = this.getProperty("ofFastDebugInfo", "true").equals("true");
this.ofBrightness = Config.limit(Float.parseFloat(this.getProperty("ofBrightness", "0.0")), 0.0F, 1.0F);
this.updateWorldLightLevels();
this.ofAoLevel = Config.limit(Float.parseFloat(this.getProperty("ofAoLevel", "1.0")), 0.0F, 1.0F);
this.ambientOcclusion = this.ofAoLevel > 0.0F;
this.ofClouds = Config.limit(Integer.parseInt(this.getProperty("ofClouds", "0")), 0, 3);
this.ofCloudsHeight = Config.limit(Float.parseFloat(this.getProperty("ofCloudsHeight", "0.0")), 0.0F, 1.0F);
this.ofTrees = Config.limit(Integer.parseInt(this.getProperty("ofTrees", "0")), 0, 2);
this.ofGrass = Config.limit(Integer.parseInt(this.getProperty("ofGrass", "0")), 0, 2);
this.ofRain = Config.limit(Integer.parseInt(this.getProperty("ofRain", "0")), 0, 3);
this.ofWater = Config.limit(Integer.parseInt(this.getProperty("ofWater", "0")), 0, 3);
this.ofAutoSaveTicks = Config.limit(Integer.parseInt(this.getProperty("ofAutoSaveTicks", "200")), 40, 40000);
this.ofBetterGrass = Config.limit(Integer.parseInt(this.getProperty("ofBetterGrass", "3")), 1, 3);
this.ofWeather = this.getProperty("ofWeather", "true").equals("true");
this.ofSky = this.getProperty("ofSky", "true").equals("true");
this.ofStars = this.getProperty("ofStars", "true").equals("true");
this.ofChunkUpdates = Config.limit(Integer.parseInt(this.getProperty("ofChunkUpdates", "1")), 1, 5);
this.ofChunkUpdatesDynamic = this.getProperty("ofChunkUpdatesDynamic", "false").equals("true");
this.ofFarView = this.getProperty("ofFarView", "false").equals("true");
this.ofClearWater = this.getProperty("ofClearWater", "true").equals("true");
this.updateWaterOpacity();
this.ofTime = Config.limit(Integer.parseInt(this.getProperty("ofTime", "0")), 0, 2);
for (int i = 0; i < this.keyBindings.length; ++i) {
this.keyBindings[i].keyCode = Integer.parseInt(
this.getProperty(
"key_" + this.keyBindings[i].keyDescription,
String.valueOf(this.keyBindings[i].keyCode)
)
);
}
} catch (Exception exception1) {
System.err.println("Failed to load options");
exception1.printStackTrace();
}
} |
02289bfe-3904-47e1-bb77-4ff282804470 | 6 | private static synchronized Mixer mixer( boolean action, Mixer m )
{
if( action == SET )
{
if( m == null )
return myMixer;
MixerRanking mixerRanker = new MixerRanking();
try
{
mixerRanker.rank( m.getMixerInfo() );
}
catch( LibraryJavaSound.Exception ljse )
{
SoundSystemConfig.getLogger().printStackTrace( ljse, 1 );
SoundSystem.setException( ljse );
}
myMixer = m;
mixerRanking( SET, mixerRanker );
ChannelJavaSound c;
if( instance != null )
{
ListIterator<Channel> itr =
instance.normalChannels.listIterator();
SoundSystem.setException( null );
while( itr.hasNext() )
{
c = (ChannelJavaSound) itr.next();
c.newMixer( m );
}
itr = instance.streamingChannels.listIterator();
while( itr.hasNext() )
{
c = (ChannelJavaSound) itr.next();
c.newMixer( m );
}
}
}
return myMixer;
} |
0cf23a06-3872-4929-b94b-d380c641dd81 | 6 | @Override
public void run() {
while(true){
synchronized (this) {
while(orderList.isEmpty()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
obOut.writeObject(orderList.remove(0));
obOut.flush();
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
if(obOut != null){
try {
obOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
cb84e7f3-9eae-44c1-9d8e-cb094a02d3ba | 2 | public void paintComponent(Graphics graphics) {
try {
if (isMouseOver == false) {
graphics.drawImage(realVersion.image, 4, 4, (this.getWidth() - 6), (this.getHeight() - 6), this);
} else {
graphics.drawImage(scrapperVersion.image, 4, 4, (this.getWidth() - 6), (this.getHeight() - 6), this);
}
} catch (NullPointerException nullImage) {
//System.out.println("ERROR: No Image Reference");
}
parent.repaint();
} |
db03cc87-24cc-4c0d-acf4-e222a1fe4e3d | 8 | public int minimumTotal(List<List<Integer>> triangle) {
if(triangle==null || triangle.isEmpty()){
return 0;
}
int maxLength = triangle.get(triangle.size()-1).size();
int[][] f = new int[triangle.size()][maxLength];
f[0][0]=triangle.get(0).get(0);
for(int i=1; i<triangle.size(); i++){
for(int j=0; j<i+1; j++){
int left = j-1<0?0:j-1;
int right = j>i-1?i-1:j;
f[i][j]=Math.min(f[i-1][left], f[i-1][right])+triangle.get(i).get(j);
}
}
int min = f[triangle.size()-1][0];
for(int i=1; i<triangle.get(triangle.size()-1).size(); i++){
if(f[triangle.size()-1][i]<min){
min = f[triangle.size()-1][i];
}
}
return min;
} |
e889d59e-e1b5-473b-b6a8-891eb3fb43cb | 3 | public double getAngle()
{
if (leftNeighbour == null || rightNeighbour == null)
return -1024;
double leftAngle = getDirection(leftNeighbour);
double rightAngle = getDirection(rightNeighbour);
if (rightAngle < leftAngle) rightAngle += Math.PI * 2;
return rightAngle - leftAngle;
} |
72207fe3-f961-4ba4-a180-aea16124629b | 9 | private ByteMatcher createRandomByteMatcher() {
int matcherType = random.nextInt(9);
boolean inverted = random.nextBoolean();
switch (matcherType) {
case 0:
return AnyByteMatcher.ANY_BYTE_MATCHER;
case 1:
return OneByteMatcher.valueOf((byte) random.nextInt(256));
case 2:
return new InvertedByteMatcher((byte) random.nextInt(256));
case 3:
return new ByteRangeMatcher(random.nextInt(256), random.nextInt(256), inverted);
case 4:
return new SetBinarySearchMatcher(createRandomByteSet(), inverted);
case 5:
return new SetBitsetMatcher(createRandomByteSet(), inverted);
case 6:
return new TwoByteMatcher((byte) random.nextInt(256), (byte) random.nextInt(256));
case 7:
return new AllBitmaskMatcher((byte) random.nextInt(256), inverted);
case 8:
return new AnyBitmaskMatcher((byte) random.nextInt(256), inverted);
default:
throw new RuntimeException("Case statement doesn't support value " + matcherType);
}
} |
faa09ffa-7e69-4745-a24f-02f797c2077b | 0 | public void setCheckBox(JCheckBox checkbox) {
this.checkbox = checkbox;
} |
fa9f5c43-4fc0-4029-9312-28ab5e8334c2 | 0 | private synchronized int nextId() {
return ++next_id;
} |
8623b38b-a012-48e9-a3ad-67cfffdbd08c | 1 | public static <T> Set<T> hashSet(T... params) {
Set<T> result = new HashSet<T>();
for (T t : params) {
result.add(t);
}
return result;
} |
4ece8cb6-6134-4c0f-80a8-12f332e8b745 | 2 | @Override
public void update(Observable arg0, Object arg1) {
if (!(arg0 instanceof Timer)) return;
Timer timer = (Timer) arg0;
int s = timer.getTime();
if (s < 5) lblTime.setForeground(Color.red);
lblTime.setText(s + "");
validate();
repaint();
} |
c23914b8-ce93-4364-b467-26725f07ae53 | 3 | public RegularGrammar convertToRegularGrammar(Automaton automaton) {
/** check if automaton is fsa. */
if (!(automaton instanceof FiniteStateAutomaton)) {
System.err.println("ATTEMPTING TO CONVERT NON FSA TO "
+ "REGULAR GRAMMAR");
return null;
}
RegularGrammar grammar = new RegularGrammar();
/** map states in automaton to variables in grammar. */
initializeConverter(automaton);
/**
* go through all transitions in automaton, creating production for
* each.
*/
Transition[] transitions = automaton.getTransitions();
for (int k = 0; k < transitions.length; k++) {
Production production = getProductionForTransition(transitions[k]);
grammar.addProduction(production);
}
/**
* for all final states in automaton, add lambda production.
*/
State[] finalStates = automaton.getFinalStates();
for (int j = 0; j < finalStates.length; j++) {
Production lprod = getLambdaProductionForFinalState(automaton,
finalStates[j]);
grammar.addProduction(lprod);
}
return grammar;
} |
684a59aa-82ca-487d-88cd-fa148f81ad21 | 7 | static private boolean jj_3R_9() {
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_23()) { jj_scanpos = xsp; break; }
}
if (jj_scan_token(ID)) return true;
if (jj_scan_token(LP)) return true;
if (jj_3R_21()) return true;
if (jj_scan_token(RP)) return true;
if (jj_3R_22()) return true;
return false;
} |
780a244f-d097-45d4-9daf-4286e0407bff | 3 | public String toString() {
String input = ""+getBias();
for(Neuron key : dendrites.keySet()) {
if(key != this) {
if(dendrites.get(key) >= 0) input += "+";
input += dendrites.get(key) + "*" + key.toString();
}
}
return _function.toString(input);
} |
39dcb603-b910-4234-a909-b0f444b6c0e5 | 1 | public boolean type(char key, java.awt.event.KeyEvent ev) {
if(key == 27) {
clbk.result(false);
close();
}
return(super.type(key, ev));
} |
21ba3abe-2497-43aa-bc33-84ebed37ae81 | 4 | @Override
public void run() {
try {
while (true) {
@SuppressWarnings("resource")
Socket socket = mServerSocket.accept();
try {
Client client = new Client(this, socket);
client.setDaemon(true);
client.start();
synchronized (mClients) {
mClients.add(client);
}
} catch (IOException ioe) {
// The client died an early death... ignore it.
socket.close();
}
}
} catch (Exception exception) {
shutdown();
}
Client[] clients;
synchronized (mClients) {
clients = mClients.toArray(new Client[0]);
mClients.clear();
}
for (Client element : clients) {
element.shutdown();
}
} |
bb602479-9e5d-43e9-9673-735410fffe45 | 1 | @SuppressWarnings("unchecked")
public synchronized List<NodeOsm> getNodes(String key, List<Long> ids){
List<NodeOsm> nodes = new ArrayList<NodeOsm>();
for (Long l: ids)
nodes.add(((NodeOsm) getKeyFromValue((Map< String, Map <Object, Long>>) ((Object)totalNodes), key, l)));
nodes.remove(null);
return nodes;
} |
afe3ad36-5700-4d39-b77c-20969af32c8a | 0 | public int getSequenceID() {
return this.sequenceID;
} |
b683627b-93f3-4930-9c8f-a13452cbe9a7 | 9 | private boolean r_mark_suffix_with_optional_U_vowel() {
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
// (, line 159
// or, line 161
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 160
// (, line 160
// test, line 160
v_2 = limit - cursor;
if (!(in_grouping_b(g_U, 105, 305)))
{
break lab1;
}
cursor = limit - v_2;
// next, line 160
if (cursor <= limit_backward)
{
break lab1;
}
cursor--;
// (, line 160
// test, line 160
v_3 = limit - cursor;
if (!(out_grouping_b(g_vowel, 97, 305)))
{
break lab1;
}
cursor = limit - v_3;
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 162
// (, line 162
// not, line 162
{
v_4 = limit - cursor;
lab2: do {
// (, line 162
// test, line 162
v_5 = limit - cursor;
if (!(in_grouping_b(g_U, 105, 305)))
{
break lab2;
}
cursor = limit - v_5;
return false;
} while (false);
cursor = limit - v_4;
}
// test, line 162
v_6 = limit - cursor;
// (, line 162
// next, line 162
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// (, line 162
// test, line 162
v_7 = limit - cursor;
if (!(out_grouping_b(g_vowel, 97, 305)))
{
return false;
}
cursor = limit - v_7;
cursor = limit - v_6;
} while (false);
return true;
} |
3eeded25-84a7-4c47-8aea-f89efb79957c | 2 | public User loadUser(String userid) {
File f = new File(users, userid + ".sav");
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
Object o = in.readObject();
if (o instanceof User) {
return ((User) o);
}
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return new User();
} |
08947542-0138-43e1-ab80-f5b647a02a8e | 9 | public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.err.println("ERROR: Missing input file argument.");
System.exit(0);
}
// INPUT VARS
FileReader inputStream = null;
CharBuffer cbuf = CharBuffer.allocate(100000);
InputStream inputSentenceModel = null;
InputStream inputTokenizerModel = null;
try {
// get trained english sentence model for sentence splitter
inputSentenceModel = new FileInputStream("../doc/en-sent.bin");
SentenceModel model = new SentenceModel(inputSentenceModel);
SentenceDetectorME sDetector = new SentenceDetectorME(model);
// get english tokenizer model
inputTokenizerModel = new FileInputStream("../doc/en-token.bin");
TokenizerModel tokModel = new TokenizerModel(inputTokenizerModel);
Tokenizer tokenizer = new TokenizerME(tokModel);
// read incomming data file into String
inputStream = new FileReader(args[0]);
int bytesRead = inputStream.read(cbuf); // read entire file into buffer
String rawText = new String(cbuf.array(), 0, bytesRead);
// parse text into Sentances
String sentences[] = sDetector.sentDetect(rawText);
for (int x = 0; x < sentences.length; x++) { // add start and end tags to all sentences
String[] tokenizedSentence = tokenizer.tokenize(sentences[x]);
System.out.print("<s> "); // start tag
for (int y = 0; y < tokenizedSentence.length; y++) {
if (y == tokenizedSentence.length - 1) {
System.out.print(tokenizedSentence[y]);
} else {
System.out.print(tokenizedSentence[y] + " ");
}
}
if (x != sentences.length - 1) {
System.out.print(" </s>\n\n");
} else {
System.out.print(" </s>");
}
}
System.out.print("\0"); // EOF
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} finally {
// close input streams
if (inputStream != null) {
inputStream.close();
}
if (inputSentenceModel != null) {
inputSentenceModel.close();
}
if (inputTokenizerModel != null) {
inputTokenizerModel.close();
}
}
} |
c7d75566-0dea-4ae0-8ae3-e68ff7f9a827 | 8 | public void startMovingToTarget(float maxVelocity)
{
// LET ITS POSITIONG GET UPDATED
movingToTarget = true;
// CALCULATE THE ANGLE OF THE TRAJECTORY TO THE TARGET
float diffX = targetX - x;
float diffY = targetY - y;
float tanResult = diffY/diffX;
float angleInRadians = (float)Math.atan(tanResult);
// COMPUTE THE X VELOCITY COMPONENT
vX = (float)(maxVelocity * Math.cos(angleInRadians));
// CLAMP THE VELOCTY IN CASE OF NEGATIVE ANGLES
if ((diffX < 0) && (vX > 0)) vX *= -1;
if ((diffX > 0) && (vX < 0)) vX *= -1;
// COMPUTE THE Y VELOCITY COMPONENT
vY = (float)(maxVelocity * Math.sin(angleInRadians));
// CLAMP THE VELOCITY IN CASE OF NEGATIVE ANGLES
if ((diffY < 0) && (vY > 0)) vY *= -1;
if ((diffY > 0) && (vY < 0)) vY *= -1;
} |
49f29744-1468-41aa-82d8-eb81f40049b1 | 1 | public void setTexture(String texturePath){
try {
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(texturePath));
} catch (IOException e) {
e.printStackTrace();
}
} |
1e0b6ee4-8168-4b52-a740-e0bae97cc498 | 2 | public boolean isDone() {
int toDo = pToT.size() - alreadyDone.size();
String message = toDo == 0 ? "The conversion is finished!" : toDo
+ " more transition" + (toDo == 1 ? "" : "s")
+ " must be added.";
javax.swing.JOptionPane.showMessageDialog(parent, message);
return toDo == 0;
} |
a037c0e6-2bb5-4918-abc2-1dbd1a1686ce | 4 | public void usePotion(){
System.out.println("What type of potion would you like?");
System.out.println("Type 'mana potion' to use a mana potion");
System.out.println("Type 'health potion' to use a health potion");
String potionType = input.nextLine();
if(potionType.compareTo("mana potion") == 0){
if(this.getManaPotion() == 0){
System.out.println("Sorry no potions!");
}
else{
this.setManaOnPotionUse();
}
}
else if(potionType.compareTo("health potion") == 0){
if(this.getHealthPotion() == 0){
System.out.println("Sorry no potions!");
}
else{
this.setHealthOnPotionUse();
}
}
} |
b95bb931-0908-4196-925c-bf7999021f2f | 8 | public void readMsg() {
if (nUpdateRectsLeft == 0) {
int type = is.readU8();
switch (type) {
case MsgTypes.framebufferUpdate: readFramebufferUpdate(); break;
case MsgTypes.setColourMapEntries: readSetColourMapEntries(); break;
case MsgTypes.bell: readBell(); break;
case MsgTypes.serverCutText: readServerCutText(); break;
default:
vlog.error("unknown message type "+type);
throw new Exception("unknown message type");
}
} else {
int x = is.readU16();
int y = is.readU16();
int w = is.readU16();
int h = is.readU16();
int encoding = is.readU32();
switch (encoding) {
case Encodings.pseudoEncodingDesktopSize:
handler.setDesktopSize(w, h);
break;
case Encodings.pseudoEncodingCursor:
readSetCursor(x, y, w, h);
break;
default:
readRect(x, y, w, h, encoding);
break;
}
nUpdateRectsLeft--;
if (nUpdateRectsLeft == 0) handler.framebufferUpdateEnd();
}
} |
2923d4b2-73ee-4e30-8503-0f9e28ef5fbf | 0 | public double getLongitude() {
return longitude;
} |
606304ac-bfee-4a02-96cf-899e5fd38dff | 6 | public void execute() {
while(running){
try{
int idx = getProgramCounter();
String opcode = "0x" + Integer.toHexString(code.getOpcode(idx)).toUpperCase();
boolean imm = code.getImmediate(idx);
boolean ind = code.getIndirect(idx);
int arg = code.getArg(idx);
INSTRUCTION_MAP.get(opcode).execute(arg, imm, ind);
}catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(
frame,
"There was an error in accessing data memory.",
"Warning",
JOptionPane.OK_OPTION);
halt();
}catch(IndexOutOfBoundsException e){
JOptionPane.showMessageDialog(
frame,
"There was an error in accessing code of the program.",
"Warning",
JOptionPane.OK_OPTION);
halt();
}catch(NullPointerException e){
JOptionPane.showMessageDialog(
frame,
"There was a a Null Pointer, indicating that there is an error in the simulator.",
"Warning",
JOptionPane.OK_OPTION);
halt();
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(
frame,
"Illegal access to code\n"
+ "Exception message: " + e.getMessage(),
"Run time error",
JOptionPane.OK_OPTION);
halt();
}catch(DivideByZeroException e){
JOptionPane.showMessageDialog(
frame,
"Error: DIV by zero.\n"
+ "Exception message: " + e.getMessage(),
"Run time error",
JOptionPane.OK_OPTION);
halt();
}
}
setChanged();
notifyObservers();
} |
249874f5-6872-4a78-a1ce-feed910f0ac9 | 0 | public void setType(String type){
this.type = type;
} |
d2fc2803-3fb4-4974-ad08-6cb9830c9d01 | 5 | public void configure( JobConf job )
{
confJsonStr = job.get( "confJsonStr" );
if( confJsonStr == null )
{
LOG.warn( "confJsonStr is null" );
return;
}
LOG.debug( confJsonStr );
confMap = JSON.decode( confJsonStr );
try
{
if( confMap.containsKey( "rrd" ) )
{
Map rrdMap = ( Map )confMap.get( "rrd" );
if( rrdMap.containsKey( "step" ) )
{
step = Long.parseLong( rrdMap.get( "step" ) + "" );
}
if( rrdMap.containsKey( "heartbeat" ) )
{
heartbeat = Long.parseLong( rrdMap.get( "heartbeat" ) + "" );
}
}
}
catch( Exception e )
{
LOG.warn( e );
}
} |
634de6e2-30a4-4a65-bb0c-4070c95dc022 | 1 | public int compareTo(Object o) {
if (o instanceof User) {
User other = (User) o;
return other._lowerNick.compareTo(_lowerNick);
}
return -1;
} |
4e041c2d-42a1-4b7f-8208-49ca844ea187 | 4 | public void friendsPortalEnter(Player player){
String invitedWorld = plugin.worldInvitation.get(player);
if (invitedWorld != null){
String worldN = plugin.getIfMainWorld(invitedWorld);
String invitingPlayerName;
if (worldN != null){
invitingPlayerName = invitedWorld.substring(worldN.length() + 1);
}else{
invitingPlayerName = invitedWorld.substring(invitedWorld.lastIndexOf("_"));
invitingPlayerName = invitingPlayerName.substring(1);
}
if (Bukkit.getPlayer(invitingPlayerName) != null){
Player inviting_player = Bukkit.getPlayer(invitingPlayerName);
if (inviting_player.getWorld().getName().equals(plugin.worldInvitation.get(player))){
world = Bukkit.getServer().getWorld(plugin.worldInvitation.get(player));
plugin.worldInvitation.remove(player);
plugin.worldInvitationTime.remove(player);
plugin.tpToWorld(world, inviting_player.getLocation(), player, false);
}else{
player.sendMessage(ChatColor.RED + "'" + invitingPlayerName + "' is no longer in the invited world!");
world = Bukkit.getServer().getWorld(plugin.lobbyWorld);
plugin.tpToWorld(world, world.getSpawnLocation(), player, true);
}
}else{
player.sendMessage(ChatColor.RED + "'" + invitingPlayerName + "' is no longer online!");
world = Bukkit.getServer().getWorld(plugin.lobbyWorld);
plugin.tpToWorld(world, world.getSpawnLocation(), player, true);
}
}else{
player.sendMessage(ChatColor.RED + "You dont have any invitations!");
world = Bukkit.getServer().getWorld(plugin.lobbyWorld);
plugin.tpToWorld(world, world.getSpawnLocation(), player, true);
}
} |
251671ef-0aa7-4af4-959b-4afede358b21 | 9 | public Board(BoardBuilder boardBuilder) {
width = boardBuilder.getWidth();
height = boardBuilder.getHeight();
cells = new Cell[getCellCount()];
cellsListView = Collections.unmodifiableList(Arrays.asList(cells));
int numberSum = 0;
final int maxNum = 0;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
final int number = boardBuilder.getNumber(x, y);
if (number == 0) {
cells[coordsToIndex(x, y)] = new SimpleCell(this, x, y);
}
else {
cells[coordsToIndex(x, y)] = new FixedCell(this, x, y, number);
}
numberSum += number;
}
}
if (numberSum <= 0) {
throw new IllegalArgumentException("no white fixed cells");
}
else if (numberSum > getCellCount()) {
throw new IllegalArgumentException("solution impossible, to many expected white cells");
}
solutionWhiteCount = numberSum;
maxNumber = maxNum;
neighborSets = cellsListView.stream().map(cell -> {
final int x = cell.getX();
final int y = cell.getY();
final Builder<Cell> builder = ImmutableSet.<Cell>builder();
if (isLegalCoord(x + 1, y)) {
builder.add(getCell(x + 1, y));
}
if (isLegalCoord(x - 1, y)) {
builder.add(getCell(x - 1, y));
}
if (isLegalCoord(x, y + 1)) {
builder.add(getCell(x, y + 1));
}
if (isLegalCoord(x, y - 1)) {
builder.add(getCell(x, y - 1));
}
return builder.build();
}).collect(Collectors.toList());
} |
5f2dbabd-168b-49f3-8aac-55dda5db510b | 5 | private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c))
break;
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c))
break;
chunk.append(c);
marker++;
}
}
return chunk.toString();
} |
04dcd5de-b0cc-445f-8f78-a1c5f1b310d1 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
} |
eabb690f-8625-4fa8-9adc-c873ccdebf81 | 5 | public static void main(String[] args) {
System.out.println(keyboard.length());
final GuitarString[] strings = new GuitarString[37];
for(int i = 0; i < strings.length; i++){
strings[i] = new GuitarString(440.0 * Math.pow(2.0, (i - 24.0) / 12.0));
// System.out.println(440.0 * Math.pow(2.0, (i - 24.0) / 12.0));
}
// Starts with a C chord as a sample
strings[0].pluck();
strings[4].pluck();
strings[7].pluck();
// Loads the keyboard image mapping keyboard keys to piano keys
BufferedImage key = null;
try {
key = ImageIO.read(new File("keyboard.png"));
} catch (IOException e) {
e.printStackTrace();
}
// Initializes the JFrame
JFrame f = new JFrame();
f.setSize(500, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Guitar");
f.setVisible(true);
Graphics g = f.getGraphics();
// Adds a key listener
f.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
int keyIndex = keyboard.indexOf(c);
if(keyIndex >= 0 && keyIndex < strings.length){
strings[keyIndex].pluck();
}
}
@Override
public void keyReleased(KeyEvent arg0) {}
});
//
while(true){
double sample = sampleAll(strings);
StdAudio.play(sample);
ticAll(strings);
g.drawImage(key, 20, 40, null); // This definitely shouldn't go here... but it doesn't seem to work anywhere else yet.
}
} |
b741924e-640d-4643-8aeb-04aaf865e341 | 9 | public void run()
{
jTextArea.append("Starting Server Side Socket On Port 27331: ");
try{
sslserverSocket = (SSLServerSocket) javax.net.ssl.SSLServerSocketFactory.getDefault().createServerSocket(port);
//sslserverSocket.setEnabledCipherSuites(sslserverSocket.getEnabledCipherSuites());
} catch (IOException e){
jTextArea.append("(ERROR: "+e.getMessage()+")\n");
}finally{
if(sslserverSocket != null)
jTextArea.append("Done\n");
else{
jTextArea.append("Shutting Down Due To: No Open Ports for the ServerSocket\n");
return;
}
}
jTextArea.append("Starting Server Socket Thread: ");
socketThread.start();
jTextArea.append("Done\n");
jTextArea.append("Starting Socket Run Thread: ");
socketRunThread.start();
jTextArea.append("Done\n");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
try{
if(br.ready())
switch(br.readLine())
{
case "EXIT":
return;
default:
jTextArea.append("Type /help or /? for a list of commands\n");
}
} catch (IOException e){
//FIXME
}
for(int i=0;i<socketList.size();i++)
if(socketList.get(i).newClientMessage())
for(int j=0;j<socketList.size();j++){
socketList.get(j).getClientPrinter().println(socketList.get(i).getClientName()+": "+socketList.get(i).getClientMessage());
System.out.println("new message sent");
}
}
} |
6fe83bd5-a0bf-43a1-8a9f-aaea7662cf43 | 4 | public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof Parameter)) return false;
Parameter otherParam = (Parameter) other;
return otherParam.key.equals(key) && otherParam.value.equals(value);
} |
2bd4c480-19fb-4c12-91a1-d4d1b8c08276 | 6 | public static void main(String[] args) throws IOException
{
logger = Logger.getLogger("MCListener");
logger.setUseParentHandlers(false);
Handler handler = new ConsoleHandler();
handler.setFormatter(new LogFormatter());
logger.addHandler(handler);
try
{
loadConfig();
}
catch(IOException e)
{
System.err.println(e.getMessage());
return;
}
ServerListener listener = new ServerListener(port);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String line = reader.readLine();
if(line.equalsIgnoreCase("exit") || line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("stop"))
break;
}
MCListener.logger.info("Shutting down...");
listener.close();
} |
8bb85755-75a2-483a-a929-2e765ee55e59 | 3 | public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
} |
f7e4404f-7ccc-4641-8175-8f17ef00bde0 | 9 | @SuppressWarnings("static-access")
@Override
public void run(String[] args) {
Options options = new Options();
options.addOption(OptionBuilder
.withLongOpt("train")
.isRequired()
.withArgName("filename")
.hasArg()
.withDescription(
"Filename prefix with training dataset. It must "
+ "exist three files with this prefix with "
+ "the following sufixes: .grandparent, "
+ ".leftsiblings and .rightsiblings.").create());
options.addOption(OptionBuilder.withLongOpt("templates").isRequired()
.withArgName("filename").hasArg()
.withDescription("Filename prefix with templates.").create());
options.addOption(OptionBuilder
.withLongOpt("numepochs")
.withArgName("integer")
.hasArg()
.withDescription(
"Number of epochs: how many iterations over the"
+ " training set.").create());
options.addOption(OptionBuilder.withLongOpt("testconll")
.withArgName("filename").hasArg()
.withDescription("CoNLL-format test dataset.").create());
options.addOption(OptionBuilder
.withLongOpt("outputconll")
.withArgName("filename")
.hasArg()
.withDescription(
"Name of the CoNLL-format file to save the output.")
.create());
options.addOption(OptionBuilder.withLongOpt("test")
.withArgName("filename").hasArg()
.withDescription("Filename prefix with test dataset.").create());
options.addOption(OptionBuilder.withLongOpt("script")
.withArgName("path").hasArg()
.withDescription("CoNLL evaluation script (eval.pl).").create());
options.addOption(OptionBuilder
.withLongOpt("perepoch")
.withDescription(
"The evaluation on the test corpus will "
+ "be performed after each training epoch.")
.create());
options.addOption(OptionBuilder
.withLongOpt("maxsteps")
.withArgName("integer")
.hasArg()
.withDescription(
"Maximum number of steps in the subgradient method.")
.create());
options.addOption(OptionBuilder
.withLongOpt("beta")
.withArgName("real number")
.hasArg()
.withDescription(
"Fraction of the edge factor weights that "
+ "are passed to the maximum branching "
+ "algorithm, instead of the passing to "
+ "the grandparent/siblings algorithm.")
.create());
options.addOption(OptionBuilder.withLongOpt("seed")
.withArgName("integer").hasArg()
.withDescription("Random number generator seed.").create());
options.addOption(OptionBuilder
.withLongOpt("lossweight")
.withArgName("double")
.hasArg()
.withDescription(
"Weight of the loss term in the inference objective function.")
.create());
options.addOption(OptionBuilder
.withLongOpt("noavg")
.withDescription(
"Turn off the weight vector averaging, i.e.,"
+ " the algorithm returns only the final weight "
+ "vector instead of the average of each step "
+ "vectors.").create());
// Parse the command-line arguments.
CommandLine cmdLine = null;
PosixParser parser = new PosixParser();
try {
cmdLine = parser.parse(options, args);
} catch (ParseException e) {
System.err.println(e.getMessage());
CommandLineOptionsUtil.usage(getClass().getSimpleName(), options);
}
// Print the list of options along the values provided by the user.
CommandLineOptionsUtil.printOptionValues(cmdLine, options);
// Training options.
String trainPrefix = cmdLine.getOptionValue("train");
String trainEdgeDatasetFileName = trainPrefix + ".edges";
String trainGPDatasetFileName = trainPrefix + ".grandparent";
String trainLSDatasetFileName = trainPrefix + ".siblings.left";
String trainRSDatasetFileName = trainPrefix + ".siblings.right";
String templatesPrefix = cmdLine.getOptionValue("templates");
String templatesEdgeFileName = templatesPrefix + ".edges";
String templatesGPFileName = templatesPrefix + ".grandparent";
String templatesLSFileName = templatesPrefix + ".siblings.left";
String templatesRSFileName = templatesPrefix + ".siblings.right";
int numEpochs = Integer.parseInt(cmdLine.getOptionValue("numepochs",
"10"));
int maxSubgradientSteps = Integer.valueOf(cmdLine.getOptionValue(
"maxsteps", "500"));
double beta = Double.valueOf(cmdLine.getOptionValue("beta", "0.001"));
// double lossWeight =
// Double.parseDouble(cmdLine.getOptionValue("lossweight", "0d"));
boolean averaged = !cmdLine.hasOption("noavg");
String seedStr = cmdLine.getOptionValue("seed");
// Test options.
String testConllFileName = cmdLine.getOptionValue("testconll");
String outputConllFilename = cmdLine.getOptionValue("outputconll");
String testPrefix = cmdLine.getOptionValue("test");
String testEdgeDatasetFilename = testPrefix + ".edges";
String testGPDatasetFilename = testPrefix + ".grandparent";
String testLSDatasetFilename = testPrefix + ".siblings.left";
String testRSDatasetFilename = testPrefix + ".siblings.right";
String script = cmdLine.getOptionValue("script");
boolean evalPerEpoch = cmdLine.hasOption("perepoch");
/*
* Options --testconll, --outputconll and --test must always be provided
* together.
*/
if ((testPrefix == null) != (testConllFileName == null)
|| (outputConllFilename == null) != (testConllFileName == null)) {
LOG.error("the options --testconll, --outputconll and --test "
+ "must always be provided together (all or none)");
System.exit(1);
}
DPGSDataset trainDataset = null;
FeatureEncoding<String> featureEncoding = null;
try {
/*
* Create an empty and flexible feature encoding that will encode
* unambiguously all feature values. If the training dataset is big,
* this may not fit in memory and one should consider using a fixed
* encoding dictionary (based on test data or frequency on training
* data, for instance) or a hash-based encoding.
*/
featureEncoding = new StringMapEncoding();
trainDataset = new DPGSDataset(new String[] { "bet-postag",
"add-head-feats", "add-mod-feats" }, new String[] {
"bet-hm-postag", "bet-hg-postag", "add-head-feats",
"add-mod-feats", "add-gp-feats" }, new String[] {
"bet-hm-postag", "bet-ms-postag", "add-head-feats",
"add-mod-feats", "add-sib-feats" }, "|", featureEncoding);
LOG.info(String.format("Loading training edge dataset (%s)...",
trainEdgeDatasetFileName));
trainDataset.loadEdgeFactors(trainEdgeDatasetFileName);
LOG.info(String.format(
"Loading training left siblings dataset (%s)...",
trainLSDatasetFileName));
trainDataset.loadSiblingsFactors(trainLSDatasetFileName);
LOG.info(String.format(
"Loading training right siblings dataset (%s)...",
trainRSDatasetFileName));
trainDataset.loadSiblingsFactors(trainRSDatasetFileName);
/*
* Grandparent factors shall be the last ones to avoid problems with
* short sentences (1 ordinary token), since grandparent factors do
* not exist for such short sentences.
*/
LOG.info(String.format(
"Loading training grandparent dataset (%s)...",
trainGPDatasetFileName));
trainDataset.loadGrandparentFactors(trainGPDatasetFileName);
// Set modifier variables in all output structures.
trainDataset.setModifierVariables();
// Template-based model.
LOG.info("Allocating initial model...");
// Model.
DPGSModel model = new DPGSModel(0);
// Templates.
model.loadEdgeTemplates(templatesEdgeFileName, trainDataset);
model.loadGrandparentTemplates(templatesGPFileName, trainDataset);
model.loadLeftSiblingsTemplates(templatesLSFileName, trainDataset);
model.loadRightSiblingsTemplates(templatesRSFileName, trainDataset);
// Generate derived features from templates.
model.generateFeatures(trainDataset);
// Inference algorithm for training.
DPGSInference inference = new DPGSInference(
trainDataset.getMaxNumberOfTokens());
// Learning algorithm.
Perceptron alg = new Perceptron(inference, model, numEpochs, 1d,
true, averaged, LearnRateUpdateStrategy.NONE);
if (seedStr != null)
// User provided seed to random number generator.
alg.setSeed(Long.parseLong(seedStr));
if (testConllFileName != null && evalPerEpoch) {
LOG.info("Loading test factors...");
DPGSDataset testset = new DPGSDataset(trainDataset);
testset.loadEdgeFactors(testEdgeDatasetFilename);
testset.loadSiblingsFactors(testLSDatasetFilename);
testset.loadSiblingsFactors(testRSDatasetFilename);
testset.loadGrandparentFactors(testGPDatasetFilename);
testset.setModifierVariables();
model.generateFeatures(testset);
LOG.info("Evaluating...");
// Use dual inference algorithm for testing.
DPGSDualInference inferenceDual = new DPGSDualInference(
testset.getMaxNumberOfTokens());
inferenceDual
.setMaxNumberOfSubgradientSteps(maxSubgradientSteps);
inferenceDual.setBeta(beta);
// // TODO test
// DPGSInference inferenceDual = new DPGSInference(
// testset.getMaxNumberOfTokens());
// inferenceDual.setCopyPredictionToParse(true);
EvaluateModelListener eval = new EvaluateModelListener(script,
testConllFileName, outputConllFilename, testset,
averaged, inferenceDual);
eval.setQuiet(true);
alg.setListener(eval);
}
LOG.info("Training model...");
// Train model.
alg.train(trainDataset.getInputs(), trainDataset.getOutputs());
LOG.info(String.format("# updated parameters: %d",
model.getNumberOfUpdatedParameters()));
if (testConllFileName != null && !evalPerEpoch) {
LOG.info("Loading test factors...");
DPGSDataset testset = new DPGSDataset(trainDataset);
testset.loadEdgeFactors(testEdgeDatasetFilename);
testset.loadSiblingsFactors(testLSDatasetFilename);
testset.loadSiblingsFactors(testRSDatasetFilename);
testset.loadGrandparentFactors(testGPDatasetFilename);
testset.setModifierVariables();
model.generateFeatures(testset);
LOG.info("Evaluating...");
// Use dual inference algorithm for testing.
DPGSDualInference inferenceDual = new DPGSDualInference(
testset.getMaxNumberOfTokens());
inferenceDual
.setMaxNumberOfSubgradientSteps(maxSubgradientSteps);
inferenceDual.setBeta(beta);
// // TODO test
// DPGSInference inferenceDual = new DPGSInference(
// testset.getMaxNumberOfTokens());
// inferenceDual.setCopyPredictionToParse(true);
EvaluateModelListener eval = new EvaluateModelListener(script,
testConllFileName, outputConllFilename, testset, false,
inferenceDual);
eval.setQuiet(true);
eval.afterEpoch(inferenceDual, model, -1, -1d, -1);
}
LOG.info("Training done!");
} catch (Exception e) {
LOG.error("Error during training", e);
System.exit(1);
}
} |
1cb69921-6206-416d-984b-6522f17f147d | 6 | public void test4() {
if (b)
;
else if (b || (new Integer(i)).toString().contains("Whatever")
&& new Double(d).compareTo(new Double(5.0)) > 55 || !(i >> 2 > 0)
&& (new String()) instanceof Object)
;
else
;
} |
0709b45c-e1ca-4417-a225-42d1aa624fed | 0 | public MessUndefined(int date, int id, int taille) {
super(date, id, taille);
} |
18e0034b-0c2b-4b48-a1c6-969d3489713a | 2 | private void handleUpdate() {
// We can simplify this when we move more methods into the Preference Interface.
if (pref instanceof PreferenceInt) {
PreferenceInt prefInt = (PreferenceInt) pref;
prefInt.setTmp(field.getText());
field.setText(String.valueOf(prefInt.tmp));
} else if (pref instanceof PreferenceString) {
PreferenceString prefString = (PreferenceString) pref;
prefString.setTmp(field.getText());
field.setText(prefString.tmp);
}
} |
28f4df24-6539-4834-a0b3-f5c4895a8e8e | 1 | private void resize(int capacity) {
Key[] temp = (Key[]) new Comparable[capacity];
for (int i = 0; i <= N; i++) {
temp[i] = pq[i];
}
this.pq = temp;
} |
8c77f92b-bc97-440f-bb99-1c441d7d2146 | 6 | public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if ((col > 0) && tableData[row][col]!=null && row < tableRows-1) {
return true;
}
else if(tableData[row][col] == null && (row == 0 || tableData[row-1][col] != null)) {
return true;
}
return false;
} |
00fd5a33-e6ff-4e91-ad98-dd0a75033d2d | 4 | @Override
public void tick() {
ticks++;
x += r.nextInt(2);
y += r.nextInt(2);
if (x < -0 || y < 0 || x >= game.getScaledWidth() || y >= game.getScaledHeight()) {
x = r.nextInt(game.getScaledWidth());
y = 0;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.