method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
af3e9f81-07b3-4322-aef5-94a10905dfd2
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddApplicant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddApplicant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddApplicant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddApplicant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddApplicant().setVisible(true);
}
});
}
|
1d9b079d-474d-4301-ab95-a496a2ab0a38
| 4
|
public void testForStyle_stringLengths() {
try {
DateTimeFormat.forStyle(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forStyle("");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forStyle("S");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forStyle("SSS");
fail();
} catch (IllegalArgumentException ex) {}
}
|
7cc2ac77-6da7-4187-ac76-195c9268cb8c
| 7
|
public boolean wordBreak2(String s, Set<String> wordDict) {
int n = s.length();
if (n < 1) return false;
// T[i][j] == true iff s[i..j] is segmentable
boolean[][] seg = new boolean[n][n];
for (int l=0; l<n; ++l) { // segment length, seg[i,i] has length of 0.
for (int i=0; i<n-l; ++i) { // start letter
int j = i + l;
if (wordDict.contains(s.substring(i, j+1))) {
seg[i][j] = true;
continue;
}
for (int k=i; k<j; ++k) { // intermediate letter
if (seg[i][k] && seg[k+1][j]) {
seg[i][j] = true;
break;
}
}
}
}
return seg[0][n-1];
}
|
da8f1202-ceb5-43fe-8d4a-919bb84d48dd
| 5
|
private void onPowerOn(){
startRun_enabled = false;
stopRun_enabled = false;
postApp_enabled = true;
resetSDSU_enabled = true;
resetPCI_enabled = false;
setupServer_enabled = false;
powerOn_enabled = false;
powerOff_enabled = true;
logPanel.add("Powered on SDSU", LogPanel.OK, true);
_setEnabledActions();
boolean active = true;
int n = 0;
while(n < 5){
n++;
if((active = isRunActive(false)) && n < 5)
try { Thread.sleep(1000); } catch(Exception e){};
}
if(active)
logPanel.add("Timed out waiting for 'power on' run to de-activate; cannot initialise run number. Stu, please tell me if this happens", LogPanel.ERROR, false);
else
getRunNumber();
}
|
9d137960-97cd-4cdd-9d0a-c145e277d702
| 9
|
private HttpResponse send(String urlString, String method,
Map<String, String> parameters, Map<String, String> propertys)
throws IOException {
HttpURLConnection urlConnection = null;
if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0) {
param.append("?");
} else {
param.append("&");
}
param.append(key).append("=").append(parameters.get(key));
i++;
}
urlString += param;
}
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if (propertys != null) {
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key));
}
}
if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
for (String key : parameters.keySet()) {
param.append("&");
param.append(key).append("=").append(parameters.get(key));
}
urlConnection.getOutputStream().write(param.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
}
return this.makeContent(urlString, urlConnection);
}
|
6d8fcfe7-3130-4f5e-8ac2-ecb1191a7efe
| 1
|
public boolean setUserlistImageFrameHeight(int height) {
boolean ret = true;
if (height <= 0) {
this.userlistImgFrame_Height = UISizeInits.USERLIST_IMAGEFRAME.getHeight();
ret = false;
} else {
this.userlistImgFrame_Height = height;
}
setUserlistImageOverlay_Height(this.userlistImgFrame_Height);
somethingChanged();
return ret;
}
|
42409240-3a86-49e9-bcaa-143f95a51a05
| 7
|
public boolean shouldExecute()
{
if (!this.theEntity.isCollidedHorizontally)
{
return false;
}
else
{
PathNavigate var1 = this.theEntity.getNavigator();
PathEntity var2 = var1.getPath();
if (var2 != null && !var2.isFinished() && var1.getCanBreakDoors())
{
for (int var3 = 0; var3 < Math.min(var2.getCurrentPathIndex() + 2, var2.getCurrentPathLength()); ++var3)
{
PathPoint var4 = var2.getPathPointFromIndex(var3);
this.entityPosX = var4.xCoord;
this.entityPosY = var4.yCoord + 1;
this.entityPosZ = var4.zCoord;
if (this.theEntity.getDistanceSq((double)this.entityPosX, this.theEntity.posY, (double)this.entityPosZ) <= 2.25D)
{
this.targetDoor = this.func_48318_a(this.entityPosX, this.entityPosY, this.entityPosZ);
if (this.targetDoor != null)
{
return true;
}
}
}
this.entityPosX = MathHelper.floor_double(this.theEntity.posX);
this.entityPosY = MathHelper.floor_double(this.theEntity.posY + 1.0D);
this.entityPosZ = MathHelper.floor_double(this.theEntity.posZ);
this.targetDoor = this.func_48318_a(this.entityPosX, this.entityPosY, this.entityPosZ);
return this.targetDoor != null;
}
else
{
return false;
}
}
}
|
53947bba-ce76-48ab-b4c6-e2579fede1d5
| 1
|
public void loadBackup(Backup bk, boolean userLoaded){
if (!userLoaded)
DB = bk.getPath() + File.separator + DB_NAME;
else
DB = bk.getPath();
dblite = new SQLiteConnection(new File(DB));
}
|
9ac36984-0bb2-4884-991b-b7f36286477a
| 2
|
protected void initStatistics(String html) {
//create stats
if(generateStatistics) {
statistics = new HtmlCompressorStatistics();
statistics.setTime((new Date()).getTime());
statistics.getOriginalMetrics().setFilesize(html.length());
//calculate number of empty chars
Matcher matcher = emptyPattern.matcher(html);
while(matcher.find()) {
statistics.getOriginalMetrics().setEmptyChars(statistics.getOriginalMetrics().getEmptyChars() + 1);
}
} else {
statistics = null;
}
}
|
67cb107c-6696-4190-954b-782029548c98
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
|
deba4db5-9a97-46ae-9572-5a679d539ebb
| 3
|
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
if(args.length == 0){
System.out.println("Please provide the location of the workload file!");
System.exit(1);
}
try {
String fileName = args[0];
// number of grid user entities + any Workload entities.
int num_user = 1;
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
// Initialize the GridSim package without any statistical
// functionalities. Hence, no GridSim_stat.txt file is created.
System.out.println("Initializing GridSim package");
GridSim.init(num_user, calendar, trace_flag);
//////////////////////////////////////////
// Creates one or more GridResource entities
int rating = 377; // rating of each PE in MIPS
int totalPE = 9; // total number of PEs for each Machine
int totalMachine = 128; // total number of Machines
String resName = "Res_0";
GridResource resource = createGridResource(resName, rating, totalMachine, totalPE);
//////////////////////////////////////////
// Creates one Workload trace entity.
WorkloadFileReader model = new WorkloadFileReader(fileName, rating);
Workload workload = new Workload("Load_1", resource.get_name(), model);
// Start the simulation in normal mode
boolean debug = true;
GridSim.startGridSimulation(debug);
if(!debug) {
long finishTime = System.currentTimeMillis();
System.out.println("The simulation took " + (finishTime - startTime) + " milliseconds");
}
// prints the Gridlets inside a Workload entity
// workload.printGridletList(trace_flag);
}
catch (Exception e) {
e.printStackTrace();
}
}
|
ef2c22ec-e6fc-4c62-96df-95fbea8806e3
| 4
|
public int login(String uname, String pword) throws Throwable {
md5 enc = new md5();
SQLite_helper log = new SQLite_helper();
ResultSet user = log.retrieve("users","username", uname);
if(!user.next()) {
return 0;
} else {
String username = user.getString("username");
if(username.compareTo(uname) == 0) {
String pword_hash = enc.encrypt(pword);
String password = user.getString("password");
if(password.compareTo(pword_hash) == 0) {
enc.close();
if(user.getBoolean("isAdmin")) {
return 1;
} else {
return 2;
}
} else {
enc.close();
log.destruct();
return 0;
}
} else {
enc.close();
log.destruct();
return 0;
}
}
}
|
44492320-6a86-4d54-9c42-48d0aadb2933
| 3
|
private static void bfsRec(mxAnalysisGraph aGraph, Set<Object> queued, LinkedList<Object[]> queue, mxICellVisitor visitor)
{
if (queue.size() > 0)
{
Object[] q = queue.removeFirst();
Object cell = q[0];
Object incomingEdge = q[1];
visitor.visit(cell, incomingEdge);
final Object[] edges = aGraph.getEdges(cell, null, false, false);
for (int i = 0; i < edges.length; i++)
{
Object[] currEdge = { edges[i] };
Object opposite = aGraph.getOpposites(currEdge, cell)[0];
if (!queued.contains(opposite))
{
Object[] current = { opposite, edges[i] };
queue.addLast(current);
queued.add(opposite);
}
}
bfsRec(aGraph, queued, queue, visitor);
}
};
|
9a61c524-dbe0-42a9-8813-fa4388aa8d36
| 2
|
private ServerInfo getServer( InetSocketAddress inetSocketAddress ) {
for ( ServerInfo s : ProxyServer.getInstance().getServers().values() ) {
if ( s.getAddress().equals( inetSocketAddress ) ) {
return s;
}
}
return null;
}
|
e5c88fe9-fa37-4539-a128-3c725d1671e9
| 6
|
protected void ensureExists(int firstKey, int secondKey) {
ConcurrentHashMap<Integer, Object> map = distrLocks.get(firstKey);
if (map == null) {
ConcurrentHashMap<Integer, Object> new_map = new ConcurrentHashMap<Integer, Object>();
map = distrLocks.putIfAbsent(firstKey, new_map);
if (map == null) {
map = new_map;
}
}
Object lock = map.get(secondKey);
if (lock == null) {
Object new_lock = new Object();
lock = map.putIfAbsent(secondKey, new_lock);
if (lock == null) {
synchronized(new_lock) {
ConcurrentHashMap<Integer, DiscreteDistribution> dmap =
distributions.get(firstKey);
if (dmap == null) {
dmap = new ConcurrentHashMap<Integer, DiscreteDistribution>();
distributions.put(firstKey, dmap);
}
dmap.put(secondKey, new DiscreteDistribution());
ConcurrentHashMap<Integer, IntegerBuffer> bmap = buffers.get(firstKey);
if (bmap == null) {
bmap = new ConcurrentHashMap<Integer, IntegerBuffer>();
buffers.put(firstKey, bmap);
}
bmap.put(secondKey, new IntegerBuffer(BUFFER_CAPACITY));
}
} else {
synchronized(lock) {
// We're just waiting for the other thread to release the lock, so that we can
// get the buffer without crashing later. Another thread actually added it,
// but we have to wait for them.
}
}
}
}
|
81f60be8-f68f-4797-9067-f9ce95da3bd2
| 6
|
public void init() {
if (user == null && userId!=0) {
user = userService.findUser(userId);
} else if (user == null && userId==0) {
user = new User();
}
if (user == null) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("error/404.xhtml");
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
}
}
|
1004c0f7-dc41-4a7b-b6d0-083c5761b468
| 5
|
public String addBinary_2(String a, String b) {
StringBuffer res = new StringBuffer();
int m = a.length();
int n = b.length();
int carry = 0;
for (int i = 0; !(i>=m && i>=n); ++i){ // stop when i >= m && i >= n
int tmp = 0;
if (i >= m) {
tmp = carry + b.charAt(n-1-i) - '0';
}else if (i >= n){
tmp = carry + a.charAt(m-1-i) - '0';
}else {
tmp = carry + a.charAt(m-1-i) - '0' + b.charAt(n-1-i) - '0';
}
carry = tmp / 2;
res.append(tmp%2);
}
if (carry == 1){
res.append(carry);
}
return res.reverse().toString();
}
|
66c28a29-e040-4879-93c4-5a11e962ec8d
| 5
|
protected static boolean checkResource(Resource resource) {
boolean isValid;
if (isValid = resource != null) {
isValid = TYPES.contains(resource.getType());
isValid = isValid && resource.getProperty(URL_PROPERTY) != null;
isValid = isValid && resource.getProperty(USERNAME_PROPERTY) != null;
isValid = isValid && resource.getProperty(PASSWORD_PROPERTY) != null;
isValid = isValid && getDriver(resource.getProperty(URL_PROPERTY)) != null;
}
return isValid;
}
|
43bcf3cf-e0bb-4cef-a0d5-9fee2a772e3f
| 7
|
public void actionPerformed(ActionEvent event){
if(event.getSource()==submitButton){
String userId=textBox.getText();
if(!userId.equals("")){
textBox.setText("");
ut = new TwitterAnalysis();
ut.analyze(userId);
int i,num=UserTopTenTweets.tw.size();
for(i=0;i<10;i++){
String temp="";
if(i<num)
temp=UserTopTenTweets.tw.poll();
tweetLabel[i].setText(temp);
}
i=0;
for(String temp : TwitterAnalysis.newsData){
newsLabel[i].setText(temp);
final String t=temp;
newsLabel[i].setCursor(new Cursor(Cursor.HAND_CURSOR));
MouseListener[] arrMouseListeners = newsLabel[i].getMouseListeners();
for ( MouseListener m : arrMouseListeners ) {
newsLabel[i].removeMouseListener(m);
}
newsLabel[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI(t));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
});
i++;
}
}
else{
JOptionPane.showMessageDialog(null,"Text Box is empty");
}
}
}
|
7042f855-7259-4324-a171-6e6306e5abe9
| 6
|
private boolean download(String link, File output) {
InputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL(link);
in = url.openStream();
out = new FileOutputStream(output);
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
}
pluginLogger.info("Download complete, restart server to apply");
return true;
} catch (IOException e) {
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
}
}
}
}
|
26797198-fe89-46ef-a7f9-104a47cf5b45
| 2
|
public Record updateRecord(Record record){
for(Record r:table){
if(r.getUsername().compareToIgnoreCase(record.getUsername())==0){
r.setSessionKey(record.getSessionKey());
r.setTimeStamp(record.getTimeStamp());
}
}
return null;
}
|
552d18be-bb6a-40f8-b174-3c7d092cf228
| 5
|
public void createScreenShot()
{
File screenshotFile = null;
JFileChooser chooser = new JFileChooser();
UIManager.put("FileChooser.saveDialogTitleText", "Save Michelizer Screenshot");
SwingUtilities.updateComponentTreeUI(chooser);
chooser.setSelectedFile(new File("Michelizer_Output.jpg"));
screenshotFile = chooser.getSelectedFile();
if(JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(this))
{
// Wait for JFileChooser to close!
try { Thread.sleep(750); }
catch (InterruptedException ie) { ie.printStackTrace(); }
screenshotFile = chooser.getSelectedFile();
String path = screenshotFile.getAbsolutePath().substring(0, screenshotFile.getAbsolutePath().length() - screenshotFile.getName().length());
String fileName = screenshotFile.getName().substring(0, screenshotFile.getName().length()-4);
String extension = ".jpg";
if(screenshotFile.exists())
{
int counter = 1;
while(screenshotFile.exists())
screenshotFile = new File(path + fileName + " (" + counter++ + ")" + extension);
}
try
{
Rectangle r = new Rectangle(getX(), getY(), getWidth(), getHeight());
BufferedImage bi = ScreenImage.createImage(r);
ScreenImage.writeImage(bi, screenshotFile.getAbsolutePath());
}
catch(Exception exception) { exception.printStackTrace(); }
}
}
|
0649ecaf-be31-483b-902c-adc2d0c212c8
| 4
|
private void initAStar(List<Scenery> opened, Scenery startingScenery) {
Set<Scenery> adjacencies = new HashSet<Scenery>();
adjacencies = getAdjacencies(startingScenery);
for (Scenery adjacency : adjacencies) {
adjacency.setParent(startingScenery);
if (!adjacency.equals(startingScenery) && adjacency.isWalkable() && adjacency != null) {
opened.add(adjacency);
}
}
}
|
b33da354-9138-4aa5-ab24-3d516079ec13
| 5
|
public void paint(Graphics g) {
super.paint(g);
if (ingame) {
Graphics2D g2d = (Graphics2D)g;
if (craft.isVisible())
g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(),
this);
ArrayList ms = craft.getMissiles();
for (int i = 0; i < ms.size(); i++) {
missile m = (missile)ms.get(i);
g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);
}
for (int i = 0; i < aliens.size(); i++) {
Alien a = (Alien)aliens.get(i);
if (a.isVisible())
g2d.drawImage(a.getImage(), a.getX(), a.getY(), this);
}
g2d.setColor(Color.WHITE);
g2d.drawString("Score:"+""+score+" "+"Aliens left: " + aliens.size(), 5, 15);
} else {
String msg1 = "Game Over"+ " --- "+"Score ="+" " + score;
Font small = new Font("Hvetica", Font.BOLD, 14);
FontMetrics metr = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg1, (B_WIDTH - metr.stringWidth(msg1)) / 2,
B_HEIGHT / 2);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
|
85dbe62d-157b-4741-90dd-e0209730522e
| 4
|
public void listCleanUp(){
for(int i = 0; i < collisionList.size(); i++){
if(collisionList.get(i).isDead()){
collisionList.remove(i);
}
}
for(int i = 0; i < paintList.size(); i++){
if(paintList.get(i).isDead()){
paintList.remove(i);
}
}
}
|
7ec09681-291f-4165-a905-9e19c4752a1d
| 6
|
public List<List<Double>> getRankNormalizedDataPoints()
{
List<List<Double>> rankList = new ArrayList<List<Double>>();
for( int x=0; x < getSampleNames().size(); x++)
{
List<RankHolder> innerRanks = new ArrayList<RankHolder>();
for( int y=0; y < getOtuNames().size(); y++ )
{
RankHolder rh = new RankHolder();
rh.originalData = getDataPointsNormalized().get(x).get(y);
rh.originalIndex = y;
innerRanks.add(rh);
}
Collections.sort(innerRanks, new Comparator<RankHolder>()
{@Override
public int compare(RankHolder o1, RankHolder o2)
{
return Double.compare(o1.originalData, o2.originalData);
}});
List<Double> crankedList = new ArrayList<Double>();
for( RankHolder rh : innerRanks)
crankedList.add(rh.originalData);
crank(crankedList);
for( int y=0; y < innerRanks.size(); y++)
innerRanks.get(y).rank = crankedList.get(y);
double[] ranks = new double[innerRanks.size()];
for( int y=0; y < innerRanks.size(); y++)
{
RankHolder rh = innerRanks.get(y);
ranks[rh.originalIndex] = rh.rank;
}
List<Double> newList = new ArrayList<Double>();
for( Double d : ranks)
newList.add(d);
rankList.add(newList);
}
return rankList;
}
|
7bbf32f8-2c2a-4024-bb38-b3f5392b23f2
| 3
|
public boolean create(final Player player, final Sign state) {
final Function function = this.getFunction(state);
if (function == null) {
Main.courier.send(player, "messages.unknownFunction", state.getLine(1));
return false;
}
if (!function.canApply(player)) {
Main.courier.send(player, "messages.applyDenied", function.getName());
return false;
}
state.setLine(0, this.title);
state.setLine(1, function.getName());
if (!state.update()) {
Main.courier.send(player, "messages.createFailed");
return false;
}
Main.courier.send(player, "messages.createSuccess");
return true;
}
|
14325688-a621-4b38-807d-2f9da1439ec0
| 4
|
private String escapeString(String s) {
StringBuffer stringBuffer = new StringBuffer();
char backslash = '\\';
char previousChar = 0;
char ch = 0;
for (int i = 0; i < s.length(); i++) {
previousChar = ch;
ch = s.charAt(i);
if (ch == '\\') {
//stringBuffer.append("\\\\");
stringBuffer.append(ch);
}
else if (ch == '"') {
if (previousChar == '\\') {
stringBuffer.append("\\\"");
}
else {
stringBuffer.append('"');
}
}
else {
stringBuffer.append(ch);
}
}
return stringBuffer.toString();
}
|
8374c68a-b640-429e-b0ff-b2aaf8be35b0
| 7
|
public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and when the
// cumulative sum is less than 1.0 (as a result of floating-point roundoff error)
while (true) {
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum > r) return i;
}
}
}
|
5c873e14-0e5c-4795-90a4-d263875b9330
| 4
|
public Type createRangeType(ReferenceType bottom) {
/*
* tArray(y), tArray(x) -> tArray( y.intersection(x) ) obj , tArray(x)
* -> <obj, tArray(x)> iff tArray extends and implements obj
*/
if (bottom.getTypeCode() == TC_ARRAY)
return tArray(elementType
.intersection(((ArrayType) bottom).elementType));
if (bottom.getTypeCode() == TC_CLASS) {
ClassInterfacesType bottomCIT = (ClassInterfacesType) bottom;
if (bottomCIT.clazz == null
&& implementsAllIfaces(null, arrayIfaces, bottomCIT.ifaces))
return tRange(bottomCIT, this);
}
return tError;
}
|
8647bea0-a9f6-41d2-977b-39a739cf3151
| 5
|
public boolean add(Row row) {
Boolean bool = true;
for (Row r : this) {
for (int i = 0; i < r.size(); i++) {
if (!r.get(i).equals(row.get(i))) {
break;
}
if (i == r.size() - 1) {
bool = false;
}
}
}
if (bool) {
_rows.add(row);
}
return bool;
}
|
bff27199-1ded-4fba-9ea8-a8e4ebf9ef11
| 1
|
@Override
public boolean matches(String inputExt, String outputExt) {
return StringUtils.equalsIgnoreCase(inputExt, "properties") && StringUtils.endsWithIgnoreCase(outputExt, "xls");
}
|
b8982f3f-ac70-45e3-9f70-8a69feb69810
| 8
|
public void actionPerformed(ActionEvent e) {
final Page p = (Page) getTextComponent(e);
Element[] elem = p.getSelectedParagraphs();
if (elem == null)
return;
float currentIndent = 0.0f;
AttributeSet as = null;
StyledDocument doc = p.getStyledDocument();
Element head = null;
Icon icon = null;
for (int i = 0; i < elem.length; i++) {
// find out the current indent of this selected paragraph
as = elem[i].getAttributes();
currentIndent = StyleConstants.getLeftIndent(as);
head = doc.getCharacterElement(elem[i].getStartOffset());
icon = StyleConstants.getIcon(head.getAttributes());
if (!(icon instanceof BulletIcon)) {
SimpleAttributeSet sas = new SimpleAttributeSet(as);
StyleConstants.setLeftIndent(sas, currentIndent + Page.INDENT_STEP);
doc.setParagraphAttributes(elem[i].getStartOffset(), elem[i].getEndOffset() - elem[i].getStartOffset(),
sas, false);
as = new SimpleAttributeSet();
StyleConstants.setIcon((MutableAttributeSet) as, BulletIcon.get(BulletIcon.OPEN_SQUARE_BULLET));
try {
doc.insertString(elem[i].getStartOffset(), " ", null);
doc.insertString(elem[i].getStartOffset(), " ", as);
}
catch (BadLocationException ble) {
ble.printStackTrace(System.err);
}
if (p.isEditable())
p.getSaveReminder().setChanged(true);
}
else {
SimpleAttributeSet sas = new SimpleAttributeSet(as);
StyleConstants.setLeftIndent(sas, currentIndent - Page.INDENT_STEP > 0 ? currentIndent
- Page.INDENT_STEP : 0);
doc.setParagraphAttributes(elem[i].getStartOffset(), elem[i].getEndOffset() - elem[i].getStartOffset(),
sas, false);
try {
doc.remove(elem[i].getStartOffset(), 3);
}
catch (BadLocationException ble) {
ble.printStackTrace(System.err);
}
if (p.isEditable())
p.getSaveReminder().setChanged(true);
}
}
}
|
7341b24f-5860-42f2-bc60-4b731c325105
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(circulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(circulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(circulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(circulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new circulo().setVisible(true);
}
});
}
|
1af2c3e3-67d0-4558-b0c0-a56351e6f816
| 9
|
public void removerUsuario(){
if ( this.num_usuarios == 0 ) System.out.println("\nNão existem "
+ "usuários.");
else{
System.out.println("\nQual dos usuários você gostaria de remover? "
+ "[ 1 - " + this.num_usuarios + " ]" );
int i = 1;
for ( Usuario x : this.usuarios ){
System.out.println( i + ")" + x);
i++;
}
System.out.print(" > ");
Scanner scan = new Scanner(System.in);
int op;
while(true){
if (scan.hasNextInt())
op = scan.nextInt();
else{
System.out.print("Erro. Insira um número.\n\n > ");
scan.next();
continue;
}
break;
}
op -= 1;
if( op < 0 || op > this.num_usuarios - 1 ){
System.out.println("Número inválido.");
}
else{
System.out.print("\nRemover o usuário "
+ usuarios.get(op).getUsername() + "? [ s / n ]"
+ "\n\n > " );
Scanner scan2 = new Scanner(System.in);
String resposta = scan2.nextLine();
if ( !"s".equals(resposta) && !"n".equals(resposta) ){
System.out.println("Resposta inválida.");
}
else{
if ( "s".equals(resposta) ){
this.usuarios.remove(op);
this.num_usuarios--;
System.out.println("\nUsuário removido com sucesso.");
}
else{
System.out.println("\nOk. Saindo...");
}
}
}
}
}
|
4570f12b-697b-4bcc-9c92-e63774138ee9
| 3
|
@Override
public List<Rule> getRulesForLhs(List<Specie> species) {
List<Rule> affectingLHSRules = new ArrayList<Rule>();
for (Rule rule : rules) {
for (Specie specie : species) {
if (!rule.getLhs().contains(specie)) {
break;
}
affectingLHSRules.add(rule);
}
}
return affectingLHSRules;
}
|
ed49ac03-c71f-4aed-a3fc-8c6e6e35173c
| 4
|
static private double getBaseValue(Converter[] u, String n){
int i=0;
while (i < u.length
&& !u[i].abrv.equalsIgnoreCase(n)
&& !u[i].unit.equalsIgnoreCase(n)) {
i++;
}
if (i >= u.length)
return 1;
else
return u[i].toBase;
}
|
dcf7ee0c-d94c-4940-8a81-cea37b104e9d
| 3
|
public double[] getCalibrationData() {
if (calibrationType == MEAN) {
double[] meanArray = new double[1];
meanArray[0] = mean;
return meanArray;
} else {
double[] calibrationData = new double[calibrationDataSize];
int index = 0;
for (int i = 0; i < data.length; i++) {
if (calibrationFlag[i]) {
calibrationData[index] = data[i];
index++;
}
}
return calibrationData;
}
}
|
34486c9d-fadb-4b30-b2b9-74d7c091ec8b
| 6
|
public void sortiere( int[] zahlen, int l, int r ) {
setRekursionen( getRekursionen() + 1 );
int positionLinks = l;
int positionRechts = r;
/*
* Sortierung von der Mitte aus starten, Pivotzahl finden
*/
int pivot = zahlen[ ( l + r ) / 2 ];
/*
* solange sie sich noch nicht getroffen haben
*/
do {
/*
* @formatter:off suche von links ein Element, dass groesser ist als
* das Pivot 1 5 6 |3| 7 8 0 i->
*/
while ( zahlen[ positionLinks ] < pivot ) {
positionLinks++;
}
/*
* @formatter:off suche von rechts ein Element, dass groesser ist
* als das Pivot 1 5 6 |3| 7 8 0 <-j
*/
while ( zahlen[ positionRechts ] > pivot ) {
positionRechts--;
}
// Zahlen links und rechts vertauschen
if ( positionLinks <= positionRechts ) {
int falscherWertL = zahlen[ positionLinks ];
zahlen[ positionLinks ] = zahlen[ positionRechts ];
zahlen[ positionRechts ] = falscherWertL;
positionLinks++;
positionRechts--;
}
} while ( positionLinks <= positionRechts );
/*
* Rekursion
*/
if ( l < positionRechts ) {
sortiere( zahlen, l, positionRechts );
}
if ( positionLinks < r ) {
sortiere( zahlen, positionLinks, r );
}
}
|
11dc02b8-f328-408e-8d16-c34406cd8ace
| 0
|
public int getS1() {
return this.state;
}
|
a5b0639a-da6e-403b-be75-9bb24ec6a190
| 2
|
public MCDObjet getElement(String name) {
for (Iterator<ZElement> e = enumElements(); e.hasNext();) {
MCDObjet o = (MCDObjet) e.next();
if (o.getName().equals(name))
return o;
}
return null;
}
|
307f3bfa-f78b-4d42-b96d-c5435062d3d2
| 0
|
public String getContrindic() {
return contrindic;
}
|
42adebf1-a44c-43fe-ae06-2e338cdb7d1b
| 3
|
void doReceive(final File file, final boolean resume) {
new Thread() {
public void run() {
BufferedOutputStream foutput = null;
Exception exception = null;
try {
// Convert the integer address to a proper IP address.
int[] ip = _bot.longToIp(_address);
String ipStr = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];
// Connect the socket and set a timeout.
_socket = new Socket(ipStr, _port);
_socket.setSoTimeout(30*1000);
_startTime = System.currentTimeMillis();
// No longer possible to resume this transfer once it's underway.
_manager.removeAwaitingResume(DccFileTransfer.this);
BufferedInputStream input = new BufferedInputStream(_socket.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(_socket.getOutputStream());
// Following line fixed for jdk 1.1 compatibility.
foutput = new BufferedOutputStream(new FileOutputStream(file.getCanonicalPath(), resume));
byte[] inBuffer = new byte[BUFFER_SIZE];
byte[] outBuffer = new byte[4];
int bytesRead = 0;
while ((bytesRead = input.read(inBuffer, 0, inBuffer.length)) != -1) {
foutput.write(inBuffer, 0, bytesRead);
_progress += bytesRead;
// Send back an acknowledgement of how many bytes we have got so far.
outBuffer[0] = (byte) ((_progress >> 24) & 0xff);
outBuffer[1] = (byte) ((_progress >> 16) & 0xff);
outBuffer[2] = (byte) ((_progress >> 8) & 0xff);
outBuffer[3] = (byte) ((_progress >> 0) & 0xff);
output.write(outBuffer);
output.flush();
delay();
}
foutput.flush();
}
catch (Exception e) {
exception = e;
}
finally {
try {
foutput.close();
_socket.close();
}
catch (Exception anye) {
// Do nothing.
}
}
_bot.onFileTransferFinished(DccFileTransfer.this, exception);
}
}.start();
}
|
3563010f-43f8-43b8-9fce-7a43ed769b0e
| 5
|
public ArrayList<Coordinate> getAvailableMoves (){
if (m_test){
System.out.println("AIEasy.getAvailableMoves- begin");
}
ArrayList<Coordinate> a = new ArrayList <Coordinate> ();
for (int x=0; x<getGame().getGrid().getGridWidth();x++){
for (int y=0; y<getGame().getGrid().getGridHeight();y++){
Coordinate c1 = new Coordinate (x, y,getGame().getPlayerTurn());
if (getGame().isValidMove(c1)==true){
a.add(c1);
}
}
}
if (m_test){
System.out.println("AIEasy.getAvailableMoves- end");
}
return a;
}
|
b94712fb-7915-4eb6-b8dd-dbdb7c8fe08f
| 7
|
public T read (Kryo kryo, Input input, Class<T> type) {
T object = kryo.newInstance(type);
kryo.reference(object);
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
try {
if (TRACE) trace("kryo", "Read property: " + property + " (" + object.getClass() + ")");
Object value;
Serializer serializer = property.serializer;
if (serializer != null)
value = kryo.readObjectOrNull(input, property.setMethodType, serializer);
else
value = kryo.readClassAndObject(input);
property.set(object, value);
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing setter method: " + property + " (" + object.getClass().getName() + ")", ex);
} catch (InvocationTargetException ex) {
throw new KryoException("Error invoking setter method: " + property + " (" + object.getClass().getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(property + " (" + object.getClass().getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(property + " (" + object.getClass().getName() + ")");
throw ex;
}
}
return object;
}
|
a3a52fcd-a67e-4d32-8f21-4c1cec64007d
| 8
|
private Cell[][] getSeats(boolean priority) {
ArrayList<ArrayList<Cell>> seats = new ArrayList<>();
for (Cell[] row : this.planeSeats) {
ArrayList<Cell> rowSeats = new ArrayList<>();
for (Cell cell : row) {
if (priority && cell.getCellType() == CellType.PRIORITY_SEAT
|| !priority && cell.getCellType() == CellType.SEAT) {
rowSeats.add(cell);
}
}
if (!rowSeats.isEmpty()) {
seats.add(rowSeats);
}
}
Cell[][] array = new Cell[seats.size()][];
for (int i = 0; i < seats.size(); i++) {
ArrayList<Cell> row = seats.get(i);
array[i] = row.toArray(new Cell[row.size()]);
}
return array;
}
|
50141f6d-8e17-4010-95c1-8b47f8d09c00
| 7
|
synchronized boolean resetMessageQueue(String statusList) {
boolean isRemove = (statusList.length() > 0 && statusList.charAt(0) == '-');
boolean isAdd = (statusList.length() > 0 && statusList.charAt(0) == '+');
String oldList = this.statusList;
if (isRemove) {
this.statusList = viewer.simpleReplace(oldList, statusList.substring(1, statusList.length()), "");
messageQueue = new Hashtable();
statusPtr = 0;
return true;
}
statusList = viewer.simpleReplace(statusList, "+", "");
if (oldList.equals(statusList) || isAdd && oldList.indexOf(statusList) >= 0)
return false;
if (!isAdd) {
messageQueue = new Hashtable();
statusPtr = 0;
this.statusList = "";
}
this.statusList += statusList;
Logger.debug(oldList + "\nmessageQueue = " + this.statusList);
return true;
}
|
7b91b9ba-f7d7-4e0b-8f9f-f5107533606c
| 1
|
@SuppressWarnings("unchecked")
public void saveError(HttpServletRequest request, String error) {
List errors = (List) request.getSession().getAttribute(ERRORS_KEY);
if (errors == null) {
errors = new ArrayList();
}
errors.add(error);
request.getSession().setAttribute(ERRORS_KEY, errors);
}
|
0a500b78-99e8-4e5e-a352-3fdef3f91ae9
| 2
|
private static void showRoundBorder(String worldName, BorderData border)
{
if (squareBorders.containsKey(worldName))
removeBorder(worldName);
CircleMarker marker = roundBorders.get(worldName);
if (marker == null)
{
marker = markSet.createCircleMarker("worldborder_"+worldName, Config.DynmapMessage(), false, worldName, border.getX(), 64.0, border.getZ(), border.getRadiusX(), border.getRadiusZ(), true);
marker.setLineStyle(lineWeight, lineOpacity, lineColor);
marker.setFillStyle(0.0, 0x000000);
roundBorders.put(worldName, marker);
}
else
{
marker.setCenter(worldName, border.getX(), 64.0, border.getZ());
marker.setRadius(border.getRadiusX(), border.getRadiusZ());
}
}
|
742fc505-604b-459f-8bd7-39b9afbf5b84
| 1
|
static int mcCarthy91(int n){
if(n > 100){
System.out.println(n);
return n-10;
} else {
System.out.println(n);
return mcCarthy91(mcCarthy91(n+11));
}
}
|
6f726fbc-e829-480f-b34a-826f541569cb
| 7
|
public byte[] encrypt(byte[] text, String key){
// System.out.println("encrypting");
byte[] textEncrypted = null;
try{
//keygenerator.init(bits); // 192 and bits bits may not be available
byte[] keyPadded = new byte[bits / 8];
for(int i = 0; i < bits / 8 && i < key.length(); i++){
keyPadded[i] = (byte)key.charAt(i);
}
/* Generate the secret key specs. */
SecretKeySpec mykey = new SecretKeySpec(keyPadded, "AES");
// Create the cipher
desCipher = Cipher.getInstance("AES");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, mykey);
// Encrypt the text
textEncrypted = desCipher.doFinal(text);
return (textEncrypted);
}catch(IllegalBlockSizeException e){
e.printStackTrace();
}catch(BadPaddingException e){
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
System.out.println("error in desCipher.init");
//}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println();
return textEncrypted;
}
|
d2c62433-2ea7-42d1-b288-b6777a477544
| 2
|
private void connectBackupServer() {
try {
if(secondary)
backupServer = (ServerInterface) Naming.lookup("rmi://127.0.0.1:9090/server1");
else
backupServer = (ServerInterface) Naming.lookup("rmi://127.0.0.2:9090/server2");
backupServer.ping();
} catch(Exception ex) {
resetBackupServer();
}
}
|
e18502d1-6f96-4a8f-b5b7-59730b71fcbc
| 7
|
public Object readBeanConnection(Element node) throws Exception {
Object result;
Vector children;
Element child;
String name;
int i;
int source;
int target;
int sourcePos;
int targetPos;
String event;
boolean hidden;
// for debugging only
if (DEBUG)
trace(new Throwable(), node.getAttribute(ATT_NAME));
m_CurrentNode = node;
result = null;
children = XMLDocument.getChildTags(node);
source = 0;
target = 0;
event = "";
hidden = false;
for (i = 0; i < children.size(); i++) {
child = (Element) children.get(i);
name = child.getAttribute(ATT_NAME);
if (name.equals(VAL_SOURCEID))
source = readIntFromXML(child);
else if (name.equals(VAL_TARGETID))
target = readIntFromXML(child);
else if (name.equals(VAL_EVENTNAME))
event = (String) invokeReadFromXML(child);
else if (name.equals(VAL_HIDDEN))
hidden = readBooleanFromXML(child);
else
System.out.println("WARNING: '" + name
+ "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!");
}
// get position of id
sourcePos = m_BeanInstancesID.indexOf(new Integer(source));
targetPos = m_BeanInstancesID.indexOf(new Integer(target));
// do we currently ignore the connections?
// Note: necessary because of the MetaBeans
if (m_IgnoreBeanConnections) {
addBeanConnectionRelation(m_CurrentMetaBean, sourcePos + "," + targetPos + "," + event + "," + hidden);
return result;
}
// generate it normally
result = createBeanConnection(sourcePos, targetPos, event, hidden);
return result;
}
|
78eeeccc-1c4d-4c4c-bc28-5f9f47d510e5
| 8
|
private static void addConstructedProblemReports(
Model cm,
List<ConstraintViolation> results,
Model model,
Resource atClass,
Resource matchRoot,
String label,
Resource source, SPINModuleRegistry registry) {
StmtIterator it = cm.listStatements(null, RDF.type, SPIN.ConstraintViolation);
while(it.hasNext()) {
Statement s = it.nextStatement();
Resource vio = s.getSubject();
Resource root = null;
Statement rootS = vio.getProperty(SPIN.violationRoot);
if(rootS != null && rootS.getObject().isResource()) {
root = (Resource)rootS.getResource().inModel(model);
}
if(matchRoot == null || matchRoot.equals(root)) {
Statement labelS = vio.getProperty(RDFS.label);
if(labelS != null && labelS.getObject().isLiteral()) {
label = labelS.getString();
}
else if(label == null) {
label = "SPIN constraint at " + SPINLabels.get().getLabel(atClass);
}
List<SimplePropertyPath> paths = getViolationPaths(model, vio, root);
List<TemplateCall> fixes = getFixes(cm, model, vio, registry);
results.add(createConstraintViolation(paths, fixes, root, label, source));
}
}
}
|
4baf9554-9e0e-43bf-8747-2e4a873d313a
| 8
|
int getLineWidth() {
int lineWidth = 0;
if (_endnoteMode && paragraphOn) {
lineWidth = endTextWidth - endParInd - endInd;
} else if (_endnoteMode && !paragraphOn) {
lineWidth = endTextWidth - endInd;
} else if (!_endnoteMode && paragraphOn) {
lineWidth = textWidth - parIndent - indent;
} else if (!_endnoteMode && !paragraphOn) {
lineWidth = textWidth - indent;
}
return lineWidth;
}
|
7c66731d-b71f-49b4-8b51-3470ca0be080
| 2
|
public boolean equals(Object o){
if(o == this || o == mKey) return true;
return mKey.equals(o);
}
|
ed0877b3-144c-48e4-ae46-a24f401b2ac9
| 9
|
public void rajayta(int x, int y) {
if(this.panoksia > 0) {
this.panoksia--;
} else {
return;
}
int vaikutusalue = this.rajahdysainetta / 33;
int rajahdysalue = this.rajahdysainetta / 100;
for (Ruutu ruutu : this.kentta.getRuudut()) {
if(itseisarvo(ruutu.getX()-x) <= vaikutusalue && itseisarvo(ruutu.getY()-y) <= vaikutusalue) {
ruutu.avaa();
}
if(itseisarvo(ruutu.getX()-x) <= rajahdysalue && itseisarvo(ruutu.getY()-y) <= rajahdysalue) {
ruutu.rajayta();
} else if(itseisarvo(ruutu.getX()-x) <= vaikutusalue-1 && itseisarvo(ruutu.getY()-y) <= vaikutusalue-1) {
if(this.random.nextInt(100)<25) { //25% mahdollisuus läheisen ruudun räjähtämiseen
ruutu.rajayta();
}
}
}
}
|
fe1ea1c1-3071-408b-8a7e-2ed4d23e13fe
| 8
|
public synchronized boolean hasMoreSteps()
{
if(worker == null || excepted || !worker.isAlive() ) return false;
try
{
while (!halted) this.wait();
// This is a difficult piece of code.
// We halt if there is an exception, this is the easy part.
// We also halt if the stack has no more steps AND there is not previous stack.
// There can be multiple stacks if there is a nesting, i.e. a command invokes eval itself.
// In the nested case, the debugger can go on stepping, no problem.
return stack != null && !excepted && (stack.hasMoreSteps() || stack.getPrevStack() != null);
}
catch (InterruptedException e)
{
halted = true;
return false;
}
}
|
0fbde7bc-41bd-481b-8396-83f5ca547b64
| 3
|
public int get_bits(int number_of_bits)
{
int returnvalue = 0;
int sum = bitindex + number_of_bits;
// E.B
// There is a problem here, wordpointer could be -1 ?!
if (wordpointer < 0) wordpointer = 0;
// E.B : End.
if (sum <= 32)
{
// all bits contained in *wordpointer
returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits];
// returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits];
if ((bitindex += number_of_bits) == 32)
{
bitindex = 0;
wordpointer++; // added by me!
}
return returnvalue;
}
// E.B : Check that ?
//((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
//wordpointer++; // Added by me!
//((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
int Right = (framebuffer[wordpointer] & 0x0000FFFF);
wordpointer++;
int Left = (framebuffer[wordpointer] & 0xFFFF0000);
returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16)& 0x0000FFFF);
returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 - bitindex))
returnvalue &= bitmask[number_of_bits];
bitindex = sum - 32;
return returnvalue;
}
|
5e33476a-9467-4e0b-97b6-346a55f856d7
| 1
|
public static final String wasWere(int amount) {
return amount == 1 ? WAS : WERE;
}
|
7fe29da8-9f9b-4edd-a8ec-6dabafc2bcf9
| 8
|
@Override
public boolean equals(Object o) {
if(o instanceof SimpleHashSet) {
if((this.size() == ((SimpleHashSet<?>)o).size())) {
int count = 0;
Iterator<?> it = ((SimpleHashSet<?>)o).iterator();
while(it.hasNext()) {
if(this.contains(it.next())) {
count++;
}
}
if(count == this.size()) {
return true;
}
}
}
return false;
}
|
e96e22d2-6d46-4b35-ac1c-49e9a897f174
| 1
|
public static void handle(String[] tokens, Client client) {
if (tokens[1].equals("login")) {
client.send(PacketCreator
.openURL(
"http://www2.knuddels.de/dprint/dprint.pl?jig=4&domain=Knuddels.de",
"_blank"));
}
}
|
9002bf68-ca33-455e-8c6d-a02577fe5870
| 9
|
@Override
public void run(MappedLEDPhidget ledPhidget) {
snake.clear();
// all off
for (int i = 0; i < 64; i ++) {
ledPhidget.setBrightness(i, 0);
}
for (int i = 0; i < 20; i+= 2) {
addLight(ledPhidget, i);
}
for (int i = 19; i >= 1; i-= 2) {
addLight(ledPhidget, i);
}
for (int i = 20; i < 40; i+= 2) {
addLight(ledPhidget, i);
}
for (int i = 39; i >= 21; i-= 2) {
addLight(ledPhidget, i);
}
for (int i = 40; i < 60; i+= 2) {
addLight(ledPhidget, i);
}
for (int i = 59; i >= 41; i-= 2) {
addLight(ledPhidget, i);
}
while (snake.size() != 0) {
int tail = snake.remove(snake.size()-1);
ledPhidget.setBrightness(tail, 0);
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
6d19b87b-2d7a-464a-9997-440e1ce74eaf
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EssensAuswahl other = (EssensAuswahl) obj;
if (auswahl == null) {
if (other.auswahl != null)
return false;
} else if (!auswahl.equals(other.auswahl))
return false;
if (person == null) {
if (other.person != null)
return false;
} else if (!person.equals(other.person))
return false;
return true;
}
|
9132c1de-6e90-4abc-8d94-8f82d6be1698
| 3
|
public static ArrayList<TestQuestionBean> updateTestQuestion2(String testid){
ArrayList<TestQuestionBean> a=new ArrayList<TestQuestionBean>();
try{
con=DBConnection.getConnection();
st=con.createStatement();
ResultSet rs=st.executeQuery("select category from test where testid='"+testid+"'");
String category=null;
if(rs.next()){
category=rs.getString(1);
}
ResultSet rs1=st.executeQuery("select questionid,question from question where category='"+category+"'");
while(rs1.next()){
TestQuestionBean t=new TestQuestionBean();
t.setTestid(testid);
t.setQuestionid(rs1.getString(1));
t.setQuestionName(rs1.getString(2));
System.out.println(rs1.getString(1));
a.add(t);
}
}catch(Exception e){
e.printStackTrace();
}
return a;
}
|
5fe61af1-742e-4854-96e0-a76ab72d0633
| 2
|
public void startSimulation() {
if (!isActive) {
isActive = true;
// If physics thread is not null it never actually stopped.
if (physicsThread == null) {
physicsThread = new Thread(physicsLoop);
physicsThread.start();
}
}
}
|
e63a0909-8af1-499b-9e32-811d5b59b4e6
| 5
|
public void hello() {
String str;
System.out.println();
System.out.println("***************************************************************");
System.out.println("* *");
System.out.println("* TIC TAC *");
System.out.println("* *");
System.out.println("* ALPHA *");
System.out.println("* *");
System.out.println("***************************************************************");
System.out.println();
System.out.println("Choose the type of the game:");
System.out.println();
System.out.println("1. Player VS Player");
System.out.println("2. Player VS Computer");
System.out.println();
Scanner input= new Scanner(System.in);
do {
str = input.next();
if (str.length() == 1) {
char []var = str.toCharArray();
typeOfGame = var[0];
if (!((var[0] == '1' ) || (var[0] == '2'))) {
wrongInputMessage();
}
} else {
wrongInputMessage();
}
} while(!(typeOfGame == '1' || typeOfGame == '2'));
}
|
32a73fc3-7188-4c76-98ce-91f25e384fa4
| 5
|
public void initialise(World world) throws PatternFormatException
{
String[] cellParts = cells.split(" ");
for (int i=0;i<cellParts.length;i++)
{
char[] currCells = cellParts[i].toCharArray();
for (int j=0;j<currCells.length;j++)
{
if (currCells[j] != '1' && currCells[j] != '0') throw new PatternFormatException("Error: incorrect format of cell description");
if (currCells[j] == '1') world.setCell(j+startCol,i+startRow,true);
}
}
}
|
ebc58b8a-48e2-4bdd-932f-61c33b4afc29
| 8
|
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String action = request.getParameter("act");
if(action != null) {
try {
RequestContext context = new RequestContext(request);
if(context.isLogged()) {
int compId = Utilities.chooseParam(request, "id", 0);
String name = Utilities.chooseParam(request, "companyname", "");
switch(action) {
case "create":
createCompany(name, response, context);
break;
case "rename":
renameCompany(compId, name, response, context);
break;
case "close":
closeCompany(compId, response, context);
break;
case "buy":
buyCompany(compId, response, context);
break;
case "sell":
long cost = Utilities.chooseParam(request, "cost", 0L);
setForSale(compId, cost, response, context);
break;
default:
response.sendRedirect("teams.jsp");
}
} else {
response.sendRedirect("login.jsp");
}
} catch(SQLException e) {
log.error("SQLException caught in Company servlet.", e);
response.sendRedirect("error.jsp?err=dberr");
}
} else {
response.sendRedirect("teams.jsp");
}
}
|
fc607f9d-4e95-428d-a39f-6c3362676ec5
| 7
|
public static void printRelationship(String file, String [] relations) {
BufferedWriter output;
FileWriter streamFiles;
try {
streamFiles = new FileWriter(file, true);
output = new BufferedWriter(streamFiles);
if(ReadFromFile.getNumberFromFile(file) < 2) {
for(int i = 0; i < relations.length; i++) {
if(i!= relations.length-1)
output.write("\\" + relations[i] + "\\,");
else
output.write("\\" + relations[i] + "\\");
}
output.close();
}
else {
for(int i = 0; i < relations.length; i++) {
if(i == 0)
output.write("\n\\" + relations[i] + "\\,");
else if(i != relations.length - 1)
output.write("\\" + relations[i] + "\\,");
else
output.write("\\" + relations[i] + "\\");
}
output.close();
}
}
catch(IOException i) {
System.out.println("ERROR: File Not Found");
}
}
|
9a664504-1c9f-4693-9dda-5794f6f840a3
| 3
|
private boolean isNotPassable(Map map, Snake[] snakes, int x, int y) {
if (!map.passable(x, y)) {
return true;
}
for (Snake s : snakes) {
if (s.cellAt(x, y) != -1) {
return true;
}
}
return false;
}
|
9406b392-ec37-46ab-90cf-2d5522ea1043
| 2
|
public String getQuote()
{
String finalString = "";
finalString += this.companyName;
finalString += " (";
finalString += this.symbol;
finalString += ")\nPrice: ";
finalString += this.lastPrice;
finalString += " hi: ";
finalString += this.highPrice;
finalString += " lo: ";
finalString += this.lowPrice;
finalString += " vol: ";
finalString += this.dayVolume;
finalString += "\nAsk: ";
if (!sellOrders.isEmpty())
{
TradeOrder order = sellOrders.peek();
finalString += order.getPrice();
finalString += " size: ";
finalString += order.getShares();
finalString += " Bid: ";
} else
{
finalString += "none Bid: ";
}
if (!buyOrders.isEmpty())
{
TradeOrder order = buyOrders.peek();
finalString += order.getPrice();
finalString += " size: ";
finalString += order.getShares();
} else
{
finalString += "none";
}
return finalString;
}
|
4a86e574-4319-458b-8e2f-653439cd0586
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Position other = (Position) obj;
if (xPos == null) {
if (other.xPos != null)
return false;
} else if (!xPos.equals(other.xPos))
return false;
if (yPos == null) {
if (other.yPos != null)
return false;
} else if (!yPos.equals(other.yPos))
return false;
return true;
}
|
f56d881d-5698-4f16-a469-611b1a58135f
| 1
|
public int chooseTurnHandler() {
if (!homing) {
return chooseTurnForGoal();
} else {
return chooseTurnReturn();
}
}
|
7d107de4-6346-4cc9-9973-6e5d84176ca1
| 2
|
private void drawLayer(Graphics g, CPLayer layer, boolean selected) {
Dimension d = getSize();
if (selected) {
g.setColor(new Color(0xB0B0C0));
} else {
g.setColor(Color.white);
}
g.fillRect(0, 0, d.width, layerH);
g.setColor(Color.black);
g.drawLine(0, 0, d.width, 0);
g.drawLine(eyeW, 0, eyeW, layerH);
g.drawString(layer.name, eyeW + 6, 12);
g.drawLine(eyeW + 6, layerH / 2, d.width - 6, layerH / 2);
g.drawString(modeNames[layer.blendMode] + ": " + layer.alpha + "%", eyeW + 6, 27);
if (layer.visible) {
g.fillOval(eyeW / 2 - 5, layerH / 2 - 5, 10, 10);
} else {
g.drawOval(eyeW / 2 - 5, layerH / 2 - 5, 10, 10);
}
}
|
b396c3da-6a1a-4d92-af92-b0808c92bb73
| 0
|
@Override
public void prepareSpecificMenu() {
menuPanel.setLayout(new GridLayout(100, 1, 0, 30));
JButton start = new JButton("Continue");
start.setActionCommand(CMD_CONTINUE);
start.addActionListener(this);
menuPanel.add(start);
}
|
30a189a1-3d03-4549-a857-ecbd959fd2ff
| 0
|
@Test
public void testGetCirclePoints() {
Set<Point> r7Points = CircleAccumulator.getCirclePoints(7, 0, 0);
Set<Point> r8Points = CircleAccumulator.getCirclePoints(8, 0, 0);
assertTrue("getCirclePoints with r = 7 misses (5,5): " + r7Points, r7Points.contains(new Point(5, 5)));
assertFalse("getCirclePoints with r = 8 has (6,6): " + r8Points, r8Points.contains(new Point(6, 6)));
}
|
447a5cec-6a24-4d75-a217-b1207f0eeff5
| 2
|
@Test
public void test6(){
Random r = new Random();
QuickSort qs = new QuickSort();
ArrayList<Integer> test = new ArrayList<Integer>();
int[] answer = new int[1000000];
int x = 0;
for(int i=0; i<1000000; i++)
{
x = r.nextInt(1000000);
test.add(x);
answer[i] = x;
}
test = qs.quickSort(test);
Arrays.sort(answer);
ArrayList<Integer> answer1 = new ArrayList<Integer>();
for(int i =0; i< answer.length; i++)
{
answer1.add(answer[i]);
}
assertEquals(test, answer1);
}
|
7b59a60e-4d12-4078-8891-ab2fb2368664
| 6
|
public void computeDistanceDensities(double max_dist) {
int bin_num=100;
int testedSet=10000;
double bin_size=max_dist/(double)bin_num;
int[] dd=null;
System.out.println("Computing distance densities...");
DatasetObject[] objects=new DatasetObject[testedSet];
dd=new int[bin_num];
for(int i=0;i<bin_num;i++)
dd[i]=0;
for (int i=0; i<testedSet;i++){
objects[i]=getObject(i);
}
for (int i=0; i<testedSet;i++)
{
for(int j=0;j<testedSet;j++)
{
double dist=distance(objects[i],objects[j]);
// System.out.println(dist);
int bin;
if (dist >= max_dist){
bin=bin_num-1;
} else
bin=(int)(dist/bin_size);
// dd[i][dist/bin_size]=dd[i][dist/bin_size]+1;
dd[bin]=dd[bin]+1;
}
//System.out.println(i);
}
double sum=0;
for(int i=0;i<bin_num;i++){
double dist=(i+1)*bin_size;
double density=dd[i]/(double)(testedSet*testedSet);
sum+=density;
System.out.println(dist+"\t"+density);
}
System.out.println(sum);
}
|
a7ac283f-ef28-4fce-b66d-07f68cbfe478
| 2
|
private String getConfigString(String path) {
FileConfiguration config = this.getConfig();
String s = config.getString(path);
if (s != null) {
s = s.trim();
if (s.length() == 0)
s = null;
}
return s;
}
|
25ec8d8f-a8dd-46dd-b93c-a99d84e48a77
| 5
|
public boolean notifyDataAvailable(AvailableData availableData, boolean lastData) {
List<Patient> patients = availableData.getPatients().getPatient();
for(int i = 0; i < patients.size(); i++){
Patient patient = patients.get(i);
System.out.println(patient.getName());
List<Study> studies = patient.getStudies().getStudy();
for(int j = 0; j < studies.size(); j++){
Study study = studies.get(j);
System.out.println(" " + study.getStudyUID());
List<Series> listOfSeries = study.getSeries().getSeries();
for(int k = 0; k < listOfSeries.size(); k++){
Series series = listOfSeries.get(k);
System.out.println(" " + series.getSeriesUID());
}
for(int k = 0; k < listOfSeries.size(); k++){
Series series = listOfSeries.get(k);
ArrayOfObjectDescriptor descriptors = series.getObjectDescriptors();
List<ObjectDescriptor> listDescriptors = descriptors.getObjectDescriptor();
for(int m =0; m < listDescriptors.size(); m++){
ObjectDescriptor desc = listDescriptors.get(m);
System.out.println(desc.getUuid().getUuid());
}
}
}
}
System.out.println("Last item? " + lastData);
System.out.println("Listener: " + listener == null);
//TODO make use of lastData
listener.notifyDataAvailable(availableData, lastData);
return true;
}
|
ffe46be6-c909-4fe1-a0f7-ff9e04b08983
| 3
|
public float[] toRGB(float comp[]) {
if (comp.length==3) {
// compute r', g' and b' by raising the given values to the
// correct gamma
float a = (float)Math.pow(comp[0], gamma[0]);
float b = (float)Math.pow(comp[1], gamma[1]);
float c = (float)Math.pow(comp[2], gamma[2]);
// now multiply by the matrix to get X, Y and Z values
float[] xyz = new float[] {
matrix[0]*a + matrix[3]*b + matrix[6]*c,
matrix[1]*a + matrix[4]*b + matrix[7]*c,
matrix[2]*a + matrix[5]*b + matrix[8]*c};
// now scale the xyz values
xyz = matrixMult(xyz, scale, 3);
// convert to RGB
float[] rgb = ciexyzToSRGB(xyz);
// cheat -- scale based on max
for (int i = 0; i < rgb.length; i++) {
rgb[i] = FunctionType0.interpolate(rgb[i], 0, max[i], 0, 1);
// sometimes we get off a little bit due to precision loss
if (rgb[i] > 1.0) {
rgb[i] = 1.0f;
}
}
return rgb;
} else {
return black;
}
}
|
f23fb36e-8a2b-4a4f-9dc6-c5ea52ce0001
| 0
|
public void init() {
System.out.println("SHS Servlet: init()");
}
|
82590aef-5ad9-4c6c-8397-0dadd6e497fd
| 9
|
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DefaultHighLowDataset)) {
return false;
}
DefaultHighLowDataset that = (DefaultHighLowDataset) obj;
if (!this.seriesKey.equals(that.seriesKey)) {
return false;
}
if (!Arrays.equals(this.date, that.date)) {
return false;
}
if (!Arrays.equals(this.open, that.open)) {
return false;
}
if (!Arrays.equals(this.high, that.high)) {
return false;
}
if (!Arrays.equals(this.low, that.low)) {
return false;
}
if (!Arrays.equals(this.close, that.close)) {
return false;
}
if (!Arrays.equals(this.volume, that.volume)) {
return false;
}
return true;
}
|
86acd18c-bef5-4846-bf77-68a0b68650b6
| 0
|
@Override
public void fromMessage(Message message) throws JMSException {
this.setId(message.getStringProperty(Strings.ID));
}
|
40b912eb-a1c7-4b6f-a97c-cd41f075ffdb
| 0
|
public void pointerDragged(int x, int y)
{
addPoint(x, y);
}
|
2f850e94-b493-47c2-bc40-16d5a7bbc253
| 0
|
public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
|
2e67ad3e-d863-41fe-a651-7050b3810e8d
| 1
|
public void setWindowPosition(Position position) {
if (position.equals(Position.NONE)) {
IllegalArgumentException iae = new IllegalArgumentException("Position none is not allowed!");
Main.handleUnhandableProblem(iae);
}
this.window_Position = position;
somethingChanged();
}
|
c2c9920c-44b6-404e-adfe-b7102bcf83cf
| 3
|
public void setIdentifier(PIdentifier node)
{
if(this._identifier_ != null)
{
this._identifier_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._identifier_ = node;
}
|
59026ca7-69be-44ea-84e1-6309edb017a6
| 7
|
private boolean containsCharacters(String n) {
boolean isCharacter = false;
String temp;
for (int i = 0; i < n.length(); i++) {
temp = n.substring(i, i + 1);
// checks to see if all characters are digits
if (!Character.isDigit(n.charAt(i)))
isCharacter = true;
// ensures than only numbers 1-5 are inputted
if (temp.equals("6") || temp.equals("7") || temp.equals("8")
|| temp.equals("9") || temp.equals("0"))
isCharacter = true;
}// end for loop
return isCharacter;
}
|
d6a2cc5e-759c-4582-8364-2612e143ead7
| 3
|
public void tampilkanDaftar(){
if (!daftarPembeli.isVisible()){
DaftarPembeli.listPembeli = pembeli.bacaDaftar();
daftarPembeli = new DaftarPembeli(null, true);
daftarPembeli.setVisible(true);
if (!DaftarPembeli.no_beliDipilih.equals("")) {
if (pembeli.baca(DaftarPembeli.no_beliDipilih)){
FormUtama.formPembeli.setNoPembelian(pembeli.getNo_beli());
FormUtama.formPembeli.setNama(pembeli.getNama());
FormUtama.formPembeli.setAlamat(pembeli.getAlamat());
FormUtama.formPembeli.setTelepon(pembeli.getTlp());
}
}
}
}
|
2a835c01-485a-46a5-bff2-2c7ac2e5ad00
| 4
|
private void fruitDistToHtml(StringBuffer buf) {
// buf.append(" <div style=\"width: 800px; float: left;\">\n");
buf.append("<div>");
buf.append("<div style=\"width: 500px; height: 40px; text-align: center;font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + "Init and current distribution" + "</div>\n");
// empty up left square
buf.append(" <div style=\"width: 34px; height: 40px; float:left;\"></div>\n");
// color squares
for (int c = 0; c < FRUIT_NAMES.length; c++) {
String color = FRUIT_COLORS[c];
String cname = Character.toString((char)(65+c));
buf.append("<div style=\"width: 34px; height: 40px; font-size:20px; font-weight:bold;font-family:'Comic Sans MS', cursive, sans-serif;text-align:center;float:left; border: 1px solid black; background-color: " + color + "\">" + cname + "</div>\n");
}
buf.append(" <div style=\"clear:both;\"></div>\n");
// Init I
buf.append(" <div style=\"width: 34px; height: 40px; float:left; border: 1px solid black; text-align: center;");
buf.append("\n");
buf.append(" font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">I</div>\n");
// initial distribution
buf.append(" <div style=\"width: 432px; height: 40px; float: left; border: 1px solid black;\">\n");
for (int r = 0 ; r != FRUIT_NAMES.length ; ++r) {
String s = Integer.toString(fruitDist[r]);
buf.append(" <div style=\"width: 36px; height: 40px; float:left; text-align: center; font-size: 20px;\n");
buf.append(" font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + s + "</div>\n");
}
buf.append(" </div>\n");
buf.append(" <div style=\"clear:both;\"></div>\n");
// Current C
buf.append(" <div style=\"width: 34px; height: 40px; float:left; border: 1px solid black; text-align: center;");
buf.append("\n");
buf.append(" font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">C</div>\n");
// current distribution
buf.append(" <div style=\"width: 432px; height: 40px; float: left; border: 1px solid black;\">\n");
for (int r = 0 ; r != FRUIT_NAMES.length ; ++r) {
String s = "-";
if (currentFruits != null)
s = Integer.toString(currentFruits[r]);
buf.append(" <div style=\"width: 36px; height: 40px; float:left; text-align: center; font-size: 20px;\n");
buf.append(" font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + s + "</div>\n");
}
buf.append(" </div>\n");
buf.append(" <div style=\"clear:both;\"></div>\n");
buf.append("</div>");
}
|
b53b84c5-4983-4892-930d-e7e644084ea4
| 2
|
private TVC[] copySetWithout(TVC withoutIt, TVC[] connections) throws CloneNotSupportedException {
TVC[] r = new TVC[connections.length - 1];
int idx = 0;
for (TVC c : connections) {
if (c != withoutIt) {
r[idx++] = c;
}
}
return r;
}
|
6eeb5c38-6de9-4d26-a392-09051c0a5db3
| 7
|
public static void main(String args[]) throws IOException, ClassNotFoundException {
// arguments: input output
if (args.length != 2)
System.out.println("Usage: java sitg.tagging.PosTagger input output");
long start = System.currentTimeMillis();
System.out.println("Tagging TXT files...");
// Initialize the tagger
MaxentTagger tagger = new MaxentTagger("taggers/french.tagger");
// French POS tags
TTags ttags = tagger.getTags();
System.out.println("French POS tags: " + ttags);
// input folder
File input = new File(args[0]);
// output folder
File output = new File(args[1]);
if (!output.exists())
output.mkdir();
for (File file : input.listFiles()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
DocumentPreprocessor dp = new DocumentPreprocessor(reader);
dp.setTokenizerFactory(PTBTokenizerFactory.newWordTokenizerFactory("americanize=false,unicodeQuotes=true,unicodeEllipsis=true,ptb3Escaping=false"));
String results = "";
for (List<HasWord> sentence : dp) {
List<TaggedWord> tSentence = tagger.tagSentence(sentence);
for (TaggedWord tWord: tSentence) {
//writer.write(tWord.toString() + " ");
String word = tWord.value();
String tag = tWord.tag();
/*
if (!tag.equals("V")) // remove verbs
writer.write(word + " ");
*/
/*
if (tag.equals("N")) // keep only nouns
writer.write(word + " ");
*/
if (tag.equals("N") || tag.equals("A")) // keep nouns and adjectives
results += word + " ";
}
}
//if (results.split(" ").length >= 5) { // keep documents with at least five words
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output+"/"+file.getName()), "UTF8"));
writer.write(results);
writer.close();
//}
reader.close();
}
System.out.println("All files are tagged with nouns and adjectives.");
long end = System.currentTimeMillis();
System.out.println("Execution time: " + (end-start)/1000 + " seconds");
}
|
912ceae6-baeb-492e-878a-97ae08463ee8
| 6
|
public static void main(String[] args) {
for (Object o: System.getProperties().keySet()) {
System.out.printf("%s:%s\n",o.toString(),System.getProperty((String)o));
}
try {
File folder = new File("files");
for (File file : folder.listFiles()) {
if (file.getAbsolutePath().endsWith(".arff")) {
System.out.println("-----------------");
System.out.println("Testing " + file);
try {
Data d = Reader.getDataFromFile(file);
Tree tree = ID3.decisionTreeLearning(d.getExamples(),
d.getAttributes(), d.getGoalAttribute(),
d.getattributeValues(), null);
int before = tree.hashCode();
String sBefore = tree.toString();
Pruning.Prune(tree, d);
int after = tree.hashCode();
String sAfter = tree.toString();
if (before != after) {
System.out.println("...was pruned");
System.out.println("Before:");
System.out.println(sBefore);
System.out.println("After:");
System.out.println(sAfter);
} else {
System.out.println("...was not pruned");
System.out.println("Before:");
System.out.println(sBefore);
}
} catch (IllegalArgumentException e) {
System.out.println("...could not parse");
}
} else {
System.out.println("ignored " + file);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
|
cc1e0e0a-1fde-4b09-88a9-ccb53cd8fe7f
| 0
|
public ImperialSword(){
this.name = Constants.IMPERIAL_SWORD;
this.attackScore = 30;
this.attackSpeed = 20;
this.money = 4000;
}
|
7d98c8ae-f6d6-4939-a174-14604f390989
| 5
|
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (((Boolean) parent.getConfigu().getOpt(
Config.Option.PistonProtection)).booleanValue()) {
Block b = event.getBlock();
CBlock conBlock = parent.getCBlock(b.getLocation());
if (conBlock != null) {
event.setCancelled(true);
return;
}
if (event.isSticky()) {
Block block = b.getWorld().getBlockAt(
event.getRetractLocation());
if ((parent.isControlledBlock(block.getLocation(),
block.getType()))
&& (!parent.isUnprotectedMaterial(block.getType()))) {
event.setCancelled(true);
return;
}
}
}
}
|
29b4356c-a9f1-4507-b64b-7d44351dbde1
| 3
|
public Element removeElement(Point location) {
Element deleted = null;
for(Element element:elements) {
if(element.getLocation().equals(location)) {
deleted = element;
break;
}
}
if(deleted != null) {
bank.deposit(deleted.getType().getPrice());
elements.remove(deleted);
}
return deleted;
}
|
5ac22b3e-433c-4112-82b6-dc2144dc193e
| 7
|
public void move() {
Random generator = new Random();
int num1 = generator.nextInt(4);
if (num1 == 0) {
x -= 5;
y -= 5;
} else if (num1 == 1) {
x -= 5;
y += 5;
} else if (num1 == 2) {
x += 5;
y -= 5;
} else {
x += 5;
y += 5;
}
if (x >= 504) {
x = 504;
} else if (x <= 0) {
x = 0;
}
if (y >= 504) {
y = 504;
} else if (y <= 0) {
y = 0;
}
rec.setLocation(x, y);
}
|
8a5514b0-60cb-4242-acf4-4cd7fd5ea170
| 7
|
public void paint(Graphics2D g2, TreePane treePane, Justification justification, Rectangle2D bounds) {
Font oldFont = g2.getFont();
Paint oldPaint = g2.getPaint();
Stroke oldStroke = g2.getStroke();
if (getBackground() != null) {
g2.setPaint(getBackground());
g2.fill(bounds);
}
if (getBorderPaint() != null && getBorderStroke() != null) {
g2.setPaint(getBorderPaint());
g2.setStroke(getBorderStroke());
g2.draw(bounds);
}
g2.setFont(getFont());
// we don't need accuracy but a nice short number
final String label = Double.toString(scaleRange);
Rectangle2D rect = g2.getFontMetrics().getStringBounds(label, g2);
double x1, x2;
float xOffset;
switch (justification) {
case CENTER:
xOffset = (float) (bounds.getX() + (bounds.getWidth() - rect.getWidth()) / 2.0);
x1 = (bounds.getX() + (bounds.getWidth() - preferredWidth) / 2.0);
x2 = x1 + preferredWidth;
break;
case FLUSH:
case LEFT:
xOffset = (float) bounds.getX();
x1 = bounds.getX();
x2 = x1 + preferredWidth;
break;
case RIGHT:
xOffset = (float) (bounds.getX() + bounds.getWidth() - rect.getWidth());
x2 = bounds.getX() + bounds.getWidth();
x1 = x2 - preferredWidth;
break;
default:
throw new IllegalArgumentException("Unrecognized alignment enum option");
}
g2.setPaint(getForeground());
g2.setStroke(getScaleBarStroke());
g2.draw(new Line2D.Double(x1, bounds.getY() + topMargin, x2, bounds.getY() + topMargin));
g2.drawString(label, xOffset, yOffset + (float) bounds.getY());
g2.setFont(oldFont);
g2.setPaint(oldPaint);
g2.setStroke(oldStroke);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.