method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
eb5cf582-35a5-4b01-9f19-43393e9f3e60 | 2 | @Override
public void finalize( Connection connection, DefaultBox<?> source, DefaultBox<?> target ) {
AbstractConnection con = (AbstractConnection) connection;
con.setSourceItem( source );
con.setTargetItem( target );
} |
d3477c4a-455c-49ff-a2c5-c921e368e33a | 4 | public String getProperty(String property){
try {
r = new BufferedReader(new FileReader(config));
} catch (IOException e) {
}
String temp;
try {
while((temp = r.readLine()) != null){
if(temp.startsWith(property)){
return temp.replace(property + ": ", "");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
} |
883f3ff9-afdf-4cfe-acc8-b79874ddc248 | 4 | public String toString() {
String temp = "";
for (int y = rows-1; y > -1; y--) {
for (int x = 0; x < cols; x++) {
if (board[x][y].getState() == EMPTY) {
temp = temp + "-";
}
else if (board[x][y].getState() == PLAYER_ONE) {
temp = temp + "O";
}
else {
temp = temp + "X";
}
}
temp += "\n";
}
return temp;
} |
a8ae5762-9bbe-4240-94e3-76180a37b11e | 8 | public int calculateSelectedAttribute(TreeNode node) {
int selectedAttribute = -1;
double minRelativeEntropy = 999999;
for(int i : node.unProcessedAttributes) {
int total = node.Y.size();
int count[][] = new int[attributePossibleValues[i]][classValues];
for(int j = 0; j < total; j++) {
count[node.X.get(j).attributes[i]][node.Y.get(j)]++;
}
double relativeEntropy = 0;
for(int k = 0; k < attributePossibleValues[i]; k++) {
double localEntropy = 0;
int subTotal = 0;
for(int l = 0; l < classValues; l++) {
subTotal += count[k][l];
}
for(int l = 0; l < classValues; l++) {
if(subTotal != 0 && count[k][l] != 0) {
double probability = (double) count[k][l]/subTotal;
localEntropy += -probability*(Math.log(probability)/Math.log(2));
}
}
relativeEntropy += ((double)subTotal/total)*localEntropy;
}
if(minRelativeEntropy > relativeEntropy) {
minRelativeEntropy = relativeEntropy;
selectedAttribute = i;
}
}
return selectedAttribute;
} |
4f9b9cc4-d342-495f-b6ec-ed8eca11f8d9 | 2 | public void Set_edgeweight() {
int ni = t_partialedgeweight.length;
int nj = t_partialedgeweight[0].length;
for (int i = 0; i < ni; i++) {
for (int j = 0; j < nj; j++) {
Float temp = t_edgemultiplier.get(i);
t_edgeweight[i][j] = t_partialedgeweight[i][j] * temp;
}
}
} |
7dcf3bb1-a5ae-460f-868d-23445db08ba6 | 7 | protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
CalendarUtility cu = new CalendarUtility();
// Params
int weekNum;
try {
weekNum = Integer.parseInt(request.getParameter("week"));
} catch (Exception e) {
weekNum = cu.getCurrentWeekNum();
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// Weeks
String jsonThisWeek = String.format(jsonThisWeekFmt, weekNum,
weekNum == cu.getCurrentWeekNum() ? "true" : "false",
cu.weekToJson(2015, weekNum)); // TODO 2015
String jsonPrevWeek = String.format(jsonPagerFmt, weekNum == 1 ? 52
: weekNum - 1, weekNum == 1 ? "true" : "false");
String jsonNextWeek = String.format(jsonPagerFmt, weekNum + 1,
weekNum == cu.getCurrentWeekNum() ? "true" : "false");
// Projects & Data
String jsonProj = "";
String jsonData = "";
try (MySqlDAOFactory factory = new MySqlDAOFactory()) {
// Projects
List<Project> projects = factory.getProjectDAO().getProjectsByUser(
(int) request.getSession().getAttribute("userid"));
for (Project project : projects) // fill in activities lists
project.setActivities(factory.getActivityDAO().getActivitiesByProject(project.getId()));
jsonProj = TransferObject.listToJson(projects);
// Data
jsonData = TransferObject.listToJson(factory.getDataDAO()
.getUserData(
(int) request.getSession().getAttribute("userid"),
cu.dateToString(cu.getDate(2015, weekNum, 0)),
cu.dateToString(cu.getDate(2015, weekNum, 6))));
} catch (Exception e) {
throw new IOException(e);
}
// Writing the response
String json = String.format(jsonFmt, jsonThisWeek, jsonPrevWeek,
jsonNextWeek, jsonProj, jsonData);
out.write(json);
out.flush();
} |
4ed52ccd-c250-4715-a280-1760b443e646 | 4 | public static boolean isHavePositionCloseToCenter(Polygon polygon, Integer distance) {
if (distance == null)
return false;
for (Position position : polygon.getPositions()) {
Position centerPosition = MathService.positionOfCenter(polygon);
// if (position.getDistanceTo(centerPosition) < distance)
if (Math.abs(position.getX() - centerPosition.getX()) < distance*4 &&
Math.abs(position.getY() - centerPosition.getY()) < distance*4)
return true;
}
return false;
} |
a2dadd59-60f3-4680-b203-4fce251b0b69 | 4 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelButton) {
do_cancelButton_actionPerformed(e);
}
if (e.getSource() == btnVerificaComunicacao) {
try {
try {
do_button_actionPerformed(e);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} |
5059f61e-722a-445b-a13d-be2ba50eb3fe | 5 | public void edit(Usuario usuario) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
usuario = em.merge(usuario);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = usuario.getId();
if (findUsuario(id) == null) {
throw new NonexistentEntityException("The usuario with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} |
0bad1797-bb65-4dea-a6ad-4d57aa7a94e6 | 0 | public void setP(Product p) {
this.p = p;
this.prezzo = p.getPrice();
} |
939d0f0a-f014-4bfc-bdb6-aee92038f6a0 | 1 | public Tessellator( int fraction, float smooth, Color color, long seed )
{
this.fraction = fraction;
if ( fraction % 2 != 0 )
this.fraction--;
this.color = color;
this.smooth = smooth;
this.noise = NoiseHelper.generatePerlinNoise( fraction + 1, fraction + 1, 5, seed );
Mesh model = calculateTesselator();
addComponent( model );
} |
bf3de1ca-2612-4741-aa86-3458f8025bc1 | 4 | public static ArrayList<String> getDoors(int roomId) {
ArrayList<String> doors = new ArrayList<String>();
if(getNextRoomId("north", roomId) != 0) {
doors.add("North");
} if(getNextRoomId("east", roomId) != 0) {
doors.add("East");
} if(getNextRoomId("south", roomId) != 0) {
doors.add("South");
} if(getNextRoomId("west", roomId) != 0) {
doors.add("West");
}
return doors;
} |
a86ade2d-2b8d-4fee-b31c-b7fafa65b41a | 2 | public boolean deleteNode(Node node) {
if (this.next == null) {
return false;
} else if (this.next.data.equals(node.data)) {
this.next = next.next;
next.previous = this;
return true;
} else {
return this.next.deleteNode(node);
}
} |
5b234f4a-842d-4561-b1af-44de2cba345f | 7 | private Column getLengthColumn( Token token ) {
LengthColumn column = new LengthColumn();
if ( token.equals( FieldType.LONG ) ) {
column.setType( FieldType.LONG );
}
else if ( token.equals( FieldType.INTEGER ) ) {
column.setType( FieldType.INTEGER );
}
else if ( token.equals( FieldType.STRING ) ) {
column.setType( FieldType.STRING );
}
else if ( token.equals( FieldType.TIMESTAMP ) ) {
column.setType( FieldType.TIMESTAMP );
}
else {
throwException( "Unhandled Type. Expected DOUBLE, STRING, LONG, INTEGER, BLOB, CLOB, BOOLEAN, DATE or VSTRING.");
}
token = getNextToken();
if ( !token.isOpenParen() )
throwException( "Expecting open parenthesis" );
token = getNextToken();
if ( !token.isNumeric() )
throwException( "Numeric length expected." );
column.setColLen( token.getValue() );
token = getNextToken();
if ( !token.isCloseParen() )
throwException( "Expecting close paren." );
return column;
} |
5be247d6-2ecd-419a-9385-63f55b60b565 | 5 | private void loadFromFile() {
URI uri;
try {
uri = ResourceLoader.loadData(ResourceLoader.MASTER_FILENAME)
.toURI();
File masterFile = new File(uri);
BufferedReader bfr = new BufferedReader(new FileReader(masterFile));
String line = "";
int y = 0;
while ((line = bfr.readLine()) != null) {
for (int x = 0; x < World.W && x < line.length(); x++) {
if (line.charAt(x) == 'X') {
Location l = new Location(x, y);
locations.add(l);
}
}
y++;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR " + e.getMessage());
// for (StackTraceElement ste : e.getStackTrace()) {
// System.out.println(ste.toString());
// }
}
} |
c8b30539-571b-4ac1-b9a7-d344ebd85400 | 7 | public void parseInput(String fileName)
{
InputStream is = null;
BufferedReader br = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream("input.txt");
br = new BufferedReader(new InputStreamReader(is));
String line = null;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
parseLine(line,++lineNumber);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(is!=null) try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if(br!=null)
{
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
55181450-546d-41c6-bbc6-c0d95cb4b6e6 | 0 | public InputStream getData() {
return data;
} |
b1ae9595-3392-4fa0-a4c6-c43e52598c37 | 6 | @Override
public void keyTyped(KeyEvent ke) {
char c = ke.getKeyChar();
if (c == '\n' || c == '\r') {
lastKey = "enter";
} else if (c == '\t') {
lastKey = "tab";
} else if (c == '\b') {
lastKey = "backspace";
} else if (c == ' ') {
lastKey = "space";
} else if (c == 27) {
lastKey = "escape";
} else {
lastKey = "" + c;
}
} |
a89b3126-df52-441f-a088-7aec0083ef3c | 1 | public String getcalibParam() {
if (calibParam == null) {
throw new RuntimeException("missing calibParam name.");
}
return calibParam;
} |
1ec38d40-aff8-46e7-be41-451add92ba08 | 0 | public boolean isMember(InfoRequest infoRequest) throws MailChimpException {
String post = post("/lists/member-info", infoRequest, new Function<InfoRequest, String>() {
@Override public String apply(InfoRequest input) {
return gson.toJson(input);
}
});
System.out.println(post);
return gson.fromJson(post, InfoRequest.Response.class).getSuccessCount() == infoRequest.getEmailsCount();
} |
fc8d4ac6-f4aa-4c08-8a8b-d068cdc1b496 | 3 | @Override
public void deserialize(Buffer buf) {
fightId = buf.readInt();
if (fightId < 0)
throw new RuntimeException("Forbidden value on fightId = " + fightId + ", it doesn't respect the following condition : fightId < 0");
int limit = buf.readUShort();
alliesId = new int[limit];
for (int i = 0; i < limit; i++) {
alliesId[i] = buf.readInt();
}
duration = buf.readShort();
if (duration < 0)
throw new RuntimeException("Forbidden value on duration = " + duration + ", it doesn't respect the following condition : duration < 0");
} |
3bd10fb5-3b53-4f76-bc90-67997b5d3f55 | 9 | public List<GeneratedImage> buildCreatedFiles() throws IOException, InterruptedException {
boolean error = false;
final List<GeneratedImage> result = new ArrayList<GeneratedImage>();
for (File f : dir.listFiles()) {
if (error) {
continue;
}
if (f.isFile() == false) {
continue;
}
if (fileToProcess(f.getName()) == false) {
continue;
}
final FileWatcher watcher = modifieds.get(f);
if (watcher == null || watcher.hasChanged()) {
final SourceFileReader sourceFileReader = new SourceFileReader(new Defines(), f, option.getOutputDir(),
option.getConfig(), option.getCharset(), option.getFileFormatOption());
final Set<File> files = new HashSet<File>(sourceFileReader.getIncludedFiles());
files.add(f);
for (GeneratedImage g : sourceFileReader.getGeneratedImages()) {
result.add(g);
if (option.isFailfastOrFailfast2() && g.lineErrorRaw() != -1) {
error = true;
}
}
modifieds.put(f, new FileWatcher(files));
}
}
Collections.sort(result);
return Collections.unmodifiableList(result);
} |
e9a07625-64dc-481f-8b50-996b35b88300 | 0 | public void run() {
openDoor();
closeDoor();
startPower();
touchPower();
} |
a294dbdc-fc31-4775-af77-b9fec70940a4 | 0 | public void clearLabels(){
Labels.clear();
} |
86a82f4a-6eb5-4f92-a930-72446df187f2 | 2 | protected LinkedList[] createAdjacentLinkedListGraph(int n,int[][]edges){
LinkedList[] adjacentList=new LinkedList[n];
for(int i=0;i<n;++i) adjacentList[i]=new LinkedList();
for(int i=0;i<edges.length;++i){
adjacentList[edges[i][0]].add(edges[i][1]);
adjacentList[edges[i][1]].add(edges[i][0]);
}
return adjacentList;
} |
f7a1a42d-8f8c-4add-850c-0d2bdfebd6e0 | 6 | public boolean isMoveAllowed(int fromX, int fromY, int toX, int toY) {
if(toX >= 0 && toY >= 0 &&
toX < map.getWidth() && toY < map.getHeight()) {
final int code = map.get(1, toX, toY);
final int feature = FeatureCodes.getFeature(code);
return
feature == FeatureCodes.OPEN ||
feature == FeatureCodes.DOOR_OPEN ||
feature == FeatureCodes.DOOR_SHUT;
}
return false;
} |
19cb63cc-2187-4016-bbc0-54d8a8e1c15e | 6 | public Boardable[] entrances() {
if (entrances != null) return entrances ;
entrances = new Boardable[4] ;
final Tile o = origin() ;
final World world = o.world ;
final int h = size / 2, s = size ;
entrance = null ;
entrances[0] = world.tileAt(o.x + h, o.y + s) ;
entrances[1] = world.tileAt(o.x + s, o.y + h) ;
entrances[2] = world.tileAt(o.x + h, o.y - 1) ;
entrances[3] = world.tileAt(o.x - 1, o.y + h) ;
for (int i = 4 ; i-- > 0 ;) {
final Tile t = (Tile) entrances[i] ;
if (t == null) continue ;
if (t.owner() instanceof ShieldWall) {
entrances[i] = (ShieldWall) t.owner() ;
}
else if (type == TYPE_DOORS && ! t.blocked()) {
entrances[i] = entrance = t ;
}
else entrances[i] = null ;
}
return entrances ;
} |
2c1e097d-5b78-4f71-aecd-dae4fc57d703 | 6 | private void quicksort(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[pivot(numbers, low, high + 1)];
// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (numbers[i] < pivot) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (numbers[j] > pivot) {
j--;
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
// Recursion
printArray(numbers, low, j + 1);
printArray(numbers, j + 1, i);
printArray(numbers, i, high + 1);
System.out.println();
if (low < j)
quicksort(low, j);
if (i < high)
quicksort(i, high);
} |
748c5e35-3daa-48d1-aab6-54568211bac2 | 9 | public static String getMessageDigestForUrl(String fileUrl)
throws FileNotFoundException, IOException {
String messageDigest = null;
if (fileUrl != null && !fileUrl.isEmpty()) {
try {
InputStream fis = new URL(fileUrl).openStream();
MessageDigest md5 = MessageDigest.getInstance("SHA");
byte[] bytes = new byte[1024];
int read = 0;
while ((read = fis.read(bytes)) != -1) {
md5.update(bytes, 0, read);
}
byte[] digestBytes = md5.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < digestBytes.length; i++) {
sb.append(Integer.toString((digestBytes[i] & 0xff) + 0x100,
16).substring(1));
}
if (log.isDebugEnabled()) {
log.debug("For Url - Digest(in hex format):: "
+ sb.toString());
}
messageDigest = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException fne) {
fne.printStackTrace();
throw new FileNotFoundException(
"The SpecifiedImage is Not Found " + fne.getMessage());
} catch (MalformedURLException mfe) {
throw new MalformedURLException("The MalformedURLException is "
+ mfe.getMessage());
} catch (IOException ioe) {
ioe.printStackTrace();
throw new IOException("The IO Exception is "
+ ioe.getMessage());
}
} else {
messageDigest = "";
}
return messageDigest;
} |
6f2c04af-bea8-42dc-ae1e-a21fcc10f0ee | 4 | static void initFeature() {
Random rand = new Random();
for(int i = 0; i < DataInfo.userNumber; i++)
for(int j = 0; j < DataInfo.featureNumber; j++)
DataInfo.userFeature[i][j] = 0.01 * rand.nextDouble();
for(int i = 0; i < DataInfo.itemNumber; i++)
for(int j = 0; j < DataInfo.featureNumber; j++)
DataInfo.itemFeature[i][j] = 0.01 * rand.nextDouble();
} |
772e1e7e-773c-4fda-b0e1-7381b3f9d780 | 4 | @SuppressWarnings({ "rawtypes", "unchecked" })
private final static PrivilegeHolder getPrivilegeHolder(String name, ArrayList privilegeHolders) {
if(name == null || privilegeHolders == null) {
return null;
}
for(PrivilegeHolder privilegeHolder: (ArrayList<PrivilegeHolder>)privilegeHolders) {
if(privilegeHolder.getName().equalsIgnoreCase(name)) {
return privilegeHolder;
}
}
return null;
} |
5c89fae4-bedb-4561-8097-fd87a49fe074 | 3 | private static byte[] getPKCS1BytesFromPKCS8Bytes(byte[] bytes) {
/*
* DER format: http://en.wikipedia.org/wiki/Distinguished_Encoding_Rules
* PKCS#8: http://tools.ietf.org/html/rfc5208
*/
int bIndex = 0;
// Start with PrivateKeyInfo::=SEQUENCE
// 0x30 Sequence
if (bytes[bIndex] != 48) {
LOG.error("Not a PKCS#8 private key");
throw new IllegalArgumentException("Not a PKCS#8 private key");
}
// next byte contain the number of bytes
// of SEQUENCE element (length field)
++bIndex;
// Get number of bytes of element
int sizeOfContent = getSizeOfContent(bytes, bIndex);
int sizeOfLengthField = getSizeOfLengthField(bytes, bIndex);
LOG.debug("PrivateKeyInfo(SEQUENCE): Number of bytes:"
+ sizeOfContent
+ "PrivateKeyInfo(SEQUENCE): Number of bytes of length field:"
+ sizeOfLengthField);
// version::=INTEGER
// shift index to version element
bIndex += sizeOfLengthField;
// 0x02 Integer
if (bytes[bIndex] != 2) {
LOG.error("Not a PKCS#8 private key");
throw new IllegalArgumentException("Not a PKCS#8 private key");
}
++bIndex;
// Get number of bytes of element
sizeOfContent = getSizeOfContent(bytes, bIndex);
sizeOfLengthField = getSizeOfLengthField(bytes, bIndex);
LOG.debug("Version(INTEGER): Number of bytes:" + sizeOfContent
+ "Version(INTEGER): Number of bytes of length field:"
+ sizeOfLengthField);
// PrivateKeyAlgorithm::= PrivateKeyAlgorithmIdentifier
// shift index to PrivateKeyAlgorithm element
bIndex = bIndex + sizeOfLengthField + sizeOfContent;
// ? PrivateKeyAlgorithmIdentifier
// if (bytes[bIndex] != ?) {
// throw new IllegalArgumentException("Not a PKCS#8 private key");
// }
++bIndex;
// Get number of bytes of element
sizeOfContent = getSizeOfContent(bytes, bIndex);
sizeOfLengthField = getSizeOfLengthField(bytes, bIndex);
LOG.debug("PrivateKeyAlgorithm(PrivateKeyAlgorithmIdentifier): Number of bytes:"
+ sizeOfContent
+ "PrivateKeyAlgorithm(PrivateKeyAlgorithmIdentifier): "
+ "Number of bytes of length field:" + sizeOfLengthField);
// PrivateKey::= OCTET STRING
// shift index to PrivateKey element
bIndex = bIndex + sizeOfLengthField + sizeOfContent;
// 0x04 OCTET STRING
if (bytes[bIndex] != 4) {
throw new IllegalArgumentException("Not a PKCS#8 private key");
}
++bIndex;
// Get number of bytes of element
sizeOfContent = getSizeOfContent(bytes, bIndex);
sizeOfLengthField = getSizeOfLengthField(bytes, bIndex);
LOG.debug("PrivateKey(OCTET STRING: Number of bytes:"
+ sizeOfContent
+ "PrivateKey(OCTET STRING): Number of bytes of length field:"
+ sizeOfLengthField);
return Arrays.copyOfRange(bytes, bIndex + sizeOfLengthField, bIndex
+ sizeOfLengthField + sizeOfContent);
} |
32c21794-6a00-4c8b-abaf-c3ac1fe31175 | 5 | public Deplacement ProchainDeplacement(int i) {
Deplacement deplacementProchain = null;
Tour touractuelle = null;
int j =0;
for (Tour tour : historiqueToursJoueur) {
touractuelle = tour;
for (Deplacement deplacement : tour.getListDeplacement()) {
j++;
if(j == (i))
{
deplacementProchain = deplacement;
break;
}
}
}
if (deplacementProchain!=null && touractuelle !=null ){
tablier.deplacerDame(deplacementProchain.getCaseDepart(),deplacementProchain.getCaseArriver());
}
return deplacementProchain;
} |
377dd4a9-b4bb-4c1a-a878-640a2f7d2392 | 2 | void close ()
throws USBException
{
if (fd < 0)
return;
try {
// make sure this isn't usable any more
long status = closeNative (fd);
if (status < 0)
throw new USBException ("error closing device",
(int)(-status));
} finally {
// make sure nobody else sees the device
usb.removeDev (this);
hub = null;
fd = -1;
}
} |
5a6c48c7-c2d4-4a07-9fe9-d55be899468e | 7 | private void quickSortMostly0(int[] a, int low, int high) { //the valid elements of the list are [low, high]
if (high - low <= a.length / 10)
return;
int n = high - low; //number of elements in the list.
int p = low + 1; //median of three; pivot's index.
int pivot = a[p]; //p's value, the pivot value
int i = low;
int j = high - 2;
initializeReversed();
swap(a, p, high - 1); //store the pivot at the end.
while (i <= j) {
while (a[i] < pivot && i < high - 2) { //don't run into the pivot we stored at index [high-1]
i++;
}
while (a[j] > pivot && j > low) {
j--;
}
if (i <= j) {
swap(a, i, j);
i++;
j--;
}
}
swap(a, i, high - 1); //put the pivot into its correct spot.
quickSortMostly0(a, low, i);
quickSortMostly0(a, i + 1, high);
} |
9b958043-fadd-4748-b324-376c7d8f4af4 | 6 | public static void main(String args[]) {
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(PaletteSampler_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PaletteSampler_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PaletteSampler_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PaletteSampler_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PaletteSampler_UI().setVisible(true);
}
});
} |
f4e5a42f-f199-4912-88dd-b701cfc1d1ad | 6 | public void populateMapWidget()
{
Random ran = new Random();
for (int i=0; i<6; ++i) {
core.Point p = new core.Point(ran.nextInt(getWidth()-6)+3, ran.nextInt(getHeight()));
MapObject o = ran.nextBoolean() ? MapObject.TREE : MapObject.MOUNTAINS;
obstacles.add(p);
mapWidget.objectAt(p.y, p.x).setLayer(2, new gui.WidgetImage(o.file));
}
for (int i=0; i<getHeight(); ++i) {
for (int j=0; j<getWidth(); ++j) {
mapWidget.objectAt(i, j).setLayer(0, new gui.WidgetImage(terrain.file, 64));
}
}
GroupOfUnits u;
for (core.Point pos: p2u.points()) {
u = p2u.get(pos);
if (u != null) {
System.out.println(mapWidget.objectAt(pos.y, pos.x));
mapWidget.objectAt(pos.y, pos.x).setLayer(3, new gui.WidgetImage(u.type.file));
mapWidget.objectAt(pos.y, pos.x).setLayer(4, new gui.WidgetLabel(""+u.getNumber(), u.getOwner().getColor()));
}
//mapWidget.objectAt(pos.y, pos.x).setToolTip(u.getTooltip());
//mapWidget.objectAt(pos.y, pos.x).setToolTip(o.getName());
}
} |
5c7ef826-6781-4256-b1a4-46d728eac178 | 9 | public void openImplicitChannel() throws CardException {
if (scpVersion == SCP_02_0A || scpVersion == SCP_02_0B || scpVersion == SCP_02_1A || scpVersion == SCP_02_1B) {
CommandAPDU getData = new CommandAPDU(CLA_GP, GET_DATA, 0, 0xE0);
ResponseAPDU data = channel.transmit(getData);
byte[] result = data.getBytes();
int keySet = 0;
if (result.length > 6)
keySet = result[result[0] != 0 ? 5 : 6];
KeySet staticKeys = keys.get(keySet);
if (staticKeys == null) {
throw new IllegalStateException("Key set " + keySet + " not defined.");
}
CommandAPDU getSeq = new CommandAPDU(CLA_GP, GET_DATA, 0, 0xC1);
ResponseAPDU seq = channel.transmit(getSeq);
result = seq.getBytes();
short sw = (short) seq.getSW();
if (sw != ISO7816.SW_NO_ERROR) {
throw new CardException("Reading sequence counter failed. SW: " + GPUtils.swToString(sw));
}
try {
KeySet sessionKeys = deriveSessionKeysSCP02(staticKeys, result[2], result[3], true);
byte[] temp = GPUtils.pad80(sdAID.getBytes());
byte[] icv = GPUtils.mac_des_3des(sessionKeys.keys[1], temp, new byte[8]);
byte[] ricv = GPUtils.mac_des_3des(sessionKeys.keys[3], temp, new byte[8]);
wrapper = new SecureChannelWrapper(sessionKeys, scpVersion, APDU_MAC, icv, ricv);
} catch (Exception e) {
throw new CardException("Implicit secure channel initialization failed.", e);
}
}
} |
e3be1051-b39c-4733-8bf6-fc2bfed23eb9 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already knowledgable about <S-HIS-HER> group."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> point(s) at <S-HIS-HER> group members and knowingly cast(s) a spell.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialVisualFizzle(mob,target,L("<S-NAME> point(s) at <S-HIS-HER> group members speak(s) knowingly, but nothing more happens."));
// return whether it worked
return success;
} |
88d68d3a-8abe-4c57-a496-3468381ddd4b | 3 | public void actionPerformed(ActionEvent ev)
{
try
{
InstituicaoCooperadora objt = classeView();
if (obj == null)
{
long x = new InstituicaoCooperadoraDAO().inserir(objt);
objt.setId(x);
JOptionPane.showMessageDialog(null,
"Os dados foram inseridos com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
if (tabela != null)
tabela.adc(objt);
else
autocp.adicionar(objt);
}
else
{
new InstituicaoCooperadoraDAO().atualizar(objt);
JOptionPane.showMessageDialog(null,
"Os dados foram atualizados com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
tabela.edt(objt);
}
view.dispose();
}
catch (Exception e)
{
JOptionPane
.showMessageDialog(
null,
"Verifique se os campos estão preenchidos corretamente ou se estão repetidos",
"Alerta", JOptionPane.WARNING_MESSAGE);
}
} |
159e3b1e-b571-4ccb-88ed-174c2d6ad21b | 3 | @RequestMapping(value = "/addFlashcard", params = {"deckId"}, method = RequestMethod.POST)
public String addFlashcard(
@RequestParam("file") MultipartFile file,
@RequestParam("deckId") int deckId,
@ModelAttribute Flashcard flashcard,
HttpSession session,
Model model) {
if(session.getAttribute("username") == null)
return "index";
flashcard.setDeckId(deckId);
if(!file.isEmpty()) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = file.getBytes();
byte[] hash = md.digest(bytes);
File pictureFile = new File("public/pictures/" + hash);
BufferedOutputStream stream =
new BufferedOutputStream(
new FileOutputStream(
pictureFile
)
);
stream.write(bytes);
stream.close();
System.out.println(pictureFile.getName());
Database.insertFlashcard(flashcard, pictureFile.getName());
return deck(deckId, session, model);
} catch(Exception e) {
return deck(deckId, session, model);
}
}
Database.insertFlashcard(flashcard);
return deck(deckId, session, model);
} |
e4cc6dbf-88ef-4c46-83c9-5935ff73a229 | 2 | public LoadMenu(){
try {
registerFont = Font.createFont(Font.TRUETYPE_FONT, getClass().getClassLoader().getResource("res/narrow.ttf").openStream());
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
intro = Toolkit.getDefaultToolkit().getImage(
(getClass().getResource("/res/intro.png")));
intro2 = Toolkit.getDefaultToolkit().getImage(
(getClass().getResource("/res/intro2.png")));
//Load the used Images
new Tile();
new Sounds();
} |
5c137204-f40f-42bd-b162-152d4ae65894 | 9 | @Override
public void configure(AbstractCommand command, String[] args) {
int page = 0;
String search = null;
boolean listReverse = false;
boolean listSimple = false;
if (args.length == 3) {
page = Integer.parseInt(args[0]);
search = args[1];
listReverse = CommandLineParser.isOptionPresent(args[2], 'r');
listSimple = CommandLineParser.isOptionPresent(args[2], 's');
} else if (args.length == 2) {
if (CommandLineParser.isInteger(args[0])) {
page = Integer.parseInt(args[0]);
listReverse = CommandLineParser.isOptionPresent(args[1], 'r');
listSimple = CommandLineParser.isOptionPresent(args[1], 's');
if (!listReverse && !listSimple) {
search = args[1];
}
} else {
search = args[0];
listReverse = CommandLineParser.isOptionPresent(args[1], 'r');
listSimple = CommandLineParser.isOptionPresent(args[1], 's');
}
} else if (args.length == 1) {
if (CommandLineParser.isInteger(args[0])) {
page = Integer.parseInt(args[0]);
} else {
listReverse = CommandLineParser.isOptionPresent(args[0], 'r');
listSimple = CommandLineParser.isOptionPresent(args[0], 's');
if (listReverse || listSimple) {
search = null;
} else {
search = args[0];
}
}
}
TimeBanListCommand listCommand = (TimeBanListCommand) command;
listCommand.setPage(page);
listCommand.setReverse(listReverse);
listCommand.setSearch(search);
listCommand.setSimple(listSimple);
} |
c4bf7232-3bfe-4464-9250-22c11c26ad6b | 9 | @Override
protected Void doInBackground() throws Exception
{
currentPlayer = this;
if (medias.length > 1)
Gui.getInstance().getStopButton().setVisible(true);
for (MediaElement item : medias)
{
if (cancelPlayer)
break;
if (!item.getVisible())
continue;
String name = item.getPath();
item.setSeen(true);
if (saver != null && !saver.isDone())
saver.cancel(true);
saver = new DatabaseSaver();
saver.execute();
if (cancelPlayer)
break;
try
{
if (System.getProperty("os.name").equals("Linux"))
{
final Process process = Runtime.getRuntime().exec(new String[]
{
"bash", "-c", "vlc \"" + name + "\""
+ " vlc://exit --play-and-exit"
});
process.waitFor();
}
else
Desktop.getDesktop().open(new File(name));
} catch (IOException | InterruptedException exception)
{
System.err.println("Could not open: " + name + System.lineSeparator());
}
}
return null;
} |
2c54ab75-5ea8-4fe3-9e6a-c07c600107ed | 4 | public Message build() {
try {
Message record = new Message();
record.to = fieldSetFlags()[0] ? this.to : (java.lang.CharSequence) defaultValue(fields()[0]);
record.from = fieldSetFlags()[1] ? this.from : (java.lang.CharSequence) defaultValue(fields()[1]);
record.body = fieldSetFlags()[2] ? this.body : (java.lang.CharSequence) defaultValue(fields()[2]);
return record;
} catch (Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
} |
2f6a08b0-2845-479a-bdaa-e8ec4cb9c28b | 9 | @Override
public void run() {
try {
// Создаём Selector
Selector selector = SelectorProvider.provider().openSelector();
// Открываем серверный канал
ServerSocketChannel serverChannel = ServerSocketChannel.open();
// Убираем блокировку
serverChannel.configureBlocking(false);
// Вешаемся на порт
serverChannel.socket().bind(new InetSocketAddress(host, port));
// Регистрация в селекторе
serverChannel.register(selector, serverChannel.validOps());
// Основной цикл работу неблокирующего сервер
// Этот цикл будет одинаковым для практически любого неблокирующего
// сервера
while (selector.select() > -1) {
// Получаем ключи на которых произошли события в момент
// последней выборки
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isValid()) {
// Обработка всех возможнных событий ключа
try {
if (key.isAcceptable()) {
// Принимаем соединение
accept(key);
} else if (key.isConnectable()) {
// Устанавливаем соединение
connect(key);
} else if (key.isReadable()) {
// Читаем данные
read(key);
} else if (key.isWritable()) {
// Пишем данные
write(key);
}
} catch (Exception e) {
e.printStackTrace();
close(key);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
} |
b7b93044-d885-4ef6-a79e-10246da3113a | 9 | public void update() {
boolean p1ReadyE = false;
boolean p2ReadyE = false;
for (int i = 0; i < model.length; i++) {
if (selection[i] == 1) {
p1ReadyE = true;
p1Character[i].setEnabled(false);
p1Character[i].setBackground(Color.RED);
p2Character[i].setEnabled(false);
p2Character[i].setBackground(Color.RED);
p1Stats.setText("Height: " + model[i].getHeight() + " \n"
+ "Speed: "+ model[i].getSpeed() + "\n"
+ "Life: " + model[i].getLife());
p1Desc.setText(model[i].getDescription());
} else if (selection[i] == 2) {
p2ReadyE = true;
p2Character[i].setEnabled(false);
p2Character[i].setBackground(Color.BLUE);
p1Character[i].setEnabled(false);
p1Character[i].setBackground(Color.BLUE);
p2Stats.setText("Height: " + model[i].getHeight() + " \n"
+ "Speed: "+ model[i].getSpeed() + "\n"
+ "Life: " + model[i].getLife());
p2Desc.setText(model[i].getDescription());
} else {
p1Character[i].setEnabled(true);
p2Character[i].setBackground(Color.WHITE);
p2Character[i].setEnabled(true);
p1Character[i].setBackground(Color.WHITE);
}
}
if (p1ReadyE)
p1Ready.setEnabled(true);
else
p1Ready.setEnabled(false);
if (p2ReadyE)
p2Ready.setEnabled(true);
else
p2Ready.setEnabled(false);
if(p1ReadyBool)
p1Ready.setText("Un Ready");
else
p1Ready.setText("Ready!");
if(p2ReadyBool)
p2Ready.setText("Un Ready");
else
p2Ready.setText("Ready!");
if(p1ReadyBool && p2ReadyBool) {
startGame.setEnabled(true);
} else {
startGame.setEnabled(false);
}
} |
34c9c0a0-f308-487e-838b-560a4214d2f8 | 7 | private Object readJSON() throws JSONException {
switch (read(3)) {
case zipObject:
return readObject();
case zipArrayString:
return readArray(true);
case zipArrayValue:
return readArray(false);
case zipEmptyObject:
return new JSONObject();
case zipEmptyArray:
return new JSONArray();
case zipTrue:
return Boolean.TRUE;
case zipFalse:
return Boolean.FALSE;
default:
return JSONObject.NULL;
}
} |
8e781cb7-01fc-4308-b5fe-d2e2ee9c0482 | 2 | public boolean hasPreferences(String module) {
module += '.';
for (Enumeration<Object> keys = mPrefs.keys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
if (key.startsWith(module)) {
return true;
}
}
return false;
} |
77ffa7b4-2b53-44ed-9f9f-9f019c87c89d | 9 | public static String[] split(String str, char separatorChar, boolean preserveAllTokens) {
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return new String[0];
}
List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
} |
7737ad0e-7ed7-4d48-aad4-5ca017a7718b | 6 | @EventHandler
public void SpiderResistance(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSpiderConfig().getDouble("Spider.Resistance.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSpiderConfig().getBoolean("Spider.Resistance.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, plugin.getSpiderConfig().getInt("Spider.Resistance.Time"), plugin.getSpiderConfig().getInt("Spider.Resistance.Power")));
}
} |
42782f35-3a70-4758-b1fe-30c9fdd436cc | 1 | public void addAccount(BankAccount account) throws IllegalArgumentException {
if (! canHaveAsAccount(account))
throw new IllegalArgumentException();
accounts.add(account);
} |
6d6a18e8-705c-48d0-a6ab-06fafabd7ece | 0 | public boolean isDirty() {
getExpression().asString(); // Force resolution of reference.
return super.isDirty();
} |
c77bea01-c09b-4595-a583-9160582fb88a | 0 | public int getX(){
return x;
} |
32ce3059-b026-401d-8fe2-8c61cdee2d13 | 8 | private String getDriverProfile() {
/**
* The temporary profile Selenium/Firefox creates should be
* located at java.io.tmpdir. On Windows it is %TEMP%
* Search is based on the presence of the file which name is the same as the name of the profile.
* This file was manually placed in profile directory.
*/
File sysTemp = new File(System.getProperty("java.io.tmpdir"));
File pd = null;
boolean bFound = false;
for (File t : sysTemp.listFiles()) {
if (!t.isDirectory()) { continue; }
if (t.toString().contains("webdriver-profile")) {
for(File f : t.listFiles()) {
if (f.isDirectory()) { continue; }
if(System.currentTimeMillis() < t.lastModified() + 10000 &&
f.getName().equalsIgnoreCase(namedProfile)) {
pd = t;
bFound = true;
break;
}
}
if(bFound) {break;}
}
}
return pd.toString();
} |
a0b84eb7-309e-4fa7-ba0c-062373fe4f38 | 1 | public static void main(String[] args) {
Application app = Application.get();
if(!app.init()) {
System.out.println("Error with initialization! :(");
System.exit(-1);
}
app.run();
} |
8aaaf8c5-4324-4017-8fdd-c679d7e621b2 | 0 | public List<EventComment> findAfterEventCommentsByHallEventId(final Long hallEventId) {
return new ArrayList<EventComment>();
} |
c6ff38b2-b13c-4a4c-8d22-b61145af59a9 | 4 | public Object getValueAt(int row, int col) {
Account account = accounts.getBusinessObjects().get(row);
if (col == 0) {
return account;
}
if (col == 1) {
if(account==null) return null;
if(account.getType().isInverted())
return account.getSaldo().negate();
else return account.getSaldo();
// TODO: use this isInverted() switch to call negate() in other places
}
return null;
} |
aa623783-7877-4084-aeb6-ebf9ff359218 | 2 | public ArrayList<String> locateAllAt(int p_X, int p_Y) throws Exception
{
String around = "locate(What," + p_X + "," + p_Y + ").";
ArrayList<String> what = new ArrayList<String>();
SolveInfo info = m_Engine.solve(around);
while(info.isSuccess())
{
String type = "";
type = info.getVarValue("What").toString();
what.add(type);
if(!info.hasOpenAlternatives())
break;
info = m_Engine.solveNext();
}
return what;
} |
905aaff5-a02e-40ee-96a8-8aa56fd36bd1 | 9 | public static void main( String[] args ) throws Exception {
Scanner scanner = new Scanner( System.in );
System.out.println( "Enter grid size:" );
int gridSize = scanner.nextInt();
StringBuilder[] grid = new StringBuilder[gridSize];
System.out.println( "Enter location of text file to parse:" );
BufferedReader br = new BufferedReader( new FileReader( scanner.next() ) );
scanner.close();
String line;
int j = 0;
while ( ( line = br.readLine() ) != null ) {
grid[j] = new StringBuilder().append( line );
j++;
}
br.close();
for ( int i = grid.length - 1; i >= 0; i-- ) {
for ( int c = 0; c < grid[i].length(); c++ ) {
if ( grid[i].charAt( c ) == ".".charAt( 0 ) ) {
int h = 0;
while ( true ) {
h++;
if ( i + h == grid.length || grid[i + h].charAt( c ) != " ".charAt( 0 ) ) {
h--;
break;
}
}
if ( h > 0 ) {
grid[i + h].setCharAt( c, grid[i].charAt( c ) );
grid[i].setCharAt( c, " ".charAt( 0 ) );
}
}
}
}
for ( StringBuilder sb : grid )
System.out.println( sb.toString() );
} |
35716b5c-644b-4e2d-802f-51ca793f60ed | 8 | @Override
public void unInvoke()
{
final MOB mob=(MOB)affected;
if((canBeUninvoked())&&(mob!=null))
if(mob.location()!=null)
{
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> dissipate(s)."));
final Vector<Item> V=new Vector<Item>();
for(int i=0;i<mob.numItems();i++)
V.addElement(mob.getItem(i));
for(int i=0;i<V.size();i++)
{
final Item I=V.elementAt(i);
mob.delItem(I);
mob.location().addItem(I,ItemPossessor.Expire.Monster_EQ);
}
}
super.unInvoke();
if((canBeUninvoked())&&(mob!=null))
{
if(mob.amDead())
mob.setLocation(null);
mob.destroy();
}
} |
8ee4732c-a97a-4b47-aec4-5c6699247964 | 2 | public static ValueFormatType fromValue(String v) {
for (ValueFormatType c: ValueFormatType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
} |
355c48e4-1800-43ec-80cd-f9c2bd506b4e | 4 | public void readInPupils() throws InvalidDataException {
ArrayList <String> ErrorPupil = new ArrayList();
try {
// TODO code application logic here
Scanner scan = new Scanner(new File("D:/Pupils.csv"));
while (scan.hasNextLine()) {
String pup = scan.nextLine();
String[] pupil = pup.split(",");
try {
Pupil p = new Pupil();
p.setSurname(pupil[0]);
p.setForename(pupil[1]);
p.setGender(pupil[2]);
p.setDOB(pupil[3]);
p.setClassGroup(pupil[4]);
p.setForm(pupil[5]);
p.setUsername(pupil[6]);
p.setPassword(pupil[7]);
DBase.addPupil(p);
PrintToFile.printToLog("Added Pupil: " + p.getSurname() + " " + p.getForename());
} catch (InvalidDataException e) {
PrintToFile.printToLog("Error: at Pupil " + pupil[0] + " " + pupil[1] + " " + e.toString());
String Error = pupil[0] + " " + pupil[1];
ErrorPupil.add(Error);
}
}
} catch (IOException ex) {
PrintToFile.printToLog("Error: " + ex.toString());
} finally {
PrintToFile.printToLog("Complete all valid Pupils added, students that need correcting are: ");
for (String temp : ErrorPupil) {
PrintToFile.printToLog("Pupil: " + temp);
}
}
} |
430f5249-4d7b-4f9a-8853-c392429898bd | 0 | public static void main(String[] args) {
int i = 32768;
short s = (short) i;
System.out.println("i = " + i + ", s = " + s); // i = 32768, s = -32768
} |
e2a14b05-91c9-4a70-ba7a-310190ef6df0 | 9 | public static void main(String[] args) {
WeatherService weatherService = new WeatherService();
Report myReport = weatherService.getReport("newark, de");
List<Forecast> myForecasts = myReport.getForecasts();
System.out.println(myForecasts.size());
Forecast firstForecast = myForecasts.get(0);
System.out.println(firstForecast.getProbabilityOfPrecipitation());
// The following pre-generated code demonstrates how you can
// use StickyWeb's EditableCache to create data files.
try {
// First, you create a new EditableCache, possibly passing in an FileInputStream to an existing cache
EditableCache recording = new EditableCache();
// You can add a Request object directly to the cache.
String[] locations= {"newark, de", "newark,de",
"blacksburg,va", "blacksburg, va",
"minneapolis,mn", "minneapolis, mn",
"seattle, wa", "seattle, wa",
"nome, al", "nome,al",
"miami,fl", "miami, fl",};
for (String location : locations) {
System.out.println(location);
recording.addData(weatherService.geocodeRequest(location));
Location l = weatherService.geocode(location);
recording.addData(weatherService.getReportRequest(l.getLatitude(), l.getLongitude()));
}
// Then you can save the expanded cache, possibly over the original
recording.saveToStream(new FileOutputStream("cache.json"));
} catch (StickyWebDataSourceNotFoundException e) {
System.err.println("The given FileStream was not able to be found.");
} catch (StickyWebDataSourceParseException e) {
System.err.println("The given FileStream could not be parsed; possibly the structure is incorrect.");
} catch (StickyWebLoadDataSourceException e) {
System.err.println("The given data source could not be loaded.");
} catch (FileNotFoundException e) {
System.err.println("The given cache.json file was not found, or could not be opened.");
}
// ** End of how to use the EditableCache
catch (StickyWebNotInCacheException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StickyWebInternetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StickyWebInvalidQueryString e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StickyWebInvalidPostArguments e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
8ba3d0d9-85de-4d32-9e3a-f1414be7fc01 | 3 | private Value term() throws Exception
{
Value previous, rval;
previous = rval = factor();
while(scan.sym == Token.mul || scan.sym == Token.div) {
Token op = scan.sym;
scan.next();
previous = rval;
Value next = factor();
Instruction ins;
if(op == Token.mul) {
ins = new Mul(previous, next);
} else { // op == Token.div
ins = new Div(previous, next);
}
currentBB.addInstruction(ins);
rval = ins;
}
return rval;
} |
7e180462-79c3-415b-a2e9-7f3caaf612dd | 8 | public boolean bootstrap()
{
String userId = node.getUserId();
boolean bootstrapped = false;
System.out.println(userId + " - Bootstrapping...");
if (bootstrapList.isEmpty()) //CA wasn't contacted
{
//bootstrap list is get from formerly known contacts
bootstrapList = node.getRouteTable().getAllBucketContacts();
//node.getRouteTable().clear(); //the route table will be filled with new contacts
}
//System.out.println("OOO " + node.getRouteTable().size());
//for (Contact c : bootstrapList)
// System.out.println("----" + c);
//while (!bootstrapList.isEmpty() && !bootstrapped)
for (Contact c : bootstrapList)
{
node.getRouteTable().add(c);
//System.out.println(">>> " + node.getRouteTable());
try
{
Collection<Contact> contacts = node.lookup(node.getNodeId()).get();
if (contacts != null && contacts.size() != 0)
{
bootstrapped = true;
break;
}
else
{
node.getRouteTable().remove(c);
}
}
catch (Exception e)
{
System.out.println(userId + " - 1st Bootstrap phase attempt failed!");
//e.printStackTrace();
}
finally
{
node.getRouteTable().remove(c);
}
}
if (bootstrapped)
{
System.out.println(userId + " - End 1st phase Bootstrap");
try
{
node.getRouteTable().resetRefreshTimes();
Collection<NodeId> toRefresh = node.getRouteTable().getRefreshIDs(true);
for (NodeId id : toRefresh)
{
node.lookup(id).get();
}
System.out.println(userId + " - End 2nd phase Bootstrap");
}
catch (Exception e)
{
System.out.println(userId + " - Bootstrap failed!");
return false;
}
return true;
}
else
{
System.out.println(userId + " - Bootstrap Failed!");
return false;
}
} |
57d67a8c-e3ae-4c0d-9521-0287d8f6105e | 0 | private void putCallObj(Long key, IRemoteCallObject object) {
sync.put(key, object);
} |
01fd2c6e-3b65-4aa7-a6ba-d2352256d415 | 2 | public static void main(String[] args) {
Hand p1Hand = findHandFromCardSet(convertToCardSet(args[0].trim(), args[2].trim()));
Hand p2Hand = findHandFromCardSet(convertToCardSet(args[1].trim(), args[2].trim()));
System.out.println("Player one has " + p1Hand.toString());
System.out.println("Player two has " + p2Hand.toString());
if (p1Hand.compareTo(p2Hand) == 0) {
System.out.println("Player one has the same hand as player two!");
} else {
System.out.println("Player " + (p1Hand.compareTo(p2Hand) > 0 ? "one" : "two") + " wins!");
}
} |
7af7c2b7-d6c5-450a-b45c-12b5febdf895 | 3 | ProvinceListDialog(java.awt.Frame parent) {
super(parent, "Provinces", false);
ProvinceData.Province[] provs = Main.provinceData.getAllProvs();
String[][] provNameTable = new String[provs.length][3];
int i = 0;
boolean pti = true;
for (ProvinceData.Province prov : provs) {
provNameTable[i][0] = Integer.toString(prov.getId());
provNameTable[i][1] = prov.getName();
if (pti) {
provNameTable[i][2] = Text.getText("terra_incognita");
pti = false;
} else {
provNameTable[i][2] = Text.getText("prov" + prov.getId());
}
i++;
}
JTable provTable = new JTable(provNameTable, new String[] { "Tag", "Name in definition", "Display name" } );
provTable.setDefaultEditor(Object.class, null);
if (supportsRowSorter) {
provTable.setAutoCreateRowSorter(true);
} else {
System.out.println("Table sorting not supported.");
}
setLayout(new BorderLayout());
add(new JScrollPane(provTable), BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
} |
dca115d7-b2cc-48c0-99d4-039dcea6a914 | 7 | private void tryToFall(World var1, int var2, int var3, int var4) {
if(canFallBelow(var1, var2, var3 - 1, var4) && var3 >= 0) {
byte var8 = 32;
if(!fallInstantly && var1.checkChunksExist(var2 - var8, var3 - var8, var4 - var8, var2 + var8, var3 + var8, var4 + var8)) {
EntityFallingSand var9 = new EntityFallingSand(var1, (double)((float)var2 + 0.5F), (double)((float)var3 + 0.5F), (double)((float)var4 + 0.5F), this.blockID);
var1.entityJoinedWorld(var9);
} else {
var1.setBlockWithNotify(var2, var3, var4, 0);
while(canFallBelow(var1, var2, var3 - 1, var4) && var3 > 0) {
--var3;
}
if(var3 > 0) {
var1.setBlockWithNotify(var2, var3, var4, this.blockID);
}
}
}
} |
751816a2-529e-40b9-8c38-5d548c47708e | 6 | public String getType(Symtab st) {
if (exp1Type.equals("message") || exp2Type.equals("message"))
return "message";
if (exp1Type.equals("String") || exp2Type.equals("String"))
return "String";
else if (exp1Type.equals("decimal") || exp2Type.equals("decimal"))
return "decimal";
else
return "int";
} |
87153533-d822-419b-8787-84fbfac76c49 | 6 | public String POST_Request(String url, String url_params) {
StringBuffer response;
String json_data = "";
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) set_headers(url);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(url_params);
wr.flush();
wr.close();
System.out.println(url_params);
System.out.println(con.getResponseCode());
if (con.getResponseCode() == 500)
System.out.println(con.getErrorStream());
if (con.getResponseCode() == 201) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
json_data = response.toString();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
} catch (Exception e) {
con.getErrorStream();
}
return json_data;
} |
3b2f8074-d87f-4a1d-8a62-f5e0d4514d60 | 2 | public boolean removeAt(int index) {
if (indexOK(index)) {
if (index == 0) {
shiftArrayBy(-1);
} else {
System.arraycopy(array, index + 1, array, index, array.length - index - 1);
expandArrayCapacityBy(-1);
}
return true;
}
return false;
} |
42b0dae7-3b45-43e0-9a9f-2a6587a45e7d | 7 | private void frequencyTable(ServletOutputStream out, TimerInfoStats stats, String sort, String baseurl)
throws IOException {
Set<TimerInfoItem> treeSet;
if ("perf".equalsIgnoreCase(sort)) {
treeSet = new TreeSet<TimerInfoItem>(new AverageComparator());
} else if ("uri".equalsIgnoreCase(sort)) {
treeSet = new TreeSet<TimerInfoItem>(new UriComparator());
} else {
treeSet = new TreeSet<TimerInfoItem>(new TotalTimeComparator());
}
treeSet.addAll(stats.getStatData().values());
float totaltime = tistat.getElapsedTime() / 1000f; // secs
//threadload
//long totalcall = tistat.getTotalNofCalls();
//float callssecs = totalcall / totaltime;
//double threadload = (tistat.getTotalAverage() * callssecs) / 1000f;
//
out.println("<br/>");
out.println("<table style='border:1px solid black' cellspacing='0' cellpadding='1'>");
out.println("<tr bgcolor='#eeeeff'>");
out.println("<th>No</th>");
out.println("<th># Calls</th>");
out.println("<th>Total (s)</th>");
out.println("<th>Min (s)</th>");
out.println("<th>1/Frequency (s)</th>");
out.println("<th>Max (s)</th>");
out.println("<th>Std (s)</th>");
out.println("<th><a href='" + baseurl + "&sort=perf'>Perf (#/s)</a></th>");
out.println("<th><a href='" + baseurl + "&sort=time'>Total (%)</a></th>");
out.println("<th>Rate (#/s)</th>");
out.println("<th>Td99 [s]</th>");
out.println("<th>Payload [KB]</th>");
out.println("<th>Bitrate [KB/s]</th>");
out.println("<th>Cacheability TTL5 [%]</th>");
out.println("<th>Cacheability TTL15 [%]</th>");
out.println("<th><a href='" + baseurl + "&sort=uri'>URI</a></th></tr>");
NumberFormat nf0 = NumberFormat.getInstance();
nf0.setMaximumFractionDigits(0);
nf0.setMinimumFractionDigits(0);
NumberFormat nf1 = NumberFormat.getInstance();
nf1.setMaximumFractionDigits(1);
nf1.setMinimumFractionDigits(1);
NumberFormat nf2 = NumberFormat.getInstance();
nf2.setMaximumFractionDigits(2);
nf2.setMinimumFractionDigits(2);
NumberFormat nf3 = NumberFormat.getInstance();
nf3.setMaximumFractionDigits(3);
nf3.setMinimumFractionDigits(3);
long loop = 1;
//frequencyTable
Map<String, CacheInfoItem> clone = stats.getCacheData();
for (TimerInfoItem item : treeSet) {
String key = item.getKey();
double[] freqDataArray = item.getFreqDataArray(stats.getTotalTotalTime(), 1d, totaltime);
CacheInfoItem cacheInfoItem = clone.get(key);
if (freqDataArray[0] != 0) {
out.println("<tr align='right'>");
out.println("<td>" + nf0.format(loop++) + "</td>");
out.println("<td>" + nf0.format(freqDataArray[0]) + "</td>");
out.println("<td>" + nf0.format(freqDataArray[1]) + "</td>");
out.println("<td bgcolor='#eeeeff'>" + nf1.format(freqDataArray[2]) + "</td>");
out.println("<td bgcolor='#dddddd'>" + nf1.format(freqDataArray[3]) + "</td>");
out.println("<td bgcolor='#eeeeff'>" + nf1.format(freqDataArray[4]) + "</td>");
out.println("<td>" + nf1.format(freqDataArray[5]) + "</td>");
out.println("<td>" + nf2.format(freqDataArray[6]) + "</td>");
out.println("<td>" + nf3.format(freqDataArray[7]) + "</td>");
out.println("<td>" + nf3.format(freqDataArray[8]) + "</td>");
if (key.contains("|200|") || key.equals("TOTAL")) {
out.println("<td>" + nf2.format(freqDataArray[9]) + "</td>");
out.println("<td bgcolor='#eee'>" + nf1.format(freqDataArray[10] / 1024) + "</td>");
out.println("<td bgcolor='#eee'>" + nf1.format(freqDataArray[12] / 1024) + "</td>");
out.println("<td>" + nf1.format(cacheInfoItem.getCacheability5()) + "</td>");
out.println("<td>" + nf1.format(cacheInfoItem.getCacheability15()) + "</td>");
} else {
out.println("<td>-</td>");
out.println("<td bgcolor='#eee'>-</td>");
out.println("<td bgcolor='#eee'>-</td>");
out.println("<td>-</td>");
out.println("<td>-</td>");
}
out.println("<td style='border-right:none' align='left'>" + key + "</td>");
}
out.println("</tr>");
if (loop > 10000) {
break;
}
}
out.println("\r\n<tr bgcolor='#eeeeff'><td colspan='16' style='border:none'> </td></tr></table>");
} |
8e7bc78f-8910-47de-81b5-8fa2c01bc586 | 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(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( InstantiationException ex ) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( IllegalAccessException ex ) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( javax.swing.UnsupportedLookAndFeelException ex ) {
java.util.logging.Logger.getLogger(About.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 About().setVisible(true);
}
});
} |
62d10272-2d63-4ee8-ae35-0bad098b3f94 | 8 | public boolean isBlack(String dir) throws IOException
{
Vector<String> black_id = new Vector<String>();
List<String> black_edges = getBlackEdges();
if (black_edges != null) {
for(int i=0; i < black_edges.size(); i++) {
String [] vals = black_edges.get(i).split("\\|");
if (vals[0].equals(dir+"r") || vals[0].equals(dir+"f")) {
black_id.add(vals[1]);
}
}
}
for(String adj : Node.dirs) {
List<String> edges = getEdges(dir+adj);
if (edges != null) {
for(int i=0; i < edges.size(); i++){
String[] vals = edges.get(i).split("!");
if (!black_id.contains(vals[0])) {
return false;
}
}
}
}
return true;
} |
0e1f877b-e4a3-4576-96dd-5583e9b3e8f4 | 9 | private final String lock2key(String lock) {
String key_return;
int len = lock.length();
char[] key = new char[len];
for (int i = 1; i < len; i++)
key[i] = (char) (lock.charAt(i) ^ lock.charAt(i - 1));
key[0] = (char) (lock.charAt(0) ^ lock.charAt(len - 1) ^ lock.charAt(len - 2) ^ 5);
for (int i = 0; i < len; i++)
key[i] = (char) (((key[i] << 4) & 240) | ((key[i] >> 4) & 15));
key_return = new String();
for (int i = 0; i < len; i++) {
if (key[i] == 0) {
key_return += "/%DCN000%/";
} else if (key[i] == 5) {
key_return += "/%DCN005%/";
} else if (key[i] == 36) {
key_return += "/%DCN036%/";
} else if (key[i] == 96) {
key_return += "/%DCN096%/";
} else if (key[i] == 124) {
key_return += "/%DCN124%/";
} else if (key[i] == 126) {
key_return += "/%DCN126%/";
} else {
key_return += key[i];
}
}
return key_return;
} |
9bdd0953-ae76-43b8-8424-e740bd459894 | 5 | @Override
public void run() {
String command = "";
while (running) {
try {
if (jLine) {
command = consoleReader.readLine(">", null);
} else {
command = consoleReader.readLine();
}
if (command == null || command.trim().length() == 0)
continue;
server.handleCommand(command.trim());
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error while reading commands", ex);
}
}
} |
efaded19-0b18-4628-9298-b0571a430fe9 | 5 | public static void main(String[] args)
{
double ran = Math.random();
if(ran < .33)
{
f = new File("dungeon.wav");
s = new SoundPlayer(f);
} else if (ran > .66)
{
f = new File("angel.wav");
s = new SoundPlayer(f);
} else {
f = new File("battle.wav");
s = new SoundPlayer(f);
}
BufferedImage img = null;
try
{
img = ImageIO.read(new File("currentMap.gif"));
} catch (IOException e) {}
// Divide image Height/ width by 16 to get grid size
RPGWorld world = new RPGWorld(new RPGGrid(img.getHeight() / 16, img.getWidth() / 16 ), s);
ArrayList<Location> locs = new ArrayList<Location>();
Grid g = world.getGrid();
for(int r = 0; r < g.getNumRows(); r++)
{
for(int c = 0; c < g.getNumCols(); c++)
{
locs.add(new Location(r, c));
world.add(new Location(r, c), new EmptySpaceDungeon());
}
}
//Door, GridItem, Obstacle, EmptySpaceTown, Person, EmptySpaceDungeon, Portal
world.add(locs.get(0), new Obstacle());
world.add(locs.get(1), new Obstacle());
world.add(locs.get(2), new Obstacle());
world.add(locs.get(3), new Obstacle());
world.add(locs.get(4), new Obstacle());
world.add(locs.get(5), new Obstacle());
world.add(locs.get(19), new Obstacle());
world.add(locs.get(20), new Obstacle());
world.add(locs.get(21), new Obstacle());
world.add(locs.get(22), new Obstacle());
world.add(locs.get(23), new Obstacle());
world.add(locs.get(24), new Obstacle());
world.add(locs.get(25), new Obstacle());
world.add(locs.get(26), new GridItem(new Armor(4)));
world.add(locs.get(31), new Obstacle());
world.add(locs.get(43), new Obstacle());
world.add(locs.get(47), new GridItem(new Weapon(1)));
world.add(locs.get(49), new Obstacle());
world.add(locs.get(50), new Obstacle());
world.add(locs.get(51), new GridItem(new Armor(3)));
world.add(locs.get(56), new Obstacle());
world.add(locs.get(68), new Obstacle());
world.add(locs.get(74), new Obstacle());
world.add(locs.get(75), new Obstacle());
world.add(locs.get(76), new GridItem(new Weapon(2)));
world.add(locs.get(81), new Obstacle());
world.add(locs.get(82), new Obstacle());
world.add(locs.get(83), new Obstacle());
world.add(locs.get(84), new Obstacle());
world.add(locs.get(85), new Obstacle());
world.add(locs.get(86), new Obstacle());
world.add(locs.get(87), new Obstacle());
world.add(locs.get(88), new Obstacle());
world.add(locs.get(89), new Obstacle());
world.add(locs.get(90), new Obstacle());
world.add(locs.get(91), new Obstacle());
world.add(locs.get(92), new Obstacle());
world.add(locs.get(93), new Obstacle());
world.add(locs.get(99), new Obstacle());
world.add(locs.get(100), new Obstacle());
world.add(locs.get(124), new Obstacle());
world.add(locs.get(125), new Obstacle());
world.add(locs.get(126), new Obstacle());
world.add(locs.get(127), new Obstacle());
world.add(locs.get(131), new Obstacle());
world.add(locs.get(132), new Obstacle());
world.add(locs.get(133), new Obstacle());
world.add(locs.get(134), new Obstacle());
world.add(locs.get(135), new Obstacle());
world.add(locs.get(136), new Obstacle());
world.add(locs.get(137), new Obstacle());
world.add(locs.get(138), new Obstacle());
world.add(locs.get(139), new Obstacle());
world.add(locs.get(140), new Obstacle());
world.add(locs.get(141), new Obstacle());
world.add(locs.get(142), new Obstacle());
world.add(locs.get(143), new Obstacle());
world.add(locs.get(144), new Obstacle());
world.add(locs.get(145), new Door("Ordeal"));
world.add(locs.get(146), new Obstacle());
world.add(locs.get(147), new Obstacle());
world.add(locs.get(148), new Obstacle());
world.add(locs.get(149), new Obstacle());
world.add(locs.get(152), new Obstacle());
world.add(locs.get(156), new Obstacle());
world.add(locs.get(169), new Obstacle());
world.add(locs.get(171), new Obstacle());
world.add(locs.get(177), new Obstacle());
world.add(locs.get(181), new Obstacle());
world.add(locs.get(194), new Obstacle());
world.add(locs.get(196), new Obstacle());
world.add(locs.get(202), new Obstacle());
world.add(locs.get(206), new Obstacle());
world.add(locs.get(219), new Obstacle());
world.add(locs.get(221), new Obstacle());
world.add(locs.get(227), new Obstacle());
world.add(locs.get(231), new Obstacle());
world.add(locs.get(244), new Obstacle());
world.add(locs.get(246), new Obstacle());
world.add(locs.get(252), new Obstacle());
world.add(locs.get(256), new Obstacle());
world.add(locs.get(269), new Obstacle());
world.add(locs.get(271), new Obstacle());
world.add(locs.get(277), new Obstacle());
world.add(locs.get(281), new Obstacle());
world.add(locs.get(294), new Obstacle());
world.add(locs.get(296), new Obstacle());
world.add(locs.get(302), new Obstacle());
world.add(locs.get(306), new Obstacle());
world.add(locs.get(319), new Obstacle());
world.add(locs.get(321), new Obstacle());
world.add(locs.get(327), new Obstacle());
world.add(locs.get(331), new Obstacle());
world.add(locs.get(344), new Obstacle());
world.add(locs.get(346), new Obstacle());
world.add(locs.get(352), new Obstacle());
world.add(locs.get(356), new Obstacle());
world.add(locs.get(369), new Obstacle());
world.add(locs.get(371), new Obstacle());
world.add(locs.get(377), new Obstacle());
world.add(locs.get(381), new Obstacle());
world.add(locs.get(389), new Obstacle());
world.add(locs.get(390), new Obstacle());
world.add(locs.get(391), new Obstacle());
world.add(locs.get(392), new Obstacle());
world.add(locs.get(393), new Obstacle());
world.add(locs.get(394), new Obstacle());
world.add(locs.get(396), new Obstacle());
world.add(locs.get(402), new Obstacle());
world.add(locs.get(406), new Obstacle());
world.add(locs.get(413), new Obstacle());
world.add(locs.get(419), new Obstacle());
world.add(locs.get(421), new Obstacle());
world.add(locs.get(427), new Obstacle());
world.add(locs.get(431), new Obstacle());
world.add(locs.get(438), new Obstacle());
world.add(locs.get(444), new Obstacle());
world.add(locs.get(446), new Obstacle());
world.add(locs.get(452), new Obstacle());
world.add(locs.get(456), new Obstacle());
world.add(locs.get(463), new Obstacle());
world.add(locs.get(469), new Obstacle());
world.add(locs.get(471), new Obstacle());
world.add(locs.get(475), new Obstacle());
world.add(locs.get(476), new Obstacle());
world.add(locs.get(477), new Obstacle());
world.add(locs.get(481), new Obstacle());
world.add(locs.get(482), new Obstacle());
world.add(locs.get(483), new Obstacle());
world.add(locs.get(484), new Obstacle());
world.add(locs.get(485), new Obstacle());
world.add(locs.get(486), new Obstacle());
world.add(locs.get(487), new Obstacle());
world.add(locs.get(488), new Obstacle());
world.add(locs.get(494), new Obstacle());
world.add(locs.get(497), new Obstacle());
world.add(locs.get(498), new Obstacle());
world.add(locs.get(499), new Obstacle());
world.add(locs.get(500), new Obstacle());
world.add(locs.get(519), new Obstacle());
world.add(locs.get(524), new Obstacle());
world.add(locs.get(525), new Obstacle());
world.add(locs.get(531), new Obstacle());
world.add(locs.get(532), new Obstacle());
world.add(locs.get(533), new Obstacle());
world.add(locs.get(534), new Obstacle());
world.add(locs.get(535), new Obstacle());
world.add(locs.get(536), new Obstacle());
world.add(locs.get(537), new Obstacle());
world.add(locs.get(538), new Obstacle());
world.add(locs.get(539), new Obstacle());
world.add(locs.get(540), new Obstacle());
world.add(locs.get(541), new Obstacle());
world.add(locs.get(542), new Obstacle());
world.add(locs.get(543), new Obstacle());
world.add(locs.get(544), new Obstacle());
world.add(locs.get(549), new Obstacle());
world.add(locs.get(550), new Obstacle());
world.add(locs.get(551), new GridItem(new Key("Ordeal")));
world.add(locs.get(552), new GridItem(new Armor(2)));
world.add(locs.get(553), new GridItem(new Weapon(5)));
world.add(locs.get(554), new GridItem(new Armor(1)));
world.add(locs.get(556), new Obstacle());
world.add(locs.get(569), new Obstacle());
world.add(locs.get(572), new Portal(null));
world.add(locs.get(574), new Obstacle());
world.add(locs.get(575), new Obstacle());
world.add(locs.get(581), new Obstacle());
world.add(locs.get(594), new Obstacle());
world.add(locs.get(599), new Obstacle());
world.add(locs.get(600), new Obstacle());
world.add(locs.get(601), new Obstacle());
world.add(locs.get(602), new Obstacle());
world.add(locs.get(603), new Obstacle());
world.add(locs.get(604), new Obstacle());
world.add(locs.get(605), new Obstacle());
world.add(locs.get(619), new Obstacle());
world.add(locs.get(620), new Obstacle());
world.add(locs.get(621), new Obstacle());
world.add(locs.get(622), new Obstacle());
world.add(locs.get(623), new Obstacle());
world.add(locs.get(624), new Obstacle());
Location playerLoc = new Location(19, 18);
ThePlayer p = new ThePlayer(world, new FFCharacter());
world.add(playerLoc, p);
world.show();
RPGListner mover = new RPGListner(world);
world.getJFrame().getDisplay().moveLocation(playerLoc.getRow(), playerLoc.getCol());
System.out.println("Usith thine W, A, S, and D keys to moveith thine self about");
s.play();
} |
a860e08d-9f4d-47cf-99ff-7bcf31e7c3c5 | 9 | private void setCircleDefault(Attributes attrs) {
// find the value to be set, then set it
if (attrs.getValue(0).equals("fill"))
circleDef.setFill(Boolean.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("color"))
circleDef.setColor(new Color((Integer.valueOf(attrs.getValue(1)
.substring(1), 16))));
else if (attrs.getValue(0).equals("thickness"))
circleDef.setThickness(Integer.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("alpha"))
circleDef.setAlpha(Float.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("starttime"))
circleDef.setStartTime(Integer.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("endtime"))
circleDef.setEndTime(Integer.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("onclick"))
circleDef.setOnClick(Integer.valueOf(attrs.getValue(1)));
else if (attrs.getValue(0).equals("onclickurl"))
circleDef.setOnClickUrl(attrs.getValue(1));
else if (attrs.getQName(0).equals("filltype"))
circleDef.setFillType(Integer.valueOf(attrs.getValue(1)));
} |
f02e1cf3-e3ab-41bd-82ea-c3a1bac60204 | 8 | public String strStr_BF(String haystack, String needle) {
if (haystack == null || needle == null)
return null;
char[] h = haystack.toCharArray(), n = needle.toCharArray();
if (h.length < n.length)
return null;
if (n.length == 0)
return haystack;
for (int i = 0; i + n.length <= h.length; i++) {
for (int j = 0; j < n.length; j++) {
if (n[j] != h[i + j])
break;
if (j == n.length - 1)
return haystack.substring(i);
}
}
return null;
} |
36eb1903-6590-4bbd-8dd3-9a9e0f2db389 | 2 | public static void equipWeapon(WeaponType type, CharacterSheet sheet) {
switch (type) {
case mel_sword:
sheet.atk_dmg = 10;
sheet.damageType = DamageType.SLASHING;
sheet.range = 1;
break;
case rng_bow:
sheet.atk_dmg = 8;
sheet.damageType = DamageType.PIERCING;
sheet.range = 10;
break;
}
} |
4ccc9c5b-3962-4156-bd6e-87218abe8420 | 5 | @Override
public void update(int delta) {
lifetime += delta;
if(type == ASTEROID)
y += 0.1f * delta;
if(first && lifetime >= MAX_LIFETIME)
isAlive = false;
if(lifetime >= MAX_LIFETIME){
lifetime = 0;
first = true;
if(type == PLAYER)
Game.getPlayer().hide();
}
} |
8750d0c1-3bb4-49f4-bd48-6d600b232194 | 6 | private void layoutHorizontal(int top, int bottom, int left, int right) {
int leftX = paddingLeft;
int height = bottom - top;
int childBottom = height - paddingBottom;
int availableHeight = height - paddingTop - paddingBottom;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.getVisibility().equals(Visibility.GONE)) {
int topY = 0;
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
LayoutParameters params = (LayoutParameters) child.getLayoutParameters();
int rawAlignment = params.getAlignment();
Alignment alignment = Alignment.getHorizontalAlignment(rawAlignment);
switch (alignment) {
case TOP:
topY = paddingTop + params.getTopMargin();
break;
case CENTER_VERTICAL:
topY = paddingTop + ((availableHeight - childHeight) / 2) + params.getTopMargin() - params.getBottomMargin();
if (params.centered) {
int width = right - left;
int availableWidth = width - paddingLeft - paddingRight;
leftX = paddingLeft + ((availableWidth - childWidth) / 2);
}
break;
case BOTTOM:
topY = childBottom - childHeight - params.getBottomMargin();
break;
default:
topY = paddingTop;
}
leftX += params.getLeftMargin();
setChildLayout(child, leftX, topY, childWidth, childHeight);
leftX += childWidth + params.getRightMargin();
}
}
} |
7e245c7d-1988-4537-bcbb-5917cd869a3d | 9 | private HashMap<Date, Double> readTideDataFromService() {
// Log a message
logger
.debug("readTideDataFromService called and params are currently :");
logger.debug("-> Location = " + tideLocation);
logger.debug("-> Location URL Fragment = " + tideLocationUrlFragment);
logger.debug("-> Start Date = " + startDateTime);
logger.debug("-> End Date = " + endDateTime);
logger.debug("-> Number of minutes between points = "
+ numberOfMinutesBetweenDataPoints);
// This is the HashMap that will be returned
HashMap<Date, Double> dataFromServices = new HashMap<Date, Double>();
// Create a Calendar that will hold the start time
Calendar dateRangeStartCal = Calendar.getInstance();
dateRangeStartCal.setTime(startDateTime);
// Create a matching Calendar that will hold the end time
Calendar dateRangeEndCal = Calendar.getInstance();
dateRangeEndCal.setTime(endDateTime);
// Let's open both ends of the range by a week to make sure we get
// enough data
dateRangeStartCal.add(Calendar.MINUTE, -2
* numberOfMinutesBetweenDataPoints);
dateRangeEndCal.add(Calendar.MINUTE,
(2 * numberOfMinutesBetweenDataPoints));
logger.debug("Opened the query window up to search between "
+ dateRangeStartCal.getTime() + " to "
+ dateRangeEndCal.getTime());
// Now we need to extract some information from the date range to build
// the correct URL
String startYear = dateRangeStartCal.get(Calendar.YEAR) + "";
String startMonth = (dateRangeStartCal.get(Calendar.MONTH) + 1) + "";
String startDay = dateRangeStartCal.get(Calendar.DAY_OF_MONTH) + "";
String startHour = dateRangeStartCal.get(Calendar.HOUR_OF_DAY) + "";
String startMin = dateRangeStartCal.get(Calendar.MINUTE) + "";
int numberOfDays = ((dateRangeEndCal.get(Calendar.YEAR) - dateRangeStartCal
.get(Calendar.YEAR)) * 365)
+ (dateRangeEndCal.get(Calendar.DAY_OF_YEAR) - (dateRangeStartCal
.get(Calendar.DAY_OF_YEAR)));
String glen = numberOfDays + "";
// Now create the URL that will read in the data from the web site
URL tideDataUrl = null;
try {
tideDataUrl = new URL("http://tbone.biol.sc.edu/tide/tideshow.cgi?"
+ "tplotdir=horiz;" + "gx=640;" + "gy=240;"
+ "caltype=ndp;" + "type=mrare;" + "interval=00%3A30;"
+ "glen="
+ glen
+ ";"
+ "fontsize=%2B0;"
+ "units=feet;"
+ "cleanout=1;"
+ "year="
+ startYear
+ ";"
+ "month="
+ startMonth
+ ";"
+ "day="
+ startDay
+ ";"
+ "hour="
+ startHour
+ ";"
+ "min="
+ startMin
+ ";"
+ "tzone=utc;"
+ "ampm24=24;"
+ "colortext=black;"
+ "colordatum=white;"
+ "colormsl=yellow;"
+ "colortics=red;"
+ "colorday=skyblue;"
+ "colornight=deep-%3Cbr%20%2F%3Eskyblue;"
+ "colorebb=seagreen;"
+ "colorflood=blue;"
+ "site="
+ tideLocationUrlFragment);
logger.debug("readTideDataFromService: URL to use: " + tideDataUrl);
} catch (MalformedURLException ex) {
logger
.error("MalforedURLException creating the URL to read tide data: "
+ ex.getMessage());
}
// Open a buffered reader to the URL
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(tideDataUrl
.openStream()));
} catch (IOException e) {
logger
.error("IOException caught trying to open "
+ "buffered reader to URL for tide data: "
+ e.getMessage());
}
// Compile some patterns to be used for matching and data extraction
// from the results
Pattern pattern = Pattern
.compile("^(\\d{4})-(\\d{2})-(\\d{2})\\s+(\\d{2}):(\\d{2})\\s+(\\S+)\\s+(-*\\d+\\.\\d+)$");
try {
// The line to be read
String inputLine = null;
// The variables (Strings) to be extracted
String year = null;
String month = null;
String day = null;
String hour = null;
String minute = null;
String zone = null;
String dataString = null;
// Loop over all lines read from the URL
while ((inputLine = in.readLine()) != null) {
// Check to see if a date can be pulled from the line
Matcher m = pattern.matcher(inputLine);
if (m.matches()) {
// Grab the year
year = m.group(1);
// Grab the month
month = m.group(2);
// Grab the day
day = m.group(3);
// Grab the hour
hour = m.group(4);
// Grab the minute
minute = m.group(5);
// Grab the timezone
zone = m.group(6);
// Grab the data
dataString = m.group(7);
// Create a calendar with the parsed information
Calendar dataPointCalendar = Calendar.getInstance();
// First grab the old timezone
String timeZoneID = dataPointCalendar.getTimeZone().getID();
// This calendar is now in local time, but the stuff read
// from the URL is in UTC. So, set the timezone to be UTC.
dataPointCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
// Now assign the values to the Calendar that were parsed
// from the line
dataPointCalendar
.set(Calendar.YEAR, Integer.parseInt(year));
dataPointCalendar.set(Calendar.MONTH, Integer
.parseInt(month) - 1);
dataPointCalendar.set(Calendar.DAY_OF_MONTH, Integer
.parseInt(day));
dataPointCalendar.set(Calendar.HOUR_OF_DAY, Integer
.parseInt(hour));
dataPointCalendar.set(Calendar.MINUTE, Integer
.parseInt(minute));
// Since seconds are not returned, zero them out
dataPointCalendar.set(Calendar.SECOND, 0);
// I have to call a get method here to make sure the changes
// in the date actually take. Seems very hackish, but hey,
// it works
dataPointCalendar.getTime();
// Construct the data point
Double tideDataPoint = null;
try {
tideDataPoint = new Double(dataString);
} catch (NumberFormatException e) {
logger.error("Read tide data point " + dataString
+ " but could not convert that to a Double: "
+ e.getMessage());
}
// Now add this to the local hashmap
if (tideDataPoint != null) {
dataFromServices.put(dataPointCalendar.getTime(),
tideDataPoint);
// Check against mins and max
if (tideDataPoint.doubleValue() > maxTide.doubleValue())
maxTide = tideDataPoint;
if (tideDataPoint.doubleValue() < minTide.doubleValue())
minTide = tideDataPoint;
}
}
}
} catch (IOException e) {
logger.error("IOException caught trying to read line from URL "
+ e.getMessage());
}
// Print some logger information at finish
logger.debug("Done with query and found " + dataFromServices.size()
+ " data points in the query results.");
logger.debug("After query:");
logger.debug("-> Minimum Tide = " + this.minTide);
logger.debug("-> Maximum Tide = " + this.maxTide);
// Return the result
return dataFromServices;
} |
97bdcc70-9a2b-4c4a-b4e5-2aedba43e8d5 | 0 | public void clickTutorial() {
System.out.println("Please choose characters that you would like to play with in this game.");
//Plus more info on how the game is played in itself
} |
ae3304dd-61bb-4a74-aedb-00eb80e0cb1e | 5 | static char getOption() {
System.out.print("\tChoose action: ");
System.out.print("(1) students at a school, ");
System.out.print("(2) shortest intro chain, ");
System.out.print("(3) cliques at school, ");
System.out.print("(4) connectors, ");
System.out.print("(q)uit? => ");
char response = stdin.next().toLowerCase().charAt(0);
while (response != '1' && response != '2' && response != '3' && response != '4' && response != 'q') {
System.out.print("\tYou must enter one of 1, 2, 3, 4, or q => ");
response = stdin.next().toLowerCase().charAt(0);
}
return response;
} |
291a601b-1c79-4687-aa46-42e1e55871a9 | 3 | public void setupMenu(){
edgeDetection = new JMenuItem("Edge Detector");
angle = new JMenuItem("Determine Angle");
threshold = new JMenuItem("Threshold");
topView = new JMenuItem("Add Top View");
lateralView = new JMenuItem("Add Lateral View");
frontView = new JMenuItem("Add Front View");
figureVoxels = new JMenuItem("Figure Voxels");
help = new JMenuItem("Help");
about = new JMenuItem("About");
testAll3D = new JMenuItem("Testing 3D chart");
//JMenuItem Event Code starts here
topView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int ret = fileChooser.showOpenDialog(null);
if(ret == JFileChooser.APPROVE_OPTION){
loadImage(fileChooser.getSelectedFile(), 0);
}
}
});
lateralView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int ret = fileChooser.showOpenDialog(null);
if(ret == JFileChooser.APPROVE_OPTION){
loadImage(fileChooser.getSelectedFile(), 1);
}
}
});
frontView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ret = fileChooser.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
loadImage(fileChooser.getSelectedFile(), 2);
}
}
});
figureVoxels.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
addAllCoordinates();
//System.out.println(allCoordinates.size());
figureVoxels();
System.out.println("Common Coordinates Size" + commonCoordinates.size());
}
});
threshold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}});
testAll3D.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("Adding All Coordinates...");
addAllCoordinates();
t1 = new Thread(new OpenChart(returnCommonCoordinates()));
System.out.println("Starting Thread");
t1.start();
/*
* Coord3d[] testy = new Coord3d[30000]; for(int i = 0; i <
* testy.length; i++){ testy[i] = new Coord3d(500, i + 60, 30 +
* i); } t1 = new Thread(new Testing(testy)); t1.start();
*/
}
});
getView.add(topView);
getView.add(lateralView);
getView.add(frontView);
fileMenu.add(figureVoxels);
fileMenu.add(testAll3D);
//imageMenu.add(edgeDetection);
imageMenu.add(threshold);
mathMenu.add(angle);
helpMenu.add(help);
helpMenu.add(about);
} |
c05257d3-a075-4185-89a2-fd8bc9bc8319 | 4 | public boolean peutCreerLien(ZElement elem1, ZElement elem2) {
return super.peutCreerLien(elem1, elem2)
&& (elem1 instanceof MCDAssociation
&& elem2 instanceof MCDEntite || elem2 instanceof MCDAssociation
&& elem1 instanceof MCDEntite);
} |
62ce5186-f52f-44a5-953d-b49da18a516a | 4 | public void propertyChange( PropertyChangeEvent evt )
{
if ( evt.getSource() == topPanel )
{
int hash = evt.getPropertyName().hashCode() ;
if ( hash == "reload".hashCode() )
{
loadOptions() ;
}
else if ( hash == "save".hashCode() )
{
saveOptions( true ) ; // save all settings from dialog
}
else if ( hash == "reset".hashCode() )
{
TGlobal.config.reset() ;
loadOptions() ;
}
}
} |
b579d614-8a76-4a33-99e4-ca109b6efa3a | 3 | public List<Double> run() {
List<Double> res = new Vector<Double>(ANN.outputNeuronCount);
for (Layer l : layers) {
for (Neuron n : l.getNeurons())
n.preCalc();
}
for (Neuron o : layers.get(layers.size() - 1).getNeurons()) {
res.add(o.getValue());
}
return res;
} |
40b4ea9c-baee-458d-a8bb-fd33b55582fc | 2 | public boolean equals(Vector3f r)
{
return m_x == r.GetX() && m_y == r.GetY() && m_z == r.GetZ();
} |
8dffb2fb-c401-4c3e-b398-4c970ac48e15 | 5 | public String toStringHtmlHeader() {
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>");
sb.append("<script type=\"text/javascript\"> google.load('visualization', '1', {packages: ['corechart']}); </script>\n");
sb.append("<script type=\"text/javascript\">\n");
sb.append("\tfunction draw_" + id + "() {\n");
sb.append("\t\tvar data = google.visualization.arrayToDataTable([\n");
// Column titles
sb.append("\t[ '' , ");
int i = 0;
for (String ct : columnTitltes) {
sb.append((i > 0 ? "," : "") + "'" + ct + "'");
i++;
}
sb.append("]\n");
// Date
int maxLen = maxColumnLength();
for (i = 0; i < maxLen; i++) {
// X labels
String lab = getXLabel(i);
if (lab != null) lab = "'" + lab + "'";
sb.append("\t,[ " + lab);
// Data
for (int j = 0; j < columns.size(); j++)
sb.append("," + getValue(i, j));
sb.append("]\n");
}
sb.append("\t\t]);\n");
sb.append("\t\tvar ac = new google.visualization.AreaChart(document.getElementById('visualization_" + id + "'));\n");
sb.append("\t\tac.draw(data, { title : '" + title + "', isStacked: " + stacked + ", width: " + width + ", height: " + height + ", vAxis: {title: \"" + vAxis + "\"}, hAxis: {title: \"" + hAxis + "\"} });\n");
sb.append("\t\t}\n");
sb.append("\tgoogle.setOnLoadCallback(draw_" + id + ");\n");
sb.append("</script>\n");
sb.append("\n");
return sb.toString();
} |
fa8efb8b-d66d-406a-9e96-c9f60e240ee5 | 5 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Posizione other = (Posizione) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
} |
268e26bd-9e85-4af1-b309-27fa2098ac80 | 3 | public void DnaSequenceBaseAt(int len) {
// Create a random sequence
char bases[] = new char[len];
for (int i = 0; i < bases.length; i++) {
char base = GprSeq.BASES[(int) (Math.random() * 4)];
bases[i] = base;
}
String sequence = new String(bases);
DnaSequence DnaSequence = new DnaSequence(sequence);
System.out.println("DnaSequence (len:" + len + ") : " + DnaSequence);
for (int i = 0; i < bases.length; i++) {
char base = Character.toUpperCase(DnaSequence.getBase(i));
if (base != bases[i]) throw new RuntimeException("Bases do not match! Base:" + base + "\tOriginal sequence: " + bases[i]);
}
} |
e7d7dc89-dcf8-4a1c-adca-072fc02861a9 | 7 | public void Solve() {
List<Integer> primes = Euler.GetPrimes(_max);
int longestSequence = 0;
int startSequenceIndex = 0;
for (int startIndex = 0; startIndex < primes.size(); startIndex++) {
int currentNumber = primes.get(startIndex);
for (int endIndex = startIndex + 1; endIndex < primes.size(); endIndex++) {
currentNumber += primes.get(endIndex);
if (_max <= currentNumber) {
break;
} else if (0 <= Collections.binarySearch(primes, currentNumber)) {
if (longestSequence < endIndex - startIndex + 1) {
longestSequence = endIndex - startIndex + 1;
startSequenceIndex = startIndex;
System.out.println("StartIndex=" + startSequenceIndex + ", Terms=" + longestSequence);
}
}
}
}
System.out.print("Result= " + longestSequence + " terms: ");
int sum = 0;
for (int i = startSequenceIndex; i < startSequenceIndex + longestSequence; i++) {
sum += primes.get(i);
System.out.print(primes.get(i));
if (i != startSequenceIndex + longestSequence - 1) {
System.out.print(" + ");
}
}
System.out.println(" = " + sum);
} |
babb68b4-9992-4799-b6cb-1d417607a79b | 7 | private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
} |
c79c3b97-940b-47dd-ad97-083365da1ebc | 5 | public void run() {
try {
JavaDBAccess = new DatabaseAccess(props);
TARGET_PHP_FILES_RUNS_FUNCTIONS_ID = 0;
long startTime = System.currentTimeMillis();
// client streams (make sure you're using streams that use
// byte arrays, so things like GIF and JPEG files and file
// downloads will transfer properly)
BufferedInputStream clientIn = new BufferedInputStream(pSocket.getInputStream());
BufferedOutputStream clientOut = new BufferedOutputStream(pSocket.getOutputStream());
// the socket to the remote server
Socket server = null;
// other variables
byte[] request = null;
byte[] response = null;
int requestLength = 0;
int responseLength = 0;
int pos = -1;
StringBuffer host = new StringBuffer("");
String hostName = "";
int hostPort = 80;
// get the header info (the web browser won't disconnect after
// it's sent a request, so make sure the waitForDisconnect
// parameter is false)
request = getHTTPData(clientIn, host, false);
requestLength = Array.getLength(request);
// debugOut.println("------------start-----------------");
// String line = new String(request, 0, requestLength);
// debugOut.println(line);
// debugOut.println("------------end-----------------");
// separate the host name from the host port, if necessary
// (like if it's "servername:8000")
hostName = host.toString();
pos = hostName.indexOf(":");
if (pos > 0) {
try {
hostPort = Integer.parseInt(hostName.substring(pos + 1));
} catch (Exception e) {
}
hostName = hostName.substring(0, pos);
}
// either forward this request to another proxy server or
// send it straight to the Host
try {
if ((fwdServer.length() > 0) && (fwdPort > 0)) {
server = new Socket(fwdServer, fwdPort);
} else {
server = new Socket(hostName, hostPort);
}
} catch (Exception e) {
// tell the client there was an error
String errMsg = "HTTP/1.0 500\nContent Type: text/plain\n\n" +
"Error connecting to the server:\n" + e + "\n";
clientOut.write(errMsg.getBytes(), 0, errMsg.length());
}
if (server != null) {
server.setSoTimeout(socketTimeout);
BufferedInputStream serverIn = new BufferedInputStream(server.getInputStream());
BufferedOutputStream serverOut = new BufferedOutputStream(server.getOutputStream());
// send the request out
serverOut.write(request, 0, requestLength);
serverOut.flush();
// and get the response; if we're not at a debug level that
// requires us to return the data in the response, just stream
// it back to the client to save ourselves from having to
// create and destroy an unnecessary byte array. Also, we
// should set the waitForDisconnect parameter to 'true',
// because some servers (like Google) don't always set the
// Content-Length header field, so we have to listen until
// they decide to disconnect (or the connection times out).
if (debugLevel > 1) {
response = getHTTPData(serverIn, true);
responseLength = Array.getLength(response);
} else {
responseLength = streamHTTPData(serverIn, clientOut, true);
}
serverIn.close();
serverOut.close();
}
// send the response back to the client, if we haven't already
if (debugLevel > 1) {
clientOut.write(response, 0, responseLength); // if the user wants debug info, send them debug info; however,
// keep in mind that because we're using threads, the output won't
// necessarily be synchronous
}
if (debugLevel > 0) {
long endTime = System.currentTimeMillis();
debugOut.println("Request from " + pSocket.getInetAddress().getHostAddress() +
" on Port " + pSocket.getLocalPort() +
" to host " + hostName + ":" + hostPort +
"\n (" + requestLength + " bytes sent, " +
responseLength + " bytes returned, " +
Long.toString(endTime - startTime) + " ms elapsed)");
debugOut.flush();
}
if (debugLevel > 1) {
debugOut.println("REQUEST:\n" + (new String(request)));
debugOut.println("RESPONSE:\n" + (new String(response)));
debugOut.flush();
}
// close all the client streams so we can listen again
clientOut.close();
clientIn.close();
pSocket.close();
} catch (Exception e) {
if (debugLevel > 0) {
debugOut.println("Error in ProxyThread: " + e);
//e.printStackTrace();
}
}
} |
74ca662b-2e52-43a4-b941-c6ee29191b16 | 5 | private void handleKey(SelectionKey key) throws IOException{
// dealing with canceled keys
if( ! key.isValid() ){
return;
}
KeyAttachment attach = ((KeyAttachment) key.attachment());
IoHandler handler = attach.handler;
if( key.isAcceptable() ){
handler.accept(key);
// keys that are acceptable will not be any of the other things
return;
}
if( key.isConnectable() ){
handler.connect(key);
}
if( key.isWritable() ){
handler.write(key);
}
if( key.isReadable() ){
handler.read(key);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.