method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
977d2141-b8ca-4553-8edf-c57a1bfaf8d3 | 5 | public void insert(String in)
{
if(this.isEmpty())
{
Nodes dataList = new Nodes(in);
head = dataList;
}
else if(in.compareTo(this.getData(numberOfItems - 1)) >= 0)
{
Nodes prev = search(numberOfItems - 1);
Nodes newItem = new Nodes(in);
prev.next = newItem;
}
else if(in.compareTo(this.getData(0)) <= 0)
{
Nodes newItem = new Nodes(in, head);
head = newItem;
}
else
{
for(int j = 1; j < numberOfItems; j++)
{
if(in.compareTo(this.getData(j)) <= 0)
{
Nodes prev = search(j - 1);
Nodes newItem = new Nodes(in, prev.next);
prev.next = newItem;
break;
}
}
}
numberOfItems++;
} |
2d5c5707-9c30-4fc6-a52d-fb3c9f5d1cf1 | 6 | public void close() throws IOException {
if ( this.mBufferedOutputStream != null ) {
boolean delete = false;
try (BufferedInputStream input = new BufferedInputStream( new FileInputStream( this.mTempFile ) )) {
this.mBufferedOutputStream.flush();
this.mBufferedOutputStream.close();
((WaveFileHeader) this.mHeader).read( input );
((WaveFileHeader) this.mHeader).setNumBytes( this.mBytesWritten );
createEmptyFile( this.mFile );
delete = true;
this.mBufferedOutputStream = new BufferedOutputStream( new FileOutputStream( this.mFile ) );
int bytesRead = 0;
byte[] data = new byte[BUFFER_SIZE];
this.mHeader.write( this.mBufferedOutputStream );
while ( (bytesRead = input.read( data, 0, BUFFER_SIZE )) != -1 ) {
this.write( data, 0, bytesRead );
}
}
catch (IOException e) {
//only delete if a new file has been written over a possible old file
if ( delete ) {
if ( !this.mTempFile.delete() ) {
throw new IOException( "couldn't delete failure file", e );
}
}
throw e;
}
finally {
this.mClosed = true;
// No need to flush, is included in close().
try {
this.mBufferedOutputStream.close();
this.mBufferedOutputStream = null;
}
finally {
if ( !this.mTempFile.delete() ) {
throw new IOException( "couldn't delete the tempfile" );
}
}
}
}
} |
6cc500ef-6af1-4801-993f-ef058642b337 | 1 | public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + "), ";
} |
139b35bd-8ed3-41d7-964d-fd0066d34d89 | 7 | @SuppressWarnings("resource")
public void menu(DataSource ds) {
while (true) {
try {
System.out.println("Main Menu");
System.out.println("1.Prescribing New Medication");
System.out.println("2.Medical Test Update");
System.out.println("3.Patient Information Update");
System.out.println("4.Search Engine");
System.out.println("0.Exit");
System.out.print("Option: ");
Scanner input = new Scanner(System.in);
int userInput = input.nextInt();
switch (userInput) {
case 1:
/*
* Prescribing new medication -----------------------------
* This component allows a user to enter the detailed
* information about the prescription: the employee_no of
* the doctor who prescribes the test, the test name, the
* name and/or the health_care_no of the patient.
*/
System.out.println("1.Prescribing New Medication");
Prescription prescription = new Prescription(ds);
break;
case 2:
System.out.println("2.Medical Test Update");
MedicalTestUpdate mtu = new MedicalTestUpdate(ds);
break;
case 3:
/*
* Patient Information Update --------------------------
* This component is used to enter the information of a new
* patient or to update the information of an existing
* patient. All the information about a patient, except the
* health_care_no for an existing patient, may be updated.
*/
System.out.println("3.Patient Information Update");
PatientInformation patientInformation = new PatientInformation(
ds);
break;
case 4:
System.out.println("4.Search Engine");
SearchEngine searchEngine = new SearchEngine(ds);
break;
case 0:
System.out.println("0.Exit");
// terminate program
ds.closeConnection();
System.out.println("Goodbye.");
System.exit(0);
break;
}
} catch (Exception e) {
}
}
} |
74ad9bf1-43e4-4762-9897-0b39fad6fd9f | 2 | public void disposeShaders() {
if (vert != 0) {
GL20.glDetachShader(getID(), vert);
GL20.glDeleteShader(vert);
vert = 0;
}
if (frag != 0) {
GL20.glDetachShader(getID(), frag);
GL20.glDeleteShader(frag);
frag = 0;
}
} |
aedee889-5b64-40a3-bd82-882d13172249 | 5 | public void DrawNumbersToInstantiate(Graphics gr)
{
int numberX = numberInstantiateX;
int numberY = numberInstantiateY;
int numerToPrint = 1;
float tempDrawX = numberX;
int drawX = (int) tempDrawX;
Stroke stroke = new BasicStroke(2);
((Graphics2D) gr).setStroke(stroke);
gr.setColor(Color.black);
for(int i = 0; i<2;i++)
{
for(int j = 0; j<GameController.sudokuSize/2;j++)
{
gr.drawRect(drawX, numberY, (int)deltaX, (int)deltaY);
if (numerToPrint < 10) {
gr.drawString(String.valueOf(numerToPrint), (int)(drawX + deltaX / 2) - 2, (int)(numberY + deltaY) - 10);
} else {
gr.drawString(String.valueOf(numerToPrint), (int)(drawX + deltaX / 2) - 5, (int)(numberY + deltaY) - 10);
}
tempDrawX += deltaX;
drawX = (int) tempDrawX;
numerToPrint++;
}
numberY += deltaY;
tempDrawX = numberX;
drawX = (int) tempDrawX;
}
if(mouseOverDomainIndex != -1)
{
System.out.println("mouseOverDomainIndex: " + mouseOverDomainIndex);
gr.setColor(ClientGameController.mouseOverColor);
if(mouseOverDomainIndex < 8) {
gr.drawRect((int)(numberInstantiateX + mouseOverDomainIndex * deltaX), numberInstantiateY, (int) deltaX, (int) deltaY);
} else {
gr.drawRect((int)(numberInstantiateX + (mouseOverDomainIndex - 8) * deltaX), (int) (numberInstantiateY + deltaY), (int) deltaX, (int) deltaY);
}
}
} |
86d01035-7ef7-4f6f-a4fe-2322409aeeb4 | 5 | public boolean validateMove(String pieceID, int fromPosition, int toPosition, int fromPosition2, int toPosition2) {
boolean valid;
if (currentCard.getRank() == 7){
if (valid = board.validateMove(currentCard.getRank(), pieceID, fromPosition, toPosition, fromPosition2, toPosition2)){
board.makeMove(currentCard.getRank(), pieceID, fromPosition, toPosition);
if (fromPosition2 != 0 && toPosition2 != 0){
board.makeMove(currentCard.getRank(), pieceID, fromPosition2, toPosition2);
}
}
}
else{
if (valid = board.validateMove(currentCard.getRank(), pieceID, fromPosition, toPosition, 0, 0)){
board.makeMove(currentCard.getRank(), pieceID, fromPosition, toPosition);
}
}
return valid;
} |
56a7caa3-995b-491c-a12a-54778f5f2a73 | 1 | public static void main(String[] args)
{
int p[] = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
int n = 10;
BURodCutting bu = new BURodCutting(n, p);
System.out.println("Read as, Length of Rod : Cuts : Maximal Revenue");
for (int i = 1; i <= bu.n; i++)
System.out.println(i + " : " + bu.cuts[i] + " : " + bu.r[i]);
} |
112d45a6-2180-44bf-9d1c-2ce6c95788e5 | 1 | public void raise(int x, int y) {
_map[y][x] += 256;
if (_map[y][x] > 1024) _map[y][x] = 100000;
} |
375b15ff-efdd-4c9d-a924-a231c1df3175 | 3 | @Override
public final Store findStore(String storeNo){
Store storeFound = null;
for(int i = 0; i < stores.length; i++){
if (storeNo.equals(stores[i].getStoreNo())){
storeFound = stores[i];
break;
}
}
if(storeFound == null) {
throw new IllegalArgumentException();
}
return storeFound;
} |
1634fb49-c44a-4b8d-b47e-4288b754d7d8 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Solido other = (Solido) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.juego, other.juego)) {
return false;
}
if (!Objects.equals(this.nombre, other.nombre)) {
return false;
}
return true;
} |
339f18cd-d502-451f-bc1b-50c9e34daebf | 6 | @Override
public WriteMsg write(FileContent data) throws RemoteException, IOException {
String fileName = data.getFileName();
// check if this is a commit acknowledgment
if (data.getData() == null) {
synchronized (this) {
ReplicaLoc[] locations = locMap.get(fileName);
metaDataWriter.write(fileName);
for (int i = 0; i < locations.length; i++) {
metaDataWriter.write(" " + locations[i].getName());
}
metaDataWriter.write("\n");
metaDataWriter.flush();
}
return null;
} else {
// This step guarantees that clients who request same file reach out
// the
// primary replica in the order which they obtain their transaction
// id's
Lock lock = null;
try {
if (!fileLock.containsKey(fileName)) {
lock = new ReentrantLock();
fileLock.put(fileName, lock);
} else {
lock = fileLock.get(fileName);
}
lock.lock();
int tId = txnID.incrementAndGet();
int ts = timeStamp.incrementAndGet();
ReplicaLoc[] locations = null;
if (locMap.containsKey(fileName)) {
locations = locMap.get(fileName);
} else {
locations = selectRandomReplicas();
}
locMap.put(fileName, locations);
ReplicaLoc primary = locations[0];
ReplicaServerClientInterface primaryServer = null;
try {
primaryServer = (ReplicaServerClientInterface) LocateRegistry
.getRegistry(primary.getHost(), primary.getPort())
.lookup(primary.getName());
} catch (Exception e) {
}
primaryServer.write(tId, 1, data);
return new WriteMsg(tId, ts, primary);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
lock.unlock();
}
}
} |
26347f75-9164-48dc-83b4-fa78bb8524ee | 5 | public static void readMappings(InputMap im) {
Preferences bindings = PREFS.node("bindings"); //$NON-NLS-1$
try {
boolean changed = false;
for (String key : bindings.keys()) {
String act = bindings.get(key, null);
if (act != null) {
changed = true;
im.put(JoshText.key(key), act);
}
}
if (changed) {
return;
}
} catch (BackingStoreException e) {
System.err.println("Failed to read JoshEdit keybindings!"); //$NON-NLS-1$
}
for (String key : DEFAULTS.keySet()) {
String act = DEFAULTS.getString(key);
im.put(JoshText.key(key), act);
}
} |
e3288c04-c55a-4902-a674-b4852ef7984a | 4 | private boolean isLocationInPicture(int column, int row)
{
boolean result = false; // the default is false
if (column >= 0 && column < picture.getWidth() &&
row >= 0 && row < picture.getHeight())
result = true;
return result;
} |
e763d81a-f167-47ed-9ca2-9e2e512bd5ac | 8 | public Boolean isPermtation( String string1, String string2) {
if (string1 == null && string2 == null) {
return true;
} else if(string1 == null && string2 !=null) {
return false;
} else if(string2 == null && string1 !=null){
return false;
} else {
if (string1.length()!=string2.length()){
return false;
}
char[] string1Array1 = string1.toCharArray();
char[] string1Array2 = string2.toCharArray();
Arrays.sort(string1Array1);
Arrays.sort(string1Array2);
String sortedString1 = new String(string1Array1);
String sortedString2 = new String(string1Array2);
if (sortedString1.equals(sortedString2)){
return true;
} else
{
return false;
}
}
} |
f9f32b01-95c2-4333-b7f2-c251c1a9c88a | 5 | @Override
public void onDisable() {
if(!restarting) {
if(config.getBoolean(ServerRestarterConfigNodes.CREATE_STATE_FILE)) {
File file = new File(config.getString(ServerRestarterConfigNodes.STATE_FILE));
if(file.isDirectory())
getLogger().severe("Status file is a directory!");
if(file.exists() && !file.delete())
getLogger().severe("Unable to delete status file!");
}
}
getLogger().info("ServerRestarter unloaded.");
} |
a7246992-e576-4455-a94c-0cc763a06f1d | 7 | public void init()
{
Context.initialize();
// Create a Session
_session = Session.acquire(CommandLine.variable("session"));
if (_session == null)
{
System.out.println("Could not acquire session.");
Context.uninitialize();
System.exit(1);
}
System.out.println("RFA Version: " + Context.getRFAVersionInfo().getProductVersion());
// Create an Event Queue
_eventQueue = EventQueue.create("myEventQueue");
// Create a OMMPool.
_pool = OMMPool.create();
// Create an OMMEncoder
_encoder = _pool.acquireEncoder();
_encoder.initialize(OMMTypes.MSG, 5000);
// Initialize client for login domain.
_loginClient = new LoginClient(this);
_directoryClient = new DirectoryClient(this);
if (_loginClient == null || _directoryClient == null)
{
System.out.println("ERROR:" + _className
+ " failed to create LoginClient / DirectoryClient");
cleanup(-1);
}
// Create an OMMConsumer event source
_ommConsumer = (OMMConsumer)_session.createEventSource(EventSource.OMM_CONSUMER,
"myOMMConsumer", true);
// Load dictionary from files in to FieldDictionary, if the files have
// been specified.
String fieldDictionaryFilename = CommandLine.variable("rdmFieldDictionary");
String enumDictionaryFilename = CommandLine.variable("enumType");
if ((fieldDictionaryFilename.length() > 0) && (enumDictionaryFilename.length() > 0))
{
try
{
_localDictionary = FieldDictionary.create();
FieldDictionary.readRDMFieldDictionary(_localDictionary, fieldDictionaryFilename);
System.out.println(_className + ": " + fieldDictionaryFilename + " is loaded.");
FieldDictionary.readEnumTypeDef(_localDictionary, enumDictionaryFilename);
System.out.println(_className + ": " + enumDictionaryFilename + " is loaded.");
printLocalDictionaryInfo();
}
catch (DictionaryException ex)
{
_localDictionary = null;
System.out.println("ERROR: " + _className
+ " unable to initialize dictionary from file.");
System.out.println(ex.getMessage());
if (ex.getCause() != null)
System.err.println(": " + ex.getCause().getMessage());
System.out.println(_className
+ " will continue download dictionary from server soon.");
}
}
// Send login request
// Application must send login request first
_loginClient.sendRequest();
} |
8de10594-0444-491f-9dce-c1253a8c566d | 7 | void getNeighbors() {
neighborCount = 0;
if (disregardNeighbors)
return;
AtomIterator iter =
frame.getWithinModelIterator(atomI, radiusI + diameterP +
maxRadius);
while (iter.hasNext()) {
Atom neighbor = iter.next();
if (neighbor == atomI)
continue;
// only consider selected neighbors
if (onlySelectedDots && !bsOn.get(neighbor.atomIndex))
continue;
float neighborRadius = getAppropriateRadius(neighbor);
if (centerI.distance(neighbor) >
radiusI + radiusP + radiusP + neighborRadius)
continue;
if (neighborCount == neighbors.length) {
neighbors = (Atom[])ArrayUtil.doubleLength(neighbors);
neighborIndices = ArrayUtil.doubleLength(neighborIndices);
neighborCenters = (Point3f[])ArrayUtil.doubleLength(neighborCenters);
neighborPlusProbeRadii2 = ArrayUtil.doubleLength(neighborPlusProbeRadii2);
neighborRadii2 = ArrayUtil.doubleLength(neighborRadii2);
}
neighbors[neighborCount] = neighbor;
neighborCenters[neighborCount] = neighbor;
neighborIndices[neighborCount] = neighbor.atomIndex;
float neighborPlusProbeRadii = neighborRadius + radiusP;
neighborPlusProbeRadii2[neighborCount] =
neighborPlusProbeRadii * neighborPlusProbeRadii;
neighborRadii2[neighborCount] =
neighborRadius * neighborRadius;
++neighborCount;
}
} |
efb98a86-18f4-4257-8239-bedca00654f2 | 1 | private void addOximata(){
/*
* vazei ta oximata tis vashs sthn lista
*/
ArrayList<String> oximata=con.getOximata();
for(int i=0;i<oximata.size();i++){
listModel.addElement(oximata.get(i));
}
} |
ef03dcf2-e773-4696-aaab-40327f05f5f7 | 8 | private static boolean isLongFilename( String filename )
{
if( filename.charAt( 0 ) == '.' || filename.charAt( filename.length() - 1 ) == '.' )
return true;
if( !filename.matches( "^\\p{ASCII}+$" ) )
return true;
// no matter whether it is file or directory
int dotIdx = filename.lastIndexOf( '.' );
String baseName = dotIdx == -1 ? filename : filename.substring( 0, dotIdx );
String ext = dotIdx == -1 ? "" : filename.substring( dotIdx + 1 );
String wrongSymbolsPattern = ".*[\\.\"\\/\\\\\\[\\]:;=, ]+.*";
return baseName.length() > 8 || ext.length() > 3 || baseName.matches( wrongSymbolsPattern ) || ext.matches( wrongSymbolsPattern );
} |
cfe874f7-381f-4370-a765-adaee12f7f0d | 1 | public void imLis(ArrayList<ConstansToken> g) {
for (ConstansToken g1 : g) {
System.out.println(g1.getSimbolo() + " " + g1.getMatch() + " " + g1.getValor());
}
} |
a562d372-0796-49ce-856f-4db2fe1e61a8 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
1b3dbfa9-beb0-490c-b1f1-b2303f72d90b | 6 | public void step(SimState state) {
Sim.instance().clearOGroups();
Bag freshmen = new Bag();
for(int i = 0; i < Sim.FRESHMAN_CLASS_SIZE; i++){
Student.Race race;
Student.Gender gender;
float racePercent = Sim.instance().random.nextFloat();
if(racePercent>Sim.PROB_MINORITY){
race = Student.Race.WHITE;
}else{
race = Student.Race.MINORITY;
}
double gpa = Sim.instance().random.nextDouble()+(Sim.instance().random.nextInt(3)+1);
float genderPercent = Sim.instance().random.nextFloat();
if(genderPercent < .65){
gender = Student.Gender.FEMALE;
}
else{
gender = Student.Gender.MALE;
}
Student student = new Student(gender,1,gpa,race);
//give student attributes
for(int x=0; x<Sim.instance().NUM_PERSONALITY_ATTRIBUTES; x++){
float attrPercent = state.random.nextFloat();
if(attrPercent<Sim.PROB_ATTRIBUTE){
student.addAttribute(x);
}
}
//assign student to O Group
Sim.instance().assignOGroup(student);
freshmen.add(student);
state.schedule.scheduleOnceIn(1/12.0,student);
}
if(Sim.instance().HOUSING_BY_RACE){
FreshmanHousingSelection.instance().assignByRace(freshmen);
} else {
FreshmanHousingSelection.instance().assign(freshmen);
}
Sim.instance().addStudents(freshmen);
state.schedule.scheduleOnceIn(1, this);
} |
8c2858fc-3d0a-4bfa-a0da-2042fc647916 | 4 | @Override
public void run() {
while(true) {
try {
Socket socket = server.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = inFromClient.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
NetworkMessage message = NetworkMessage.parse(text);
message.setSender(socket.getInetAddress());
message.setReceiver(Network.getLocalAddress());
//System.out.println("DOWNLOAD");
switch (message.type){
case NetworkMessage.TYPE_FILE:
System.out.println("DOWNLOADING IN");
String[] s = message.content.split(",");
inFromClient.close();
//server.close();
socket = server.accept();
message.content=download( s[0], socket);
message.setType(8);
break;
default:
break;
}
//Evento
setChanged();
notifyObservers(message);
}
catch(Exception e) {
System.err.println("Connection error receiving message \n"+e.getMessage());
}
}
} |
55af9de4-8330-401a-b0cc-47f6c5c8659c | 0 | public void setMessageAuthScheme(SignatureMethodType value) {
this.messageAuthScheme = value;
} |
80c521e4-5ef1-4199-8a3c-ff0814063059 | 5 | public static void getHelp(Player p, String page) {
int pg = 1;
int tpg = getTotallHelpPG();
if (!page.equalsIgnoreCase("")) {
try {
pg = Integer.parseInt(page);
} catch (Exception e) {
MessageManager.getInstance().error(p, page + " is not a number");
return;
}
}
if (pg > tpg) {
pg = 1;
}
int start = (pg * 4) - 4;
int end = (pg * 4);
if (end > cmd.size()) {
end = cmd.size();
}
List<String> sub = cmd.subList(start, end);
MessageManager.getInstance().sendMessage(
p,
ChatColor.RED + "------------===== " + ChatColor.GREEN + "" + ChatColor.BOLD + "page " + pg + "/" + tpg + ChatColor.RED
+ " =====------------");
for (String s : sub) {
MessageManager.getInstance().sendMessage(p, ChatColor.GOLD + s);
}
} |
03a5990d-b5c2-45ff-a171-992836e0289d | 1 | @Override
public String getPotentialContentSizeChangeActionCommand() {
if (mOutlineToProxy != null) {
return mOutlineToProxy.getPotentialContentSizeChangeActionCommand();
}
return super.getPotentialContentSizeChangeActionCommand();
} |
70ef186b-dd41-46aa-9965-a9cbf0c31183 | 2 | @Override
public int compareTo(AstronomicalObject o) {
return (this.mass < o.mass) ? -1 : (this.mass > o.mass) ? 1 : 0;
} |
2aace461-1a02-42dc-8be4-b9f93ccc3f6a | 8 | public static void multTransA_small( RowD1Matrix64F A , D1Matrix64F B , D1Matrix64F C )
{
if( C.numCols != 1 ) {
throw new MatrixDimensionException("C is not a column vector");
} else if( C.numRows != A.numCols ) {
throw new MatrixDimensionException("C is not the expected length");
}
if( B.numRows == 1 ) {
if( A.numRows != B.numCols ) {
throw new MatrixDimensionException("A and B are not compatible");
}
} else if( B.numCols == 1 ) {
if( A.numRows != B.numRows ) {
throw new MatrixDimensionException("A and B are not compatible");
}
} else {
throw new MatrixDimensionException("B is not a vector");
}
int cIndex = 0;
for( int i = 0; i < A.numCols; i++ ) {
double total = 0.0;
int indexA = i;
for( int j = 0; j < A.numRows; j++ ) {
total += A.get(indexA) * B.get(j);
indexA += A.numCols;
}
C.set(cIndex++ , total);
}
} |
a1c07204-6fe3-4348-9465-9d73fbf7ff8b | 9 | protected static Ptg calcRows( Ptg[] operands ) throws FunctionNotSupportedException
{
try
{
int rsz = 0;
if( operands[0] instanceof PtgStr )
{
String rangestr = operands[0].getValue().toString();
String startx = rangestr.substring( 0, rangestr.indexOf( ":" ) );
String endx = rangestr.substring( rangestr.indexOf( ":" ) + 1 );
int[] startints = ExcelTools.getRowColFromString( startx );
int[] endints = ExcelTools.getRowColFromString( endx );
rsz = endints[0] - startints[0];
rsz++; // inclusive
}
else if( operands[0] instanceof PtgName )
{
int[] rc = ExcelTools.getRangeCoords( operands[0].getLocation() );
rsz = rc[2] - rc[0];
rsz++; // inclusive
}
else if( operands[0] instanceof PtgRef )
{
int[] rc = ExcelTools.getRangeCoords( ((PtgRef) operands[0]).getLocation() );
rsz = rc[2] - rc[0];
rsz++; // inclusive
}
else if( operands[0] instanceof PtgMemFunc )
{
Ptg[] p = operands[0].getComponents();
if( (p != null) && (p.length > 0) )
{
int[] rc0 = p[0].getIntLocation();
int[] rc1 = null;
if( p.length > 1 )
{
rc1 = p[p.length - 1].getIntLocation();
}
if( rc1 == null )
{
rsz = 0;
}
else
{
rsz = rc1[0] - rc0[0];
}
rsz++;
}
else
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
}
else
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
return new PtgInt( rsz );
}
catch( Exception e )
{
}
return new PtgErr( PtgErr.ERROR_VALUE );
} |
d95fb5e7-02ff-454b-a9fb-3f586d5e042a | 4 | public void stopDiagonal(int otherX, int otherY) {
if (c.freezeDelay > 0)
return;
if (c.freezeTimer > 0) //player can't move
return;
c.newWalkCmdSteps = 1;
int xMove = otherX - c.getX();
int yMove = 0;
if (xMove == 0)
yMove = otherY - c.getY();
/*if (!clipHor) {
yMove = 0;
} else if (!clipVer) {
xMove = 0;
}*/
int k = c.getX() + xMove;
k -= c.mapRegionX * 8;
c.getNewWalkCmdX()[0] = c.getNewWalkCmdY()[0] = 0;
int l = c.getY() + yMove;
l -= c.mapRegionY * 8;
for(int n = 0; n < c.newWalkCmdSteps; n++) {
c.getNewWalkCmdX()[n] += k;
c.getNewWalkCmdY()[n] += l;
}
} |
ab06777b-b65f-426c-b7e2-12d8e245271a | 2 | private static boolean doesListContain(String value, List<String> names){
boolean contains = false;
for(String name : names)
{
if (name.contains(value))
contains = true;
}
return contains;
} |
90026dc3-8300-4e66-b85d-0fb9845196a8 | 5 | @EventHandler
public void onBlockPistonExtend(final BlockPistonExtendEvent event){
BlockFace facing = event.getDirection();
if (plugin.gates.isGate(event.getBlock().getRelative(facing))){
plugin.verbose("Piston tried to mess with a KonseptGate by pushing it! BOO!!");
event.setCancelled(true);
}
else {
for (Block affected : event.getBlocks()){
if (plugin.gates.isGate(affected)){
// Yeah, this doesn't work because of a bug.
// I'll leave it in here as it will "take over" when that bug is fixed.
plugin.verbose("Piston tried to mess with a KonseptGate! BOO!!");
event.setCancelled(true);
break;
}
else if (plugin.gates.isGate(affected.getRelative(facing))){
plugin.verbose("Piston tried to mess with a KonseptGate by proxy! BOO!!");
event.setCancelled(true);
break;
}
else if (plugin.gates.isGate(affected.getRelative(BlockFace.UP))){
plugin.verbose("Piston tried to mess with the block below a KonseptGate! BOO!!");
event.setCancelled(true);
break;
}
}
}
} |
eb25268e-d5b1-4ad9-b5e9-5531b48daf8b | 5 | public static void main(String[]args){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int d1 = in.nextInt();
int d2 = in.nextInt();
int work = d1*n;
int z = work/d2+((work%d2>0)?1:0);
for (int i = 1 ; i < d2 ; i++ ){
if (work > 0)
out.print(Math.min(z,work)+" ");
else
out.print(0 +" ");
work = (work - z<0)?0:work-z;
}
out.print((work>0)?work:0);
out.flush();
} |
1ce0ce22-439d-4eb7-9643-f4797072820f | 5 | @Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<tr><td colspan ='3'>");
sb.append("<h3>Experience: ").append(getTitle()+"</h3><br />");
sb.append("Created by: ").append(getCreator()+"<br />");
if(isShared()){
TimelineResource res = new TimelineResource();
sb.append("The experience is shared with: ").append(res.getGroup(getSharingGroup()).getName()+"<br />");
}
sb.append("</td></tr>");
if(events.size()>0){
sb.append("<tr><td colspan ='3'>");
sb.append("<h2><b><font size=12>"+events.size()+"</font></b> events:</h2>");
sb.append("</td></tr>");
int coloumnCounter = 0;
sb.append("<tr>");
for (Event e : events) {
if(coloumnCounter<3){
sb.append(e.toString());
coloumnCounter++;
}else{
sb.append("</tr><tr>");
sb.append(e.toString());
coloumnCounter=1;
}
}
//To make the table "complete"
for (int i = coloumnCounter; i < 3; i++) {
sb.append("<td/>");
}
sb.append("</tr>");
}
sb.append("<tr><td colspan ='3'>");
sb.append("<hr>");
sb.append("</td></tr>");
return sb.toString();
} |
895bf027-281c-460d-a3ee-444d1724b7dc | 4 | public static HashMap unpack(ByteBuffer buf)
{
HashMap data = new HashMap();
int index = 0;
while (buf.hasRemaining())
{
switch (buf.getInt())
{
case 0:
int valui = buf.getInt();
data.put(index, valui);
System.out.println(valui);
break;
case 1:
double valud = buf.getDouble();
System.out.println(valud);
data.put(index, valud);
break;
case 2:
int size = buf.getInt();
byte[] string = new byte[size];
buf.get(string);
String valus = new String(string);
System.out.println(valus);
data.put(index, valus);
break;
}
index++;
}
buf.rewind();
return data;
} |
d187c0ad-d6d9-47a3-b6ca-519cb0a82c54 | 3 | public void AImove(Ball ball, int height) {
cnt++;
if (cnt == 2) {
cnt = 0;
//center = (y + (length / 2));
if (y + length < ball.getY() + ball.getRadius()) {
moveDown();
}
if (y > ball.getY()) {
moveUp();
}
}
} |
d15fd227-f5f5-4a2b-a969-d6c1e53d9aa2 | 7 | public void slaughter(GameWorld gw) {
gw.map[y][x].blood += 1500;
for (int dy = -1; dy < 2; dy++) {
if (y + dy < 0 || y + dy >= gw.map.length) { continue; }
for (int dx = -1; dx < 2; dx++) {
if (x + dx < 0 || x + dx >= gw.map[y].length) { continue; }
if (gw.r.nextInt(3) == 0) {
gw.map[y + dy][x + dx].blood += 500;
}
}
}
killed = true;
} |
339ce426-ebf7-4975-bcd8-1edea0decb0d | 0 | public void setExteriorRing(List<LngLatAlt> points)
{
coordinates.add(0, points);
} |
473de1a2-198d-4788-bd40-d5df7d739f92 | 7 | public boolean hit(ArrayList<Bullet> bullets,int damage){
if( this.isAlive() ){
for(Bullet b:bullets){
//ӵŵʱɱ
if( b.isAlive() && b.getId()!=id ){
if(inside(b)){
//HP
if( hp>0 ){
hp = hp - damage;
}
if( hp<=0 ){
this.setAlive(false);
cx = this.x;
cy = this.y;
cwidth = WIDTH;
cheight = HEIGHT;
deadStatus = DEAD_1;
}
return true;
}
}
}
}
return false;
} |
a4e3703c-d70c-4ac5-83b6-0574d8cdc97e | 8 | @Override
public void mousePressed(MouseEvent e) {
if (e.getX() < 0 || e.getY() < 0 || e.getX() > Minesweeper.myWidth * Minesweeper.SIZE || e.getY() > Minesweeper.myHeight * Minesweeper.SIZE) {
return;
}
boolean left = e.getButton() == MouseEvent.BUTTON1,
right = e.getButton() == MouseEvent.BUTTON3,
middle = e.getButton() == MouseEvent.BUTTON2;
if (right) { //handle right press
rightDown = true;
if (leftDown) {
board.teaseChord(board.spaceAt(e.getX(), e.getY()));
board.teaseSmile();
chordTeasing = true;
} else {
board.cycleState(board.spaceAt(e.getX(), e.getY()));
}
} else if (left) { //handle left press
leftDown = true;
if (rightDown) {
board.teaseChord(board.spaceAt(e.getX(), e.getY()));
board.teaseSmile();
chordTeasing = true;
} else {
board.spaceAt(e.getX(), e.getY()).tease();
board.teaseSmile();
}
}
lastX = e.getX();
lastY = e.getY();
} |
c8b2bccf-deb9-4a0d-a7d1-335a619d9dc1 | 6 | static public Vector3f findTetrahedronSimplex(List<Vector3f> simplex){
//A is the point added last to the simplex
Vector3f a = simplex.get(3);
Vector3f b = simplex.get(2);
Vector3f c = simplex.get(1);
Vector3f d = simplex.get(0);
Vector3f ao = a.negate();
Vector3f ab = b.minus(a);
Vector3f ac = c.minus(a);
Vector3f ad = d.minus(a);
Vector3f acd = ac.cross(ad);
Vector3f adb = ad.cross(ab);
//the side (positive or negative) of B, C and D relative to the planes of ACD, ADB and ABC respectively
int BsideOnACD = acd.dotProduct(ab) > 0.0f ? 1 : 0;
int CsideOnADB = adb.dotProduct(ac) > 0.0f ? 1 : 0;
//whether the origin is on the same side of ACD/ADB/ABC as B, C and D respectively
boolean ABsameAsOrigin = (acd.dotProduct(ao) > 0.0f ? 1 : 0) == BsideOnACD;
boolean ACsameAsOrigin = (adb.dotProduct(ao) > 0.0f ? 1 : 0) == CsideOnADB;
//if the origin is not on the side of B relative to ACD
if (!ABsameAsOrigin) {
//B is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(b);
//the new direction is on the other side of ACD, relative to B
}
//if the origin is not on the side of C relative to ADB
else if (!ACsameAsOrigin) {
//C is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(c);
//the new direction is on the other side of ADB, relative to C
}
//if the origin is not on the side of D relative to ABC
else //if (!ADsameAsOrigin) {
//D is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(d);
//the new direction is on the other side of ABC, relative to D
//go on with the triangle case
//TODO: maybe we should restrict the depth of the recursion, just like we restricted the number of iterations in BodiesIntersect?
return findTriangleSimplex(simplex);
} |
e020f5fa-7b09-4147-ae02-f89002fbd454 | 5 | public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
final int n = 2;
MethodOfEilerN.iterCount = 0;
System.out.println("y(k+1)[0] | y(k+1)[1] | t(k+1) ");
while (tk < T) {
tk1 = tk + tau;
ynext = Arrays.copyOf(MethodOfNewton.MethodNewton(ynext), n);
boolean flagEps = false;
for (int i = 0; i < n; i++) {
epsk[i] = -(tau / (tau + tauprev)) * (ynext[i] - y[i] - tau / tauprev * (y[i] - yprev[i]));
if (Math.abs(epsk[i]) > eps) flagEps = true;
}
if (flagEps) {
tau /= 2;
tk1 = tk;
ynext = Arrays.copyOf(y, n);
} else {
taunext = Math.min(Math.sqrt(eps / Math.abs(epsk[0])) * tau, Math.sqrt(eps / Math.abs(epsk[1])) * tau);
if (taunext > taumax) taunext = taumax;
yprev = Arrays.copyOf(y, n);
y = Arrays.copyOf(ynext, n);
tauprev = tau;
tau = taunext;
tk = tk1;
//Выводим
System.out.print(ynext[0] + " | ");
System.out.print(ynext[1] + " | ");
System.out.println(tk1);
}
flagEps = false;
iterCount++;
}
System.out.println(ynext[0] + " " + ynext[1]);
System.out.println(iterCount);
scanner.close();
} |
c78f1f91-e5de-4509-859a-7d019dcbaf15 | 1 | private void initialize(){
frame.setTitle("Learn-Words");
frame.setIconImage(MAIN_ICON.getImage());
frame.setSize(WINDOW_SIZE);
// setResizable(false);
frame.setMinimumSize(MIN_WINDOW_SIZE);
frame.setLocation((int) (SCREEN_SIZE.getWidth() / 2 - frame.getWidth() / 2),
(int) (SCREEN_SIZE.getHeight() / 2 - frame.getHeight() / 2));
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
LayoutManager layout = frame.getContentPane().getLayout();
BorderLayout bl = new BorderLayout();
bl.setVgap(1);
frame.getContentPane().setLayout(bl);
mainPanel = new JPanel(layout);
repetPanel = new JPanel(layout);
repetitionWords = new ArrayList<Word>();
initStatusBar();
initButton();
initMenuBar();
initTextArea();
initTextField();
initProgressBar();
initLabel();
mainPane = new JTabbedPane();
mainPane.addTab(TAB_MAIN, mainPanel);
mainPane.addTab(TAB_REPETITION, repetPanel);
frame.add(mainPane, BorderLayout.CENTER);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
bCancel.setLocation(frame.getWidth() - bCancel.getWidth() - 20, frame.getHeight() - 90);
menu.setBounds(0, 0, frame.getWidth(), 25);
scrollPaneQuestion.setBounds(10, 55, frame.getWidth() - 30, 50);
answer.setBounds(scrollPaneQuestion.getX(),
scrollPaneQuestion.getHeight() + scrollPaneQuestion.getY() + 10,
scrollPaneQuestion.getWidth(), 25);
progressBar.setLocation(answer.getX(), answer.getY() + answer.getHeight() + 20);
// bAddToRepetition.setLocation(progressBar.getX() + progressBar.getWidth() + 20, progressBar.getY());
bNext.setLocation(frame.getWidth() - bCancel.getWidth() - 20, progressBar.getY());
bAnswer.setLocation(bNext.getX(), bNext.getY() + 30);
totalQuestions.setLocation(answer.getX(), progressBar.getY() + progressBar.getHeight() + 20);
numberTotQuestions.setLocation(totalQuestions.getX() + totalQuestions.getWidth(),
totalQuestions.getY());
currentQuestions.setLocation(totalQuestions.getX(), totalQuestions.getY() + totalQuestions.getHeight() + 10);
numberOfCurQuestion.setLocation(currentQuestions.getX() + currentQuestions.getWidth(),
currentQuestions.getY());
totalRepetitions.setLocation(currentQuestions.getX(), currentQuestions.getY() + currentQuestions.getHeight() + 10);
numberTotRepetitions.setLocation(totalRepetitions.getX() + totalRepetitions.getWidth(),
totalRepetitions.getY());
}
});
mainPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
try{
JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
tabIndex = sourceTabbedPane.getSelectedIndex();
setQuestion();
}catch(RuntimeException ex){
/* Does nothing */
}
}
});
} |
070380eb-7abd-4f17-b4c7-040d9f4b55e6 | 8 | public void loadLayout(InputStream stream) {
Chrono c = new Chrono("loadLayout");
XMLDecoder d = new XMLDecoder(new BufferedInputStream(stream));
Node model = (Node) d.readObject();
Map<?, ?> m = (Map<?, ?>) d.readObject();
d.close();
this.splitPanels.removeAll();
try {
for (Entry<?, ?> e : m.entrySet()) {
Component component = ((ComponentConfiguration) e.getValue())
.getComponent(this);
this.splitPanels.add(component, e.getKey());
}
this.splitPanels.getMultiSplitLayout().setModel(model);
} catch (ObjectStreamException e) {
e.printStackTrace();
}
c.report();
} |
6575d300-81b2-4c22-ad06-cb8685ae76fa | 7 | public void parse(String fileName){
int i,j;
Sentence s;
NodeList sentences = doc.getElementsByTagName(XML_NODE_SENTENCE);
Node sentenceNode;
Element sentenceElement;
WordSW w;
NodeList words;
Node wordNode;
Element wordElement;
String link;
int dom;
for (i=0; i < sentences.getLength(); i++) {
sentenceNode = sentences.item(i);
if (sentenceNode.getNodeType() == Node.ELEMENT_NODE) {
sentenceElement = (Element) sentenceNode;
words = sentenceElement.getElementsByTagName(XML_NODE_WORD);
HashMap<Integer, Word> wordsMap = new HashMap<Integer, Word>();
for (j=0; j < words.getLength(); j++) {
wordNode = words.item(j);
if(wordNode.getNodeType() == Node.ELEMENT_NODE) {
wordElement = (Element) wordNode;
dom = 0;
if(!wordElement.getAttribute(WORD_ATTR_DOM).equals(XML_ROOT_NODE))
dom = Integer.valueOf(wordElement.getAttribute(WORD_ATTR_DOM));
//обработка токенов не имеющих связей
link = wordElement.getAttribute(WORD_ATTR_LINK);
if(link.length()==0 || wordElement.getAttribute(WORD_ATTR_LINK)==null) link="NULL";
//
//создаем слово
w = new WordSW(dom,
partOfSpeechMeta.get(wordElement.getAttribute(WORD_ATTR_FEAT)),
Integer.valueOf(wordElement.getAttribute(WORD_ATTR_ID)),
wordElement.getAttribute(WORD_ATTR_LEMMA),
wordElement.getAttribute(WORD_ATTR_LINK));
wordsMap.put(Integer.valueOf(wordElement.getAttribute(WORD_ATTR_ID)), w);
}
}
s = new Sentence(Integer.valueOf(sentenceElement.getAttribute(SENTENCE_ATTR_ID)),
wordsMap,null);
sentenceMap.put(s.id, s);
}
}
} |
d3f74ff6-bca7-4d91-9a97-0dc2651978a0 | 5 | @Override
public Query parse() {
if(!this.prepared) {
this.prepared = true;
StringBuilder sB = new StringBuilder();
sB.append("ALTER TABLE ");
sB.append(this.t.replace("#__", this.db.getPrefix()));
sB.append("\n ");
if(this.ren) {
sB.append(" RENAME TO ");
sB.append(this.renTo.replace("#__", this.db.getPrefix()));
}else{
sB.append(" ADD ");
int i = 0;
for(Column c : this.cL) {
if(!c.isParsed()) {
c.parse();
}
if(i > 0) {
sB.append(", ");
}else{
++i;
}
sB.append(c.getParsedColumn());
}
sB.append(" ");
}
sB.append(";");
this.query = sB.toString();
}
return this;
} |
9c3f9102-8a11-4969-b23e-1d2bc2818267 | 2 | public static boolean isHellSkeleton (Entity entity) {
if (entity instanceof Skeleton) {
LeatherArmorMeta chestMeta;
ItemStack HSC = new ItemStack(Material.LEATHER_CHESTPLATE, 1,
(short) - 98789);
chestMeta = (LeatherArmorMeta) HSC.getItemMeta();
chestMeta.setColor(Color.fromRGB(218, 28, 28));
HSC.setItemMeta(chestMeta);
Skeleton HS = (Skeleton) entity;
if (HS.getEquipment()
.getChestplate()
.equals(new ItemStack(Material.LEATHER_CHESTPLATE, 1,
(short) - 98789))) {
return true;
}
}
return false;
} |
54110f99-fa29-4444-9def-50381c536a1b | 4 | @SuppressWarnings("rawtypes")
public static void printList(AbstractList list, int depth)
{
final Iterator i = list.iterator();
Object o = null;
for (int k = 0; k < depth; k++)
System.out.print(" ");
System.out.println("List: ");
while (i.hasNext() && (o = i.next()) != null)
{
for (int k = 0; k < depth; k++)
System.out.print(" ");
System.out.print(" +");
print(o, depth);
}
} |
90bd5161-f2bf-4554-8826-77d42b4f1cdb | 0 | public Map<Integer, String> getGlobalStringPool() {
return this.stringTable;
} |
8860fb3d-4a3a-4c9a-b61a-b31f051299e3 | 4 | @Test(groups = { "Integer-Sorting", "Primitive Sort" })
public void testSelectionSortInt() {
Reporter.log("[ ** Selection Sort ** ]\n");
try {
testSortIntegers = new SelectionSort<>(
primitiveShuffledArrayInt.clone());
Reporter.log("1. Unsorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("2. Sorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("3. Reversed Sorted Array\n");
ShuffleArray.reverseArray(testSortIntegers.getArray());
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
}
catch (Exception x) {
System.err.println(x);
throw x;
}
} |
10ef5fdd-6d01-45e3-af4b-0ced7a1bf044 | 6 | public Word[] verboseAlternatives(Word wordizedSearch){
int n = wordizedSearch.getWord().length();
Word[] words = this.getAlternatives(wordizedSearch);
if(dictionary.contains(wordizedSearch))
return new Word[] {wordizedSearch};
try{
FileWriter fw = new FileWriter(wordizedSearch.getWord() + ".txt");
fw.write("User string: " + wordizedSearch.getWord() + "\r\n\r\n");
//Deletions
for(int i = 0; i < n; i++){
fw.write("Deletion string: " + words[i].getWord() + "\r\n");
}
fw.write("Created " + n + " deletion alternatives\r\n\r\n");
//Transposition
for(int i = n; i < n+n-1; i++){
fw.write("Transposition string: " + words[i].getWord() + "\r\n");
}
fw.write("Created " + (n-1) + " transposition alternatives\r\n\r\n");
//Substitution
int x = 25*n + 2*n - 1;//variable to shorten code
for(int i = n+n-1; i < x; i++){
fw.write("Substitution string: " + words[i].getWord() + "\r\n");
}
fw.write("Created " + 25*(n) + " substitution alternatives\r\n\r\n");
//Insertion
for(int i = x; i < 26*(n+1) + x; i++){
fw.write("Insertion string: " + words[i].getWord() + "\r\n");
}
fw.write("Created " + 26*(n+1) + " insertion alternatives\r\n\r\n");
fw.write("TOTAL: generated " + (53*wordizedSearch.getWord().length() + 25)+ " alternative spellings!");
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
return words;
} |
fbbbe8d7-a7f1-4b5b-8f1b-8f298684c5fc | 8 | public int findThreat(){
int index=-1;
for(int q=0;q<objects.size();q++) {
if (objects.get(q) == this||objects.get(q).kind==kind||objects.get(q).kind==0)
continue;
int searchRadius = 400; //radius of whether the object will be findable
boolean search = collisionCircle(getX(),getY(),searchRadius,objects.get(q).getX(),objects.get(q).getY(),20); // whether the object is close enough to be considered
boolean facing = isFacing(q,45); //whether it's facing the object
if(search&&facing) {
int distance1 = (int)Math.sqrt(Math.pow(objects.get(0).x-objects.get(q).x,2)+Math.pow(objects.get(0).y-objects.get(q).y,2));
if(index==-1)
index=q;
else if(distance1<((int)Math.sqrt(Math.pow(objects.get(0).x-objects.get(index).x,2)+Math.pow(objects.get(0).y-objects.get(index).y,2))))
index=q;
}
}
return index;
} |
d4f07af0-5d8b-4651-bf41-a82dfe1d331c | 0 | @Override
public boolean removeGroup(String group) {
return groups.remove(group);
} |
ad7c8a3b-93ae-41fc-971c-4af15aadc78c | 3 | @Override
public void done()
{
try
{
StringBuilder result = get();
textArea.setText(result.toString());
statusLine.setText("Done");
}
catch (InterruptedException ex)
{
}
catch (CancellationException ex)
{
textArea.setText("");
statusLine.setText("Cancelled");
}
catch (ExecutionException ex)
{
statusLine.setText("" + ex.getCause());
}
cancelItem.setEnabled(false);
openItem.setEnabled(true);
} |
702a075f-3480-445b-b38e-74a69726ac1a | 3 | public void runStep () {
ArrayList<Node> readyNodes = new ArrayList<Node>();
for (Node node : _nodes) {
if (node.getReady()) {
readyNodes.add(node);
}
}
for (Node node : readyNodes) {
node.sendTrigger();
}
} |
f38cb6f8-e1ff-42f4-9d83-290829bb870e | 0 | public VueConnexion(CtrlAbstrait ctrlA) {
super(ctrlA);
initComponents();
VueAbstrait vueA = null;
this.ctrl = new CtrlConnexion(this, vueA);
} |
2968dc71-4fa4-4350-8a19-7b0f7844019d | 8 | public Object parse(String original) throws ValidatorException {
LinkedHashMap<String, String> map = new LinkedHashMap<String,String>();
String[] lines = original.split("\\n+");
for (String line : lines) {
String[] tokens = line.replaceFirst("^\\s+","").split("\\s+");
if (tokens.length > 2)
throw new ValidatorException("Invalid line: " + line);
if (tokens.length == 0 || (tokens.length == 1 && tokens[0].isEmpty()))
continue;
String key,value;
if (tokens.length == 2) {
key = tokens[0];
value = tokens[1];
} else {
key = " ";
value = tokens[0];
}
if (map.containsKey(key))
throw new ValidatorException("Duplicate key: " + key);
map.put(key, value);
}
if (map.size() == 0)
throw new ValidatorException("There must be at least one entry");
return map;
} |
b57cc281-8102-43bd-ac11-6976e15a3041 | 8 | private void doread(ScanfReader scanReader)
throws IOException {
chartData.setEntryList(new Vector<ChartEntry>(10));
HashMap<String, Color> colorList = new HashMap<String, Color>(10);
boolean attributesRead = false;
colorList.put("red", Color.red);
colorList.put("green", Color.green);
colorList.put("blue", Color.blue);
colorList.put("cyan", Color.cyan);
colorList.put("magenta", Color.magenta);
colorList.put("yellow", Color.yellow);
while (true) {
String keyword = null;
try {
keyword = scanReader.scanString();
} catch (EOFException e) {
break;
}
if (keyword.equals("attributes")) {
mainPane = new TablePane();
chartData.setAttrData(new Vector<AttributeData>());
readAttributes(scanReader, null, colorList);
renderMainPaneAttributes();
mainPane.adjustAttributesForDepth(mainPane.getDepth());
attributesRead = true;
} else if (keyword.equals("color")) {
String name = scanReader.scanString();
float r = scanReader.scanFloat();
float g = scanReader.scanFloat();
float b = scanReader.scanFloat();
colorList.put(name, new Color(r, g, b));
} else if (keyword.equals("entry")) {
if (!attributesRead) {
throw new IOException("Entry specified before attributes");
}
chartData.addChartEntry(readEntry(scanReader, mainPane));
} else if (keyword.startsWith("report=")) {
//Sets the report location for the ValueCharts parent interface (there is another reportFileLocation, which is specific to the AttributeCell bar charts)
reportFile = new File(keyword.substring(7).replace("$", " ").replace("\\", "\\\\"));
if (reportFile.exists()) {
createReportController();
} else {
//since the report does not exist, throw a system message letting the user know this, and set the report to null
System.out.println("The report for the ValueChart is not valid, the system believes the report is located at: ");
System.out.println(" " + reportFile.toString());
System.out.println(" If this is an error, please verify that you have correctly substituted all spaces and added two slashes between directories.");
reportFile = null;
}
} else {
throw new IOException("Unknown keyword " + keyword);
}
}
renderMainPane();
} |
8f325d1c-65de-44a2-913c-bcd4a775b5bc | 2 | public static Long parseNumericStringObject(Object object) throws InvalidRpcDataException {
if (object == null) {
return null;
}
if (object instanceof String) {
return parseNumericString((String) object);
} else {
throw new InvalidRpcDataException("Expected numeric String, but got: " + object.getClass().getName());
}
} |
f893323e-d1da-448f-839e-93a49c740df4 | 6 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MessageBlockDef other = (MessageBlockDef) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (length != other.length) {
return false;
}
if (offset != other.offset) {
return false;
}
return true;
} |
c90fd919-972f-462d-9c9e-3b253be63136 | 0 | public Long getFilmId() {
return filmId;
} |
08864427-4138-47e3-90a0-a62516ba5f2f | 4 | public static String postXml(String content,String postUrl) throws IOException{
OutputStreamWriter out = null;
URLConnection con=null;
BufferedReader br = null;
try {
URL url = new URL(postUrl);
con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
out = new OutputStreamWriter(con.getOutputStream());
out.write(new String(content.getBytes("UTF-8")));
out.flush();
br = new BufferedReader(new InputStreamReader(
con.getInputStream()));
StringBuilder result = new StringBuilder();
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
result.append(line + "\n");
}
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}finally{
if(out!=null){out.close();}
if(br!=null){br.close();}
}
} |
8a46635e-c214-4942-9c84-6f6533b5af11 | 7 | public void checkPKReward() {
if(pkpoints == 500000) {
addItem(1038, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 750000) {
addItem(1040, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 100000) {
addItem(1042, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 150000) {
addItem(1044, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 200000) {
addItem(1046, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 300000) {
addItem(1048, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a phat =)");
}
if(pkpoints == 500000) {
addItem(6570, 1);
sendMessage("Congratz on getting "+pkpoints+" pk points! Have a firecape =)");
}
} |
3990d569-a9a5-4c4e-afdc-aa9074fc53a1 | 7 | public static boolean isInteger(String s) {
if (s == null || s.length() == 0) {
return false;
}
char c = s.charAt(0);
if (s.length() == 1) {
return c >= '0' && c <= '9';
}
return (c == '-' || c >= '0' && c <= '9') && onlyDigits(s.substring(1));
} |
288340b5-18f5-448f-9167-8f697a583edc | 0 | public String getEmail() {
return this.email;
} |
2d2809c5-5e5f-4bcc-b95f-6d4b3bdd56c3 | 0 | private void applyChanges() {
updateGUI();
// Record all the changes.
docSettings.getLineEnd().applyTemporaryToCurrent();
docSettings.getSaveEncoding().applyTemporaryToCurrent();
docSettings.getSaveFormat().applyTemporaryToCurrent();
docSettings.getOwnerName().applyTemporaryToCurrent();
docSettings.getOwnerEmail().applyTemporaryToCurrent();
docSettings.getApplyFontStyleForComments().applyTemporaryToCurrent();
docSettings.getApplyFontStyleForEditability().applyTemporaryToCurrent();
docSettings.getApplyFontStyleForMoveability().applyTemporaryToCurrent();
docSettings.getUseCreateModDates().applyTemporaryToCurrent();
docSettings.getCreateModDatesFormat().applyTemporaryToCurrent();
docSettings.updateSimpleDateFormat(docSettings.getCreateModDatesFormat().cur);
} |
b3415deb-2724-48c7-a87b-c88a202a3fb6 | 4 | @Test
public void TestAll() throws IOException, SyntaxFormatException {
for (File file : new File("src/test/resources/testprogs/").listFiles()) {
if (file.isFile()) {
if (file.getPath().indexOf(StatementTest.simpleFuncTest4) >= 0) {
continue;
}
if (!file.getPath().endsWith(".txt")) {
continue;
}
TouchDataHelper.resetAll();
System.out.println(file.getPath());
checkGraph(file.getPath(), "optimized");
}
}
} |
366f3ace-dfec-4b8b-b996-a752eb47cce2 | 0 | public Scheduler get()
{
return scheduler;
} |
2af1f00f-03af-4ae2-bd7d-fd5db5f5dff1 | 1 | public void setOption(String option, Collection values) {
if (option.equals("all")) {
onlySUID = false;
} else
throw new IllegalArgumentException("Invalid option `" + option
+ "'.");
} |
0733f1cb-c3d3-4604-8a35-d50df05d0e81 | 8 | Edge enter(Node branch) {
Node n;
Edge result = null;
int minSlack = Integer.MAX_VALUE;
boolean incoming = getParentEdge(branch).target != branch;
// searchDirection = !searchDirection;
for (int i = 0; i < graph.nodes.size(); i++) {
if (searchDirection)
n = graph.nodes.getNode(i);
else
n = graph.nodes.getNode(graph.nodes.size() - 1 - i);
if (subtreeContains(branch, n)) {
EdgeList edges;
if (incoming)
edges = n.incoming;
else
edges = n.outgoing;
for (int j = 0; j < edges.size(); j++) {
Edge e = edges.getEdge(j);
if (!subtreeContains(branch, e.opposite(n)) && !e.tree
&& e.getSlack() < minSlack) {
result = e;
minSlack = e.getSlack();
}
}
}
}
return result;
} |
6955e6c5-1774-4983-8fdf-fea59c133707 | 5 | public void register(final JComponent showDate) {
this.showDate = showDate;
showDate.setRequestFocusEnabled(true);
showDate.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showDate.requestFocusInWindow();
}
});
this.setBackground(Color.WHITE);
this.add(showDate, BorderLayout.CENTER);
this.setPreferredSize(new Dimension(90, 25));
this.setBorder(BorderFactory.createLineBorder(Color.GRAY));
showDate.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setCursor(new Cursor(Cursor.HAND_CURSOR));
showDate.setForeground(Color.RED);
}
}
public void mouseExited(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
showDate.setForeground(Color.BLACK);
}
}
public void mousePressed(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setForeground(Color.CYAN);
if (isShow) {
hidePanel();
} else {
showPanel(showDate);
}
}
}
public void mouseReleased(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setForeground(Color.BLACK);
}
}
});
showDate.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
hidePanel();
}
public void focusGained(FocusEvent e) {
}
});
} |
c1e3447b-efc8-4d1a-9b8b-da8fa7ea4b34 | 1 | public void testDividedBy_int() {
Minutes test = Minutes.minutes(12);
assertEquals(6, test.dividedBy(2).getMinutes());
assertEquals(12, test.getMinutes());
assertEquals(4, test.dividedBy(3).getMinutes());
assertEquals(3, test.dividedBy(4).getMinutes());
assertEquals(2, test.dividedBy(5).getMinutes());
assertEquals(2, test.dividedBy(6).getMinutes());
assertSame(test, test.dividedBy(1));
try {
Minutes.ONE.dividedBy(0);
fail();
} catch (ArithmeticException ex) {
// expected
}
} |
1beba52d-90dd-495e-ac90-bed25e7ff44c | 6 | @EventHandler(priority = EventPriority.LOW)
public void onEntityDeath(EntityDeathEvent e) {
final Entity player = e.getEntity();
for (String worldname : WorldSettings.worlds) {
if (e.getEntity().getWorld().getName().equals(worldname)) {
if (Settings.onDeath) {
e.getDrops().clear();
return;
}
/*
* Filters through the drops of dead entities If its a player,
* check if they have permission, if they dont remove the
* blacklisted drops If its any other entity, remove the blocked
* items from there droppings
*/
for (Integer bitem : Settings.bitems) {
if (e.getEntity() instanceof Player) {
if (!PermissionHandler.has((Player) player,
PermissionNode.BYPASS_BLACKLIST)) {
e.getDrops().remove(bitem);
}
} else {
e.getDrops().remove(bitem);
}
}
}
}
} |
29e8de45-4410-4db2-9044-039e31744e1a | 5 | public final SymbolraetselASTNormalizer.start_return start() throws RecognitionException {
SymbolraetselASTNormalizer.start_return retval = new SymbolraetselASTNormalizer.start_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
CommonTree _first_0 = null;
CommonTree _last = null;
CommonTree START1=null;
SymbolraetselASTNormalizer.redraw_return redraw2 = null;
CommonTree START1_tree=null;
try {
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe4\\src\\symbolraetsel_AST_Solver\\grammar\\SymbolraetselASTNormalizer.g:19:7: ( ^( START ( redraw )+ ) )
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe4\\src\\symbolraetsel_AST_Solver\\grammar\\SymbolraetselASTNormalizer.g:19:9: ^( START ( redraw )+ )
{
root_0 = (CommonTree)adaptor.nil();
_last = (CommonTree)input.LT(1);
{
CommonTree _save_last_1 = _last;
CommonTree _first_1 = null;
CommonTree root_1 = (CommonTree)adaptor.nil();_last = (CommonTree)input.LT(1);
START1=(CommonTree)match(input,START,FOLLOW_START_in_start69);
START1_tree = (CommonTree)adaptor.dupNode(START1);
root_1 = (CommonTree)adaptor.becomeRoot(START1_tree, root_1);
match(input, Token.DOWN, null);
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe4\\src\\symbolraetsel_AST_Solver\\grammar\\SymbolraetselASTNormalizer.g:19:17: ( redraw )+
int cnt1=0;
loop1:
do {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==EQUALS) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe4\\src\\symbolraetsel_AST_Solver\\grammar\\SymbolraetselASTNormalizer.g:19:17: redraw
{
_last = (CommonTree)input.LT(1);
pushFollow(FOLLOW_redraw_in_start71);
redraw2=redraw();
state._fsp--;
adaptor.addChild(root_1, redraw2.getTree());
}
break;
default :
if ( cnt1 >= 1 ) break loop1;
EarlyExitException eee =
new EarlyExitException(1, input);
throw eee;
}
cnt1++;
} while (true);
match(input, Token.UP, null); adaptor.addChild(root_0, root_1);_last = _save_last_1;
}
}
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return retval;
} |
649c877a-f308-4707-bcde-1fa22709f4db | 3 | private void jButtonCalcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCalcActionPerformed
/**This method calculates Monthly Mortgage Payment**/
/**Get Input**/
//Get the vlaue of the text fiels
sPrinciple = jTextFieldPrincipal.getText();
//add error checking
sAnualInterest = jTextFieldInterest.getText();
//add error checking
sTermYr = jTextFieldTerm.getText();
//error checking
if(sPrinciple.isEmpty()||sAnualInterest.isEmpty()||sTermYr.isEmpty()){
ErrorLabel.setText("Incorrect or missing value");
return;}
//convert strings to numbers
dPrinciple = Double.parseDouble(sPrinciple); //Amount Barrowed
dInterest = Double.parseDouble(sAnualInterest); //Anual interest Rate
iYearTerm = Integer.parseInt(sTermYr); // Loan Payback Period in Years
//TODO add error checking
//get monthly payment info
dMonthlyPayment=getMoPayment(iYearTerm, dInterest, dPrinciple);
//Formats Monthly Payment
currency = NumberFormat.getCurrencyInstance(); //creates currency
sMonthlyPayment=currency.format(dMonthlyPayment);
//write output
jTextFieldMoPay.setText(sMonthlyPayment);
}//GEN-LAST:event_jButtonCalcActionPerformed |
325a3346-3cd1-40b8-8137-6d610ad3204d | 2 | public static byte[] serialize(Inventory items) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
NbtTagCompound nbtTagCompound = NbtFactory.toCompound(NbtFactory.createTag(NbtType.TAG_COMPOUND));
NbtTagList nbtTagList = NbtFactory.toList(NbtFactory.createTag(NbtType.TAG_LIST));
for (int i = 0; i < items.getSize(); i++) {
NbtTagCompound compound = NbtFactory.toCompound(NbtFactory.createTag(NbtType.TAG_COMPOUND));
ItemStack stack = items.getItem(i);
if (stack != null)
NbtFactory.saveItemStack(stack, compound);
nbtTagList.add(compound);
}
nbtTagCompound.put(VERSION_KEY, NBT_VERSION);
nbtTagCompound.put(ITEMS_KEY, nbtTagList);
NbtFactory.fromNbtBase(nbtTagCompound).write(dataOutputStream);
return byteArrayOutputStream.toByteArray();
} |
b57220de-d9e2-4d11-8529-e83dc3f12edd | 4 | public static Mask buildPrewittMask(Direction d) {
switch (d) {
case HORIZONTAL:
double[][] dValues = { { 1, 0, -1 }, { 1, 0, -1 }, { 1, 0, -1 } };
return new Mask(dValues);
case VERTICAL:
double[][] aValues = { { 1, 1, 1 }, { 0, 0, 0 }, { -1, -1, -1 } };
return new Mask(aValues);
case DIAGONAL:
double[][] bValues = { { 1, 1, 0 }, { 1, 0, -1 }, { 0, -1, -1 } };
return new Mask(bValues);
case INVERSE_DIAGONAL:
double[][] cValues = { { 0, -1, -1 }, { 1, 0, -1 }, { 1, 1, 0 } };
return new Mask(cValues);
}
return null;
} |
d7957b6e-6444-4976-92f2-ede9f12953ba | 6 | public static boolean isValidIPAddress(String s) {
String[] nums = s.split("\\.");
if (4 != nums.length) return false;
for (int i = 0; i < nums.length; i++) {
if (nums[i].startsWith("0") && nums[i].length() > 1) return false;
int n = Integer.parseInt(nums[i]);
if (n > 255 || n < 0) return false;
}
return true;
} |
c3a82889-5592-42b5-accf-96b9530fc20a | 4 | public static String[] parse(String name) throws IOException, NavException, XPathParseException, XPathEvalException, ParseException{
File f = new File(name);
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
fis.read(b);
VTDGen vg = new VTDGen();
vg.setDoc(b);
vg.parse(true); // set namespace awareness to true
// Objects to assist navigation in XML
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.bind(vn);
int count = 0;
int t;
//First of all select element. The VTD Navigator VTDNav will iterate over all
//such elements
ap.selectElement("node");
while(ap.iterate()){
//get first child that is a kdv number
vn.toElement(VTDNav.FIRST_CHILD,"kdv");
//getText returns an index in the XML document so take this index t and
//then if t!=-1 print the text of the respective element
if ((t=vn.getText())!= -1) {
kdv = null;
kdv = vn.toNormalizedString(t);
}
vn.toElement(VTDNav.NEXT_SIBLING); //navigates to next sibling on the XML tree
if ((t=vn.getText())!= -1) {
xcoord = null;
xcoord = vn.toNormalizedString(t);
}
vn.toElement(VTDNav.NEXT_SIBLING); //navigates to next sibling on the XML tree
if ((t=vn.getText())!= -1) {
ycoord = null;
ycoord = vn.toNormalizedString(t);
//Add all the information to one string
String finalString = kdv + " &&& " + xcoord + " &&& " + ycoord;
sArray[count] = finalString;
count++;
}
}
ap.resetXPath();
b=null;
fis.close();
return sArray;
} |
5cde5c32-c905-4977-83d0-7efe8fabdffe | 6 | public static void unit_test( final int ARRAY_SIZE ) {
SortAlgorithm[] algorithms = {
new InsertionSort(),
new BubbleSortForLoop(),
new BubbleSortUntilLoop(),
new SelectionSort(),
new MergeSort(),
new InPlaceQuickSort( new LastElementAsPivot() )
};
for( SortAlgorithm algo : algorithms ) {
System.out.print("Launching " + algo.toString() + "... ");
int[] list = Utils.generate(ARRAY_SIZE);
int[] copy = list.clone();
long begin = System.currentTimeMillis();
algo.sort( list );
System.out.println("Finished in " + (System.currentTimeMillis() - begin) + "ms.");
if( !Utils.sameValues(list, copy) ) {
System.out.println("Error at this point: the input and output arrays are not the same.");
System.out.println("Original:");
for(int i = 0; i < copy.length; ++i) System.out.print(copy[i] + ",");
System.out.println("\nSorted:");
for(int i = 0; i < list.length; ++i) System.out.print(list[i] + ",");
return;
}
if( !Utils.checkSorted( list ) ) {
for(int i = 0; i < list.length; ++i) System.out.print(list[i] + ",");
System.out.println("Error at this point: array not sorted");
return;
}
}
System.out.println("Everything worked :)");
} |
f629adde-71d0-4efc-a350-c9ff754f62c0 | 5 | public void writeStep(int r, int s, Step step, Data stepData, double finalOF) {
checkFile();
if (w != null) {
this.writeStepHeader();
w.println("-------------------------------");
w.println("Round " + (r+1) + " Step " + step.getName());
w.println("-------------------------------\n");
w.println();
w.println("Objective Function Values for round " + (r+1) + " = " + finalOF);
ParameterData[] paramData = stepData.paramData;
for (int i = 0; i < paramData.length; i++) {
ParameterData paramInstance = paramData[i];
w.println(">>> Parameter Name: " + paramInstance.getName());
w.println();
w.println("Lower Bound = " + paramInstance.getOriginalLowerBound() );
w.println("Upper Bound = " + paramInstance.getOriginalUpperBound() );
w.println();
w.println("Parameter Values:");
w.println("\t#\tinit value\t\tRound " + r + " data");
double[] pdata = paramInstance.getDataValue();
boolean[] calibrated = paramInstance.getCalibrationFlag();
int calibrationCount = 0;
double mean = 0;
for(int j=0; j<pdata.length; j++) {
w.format("\t"+ (j+1) + "\t%f\t\t%f\n", iData.get(inxt), pdata[j]);
inxt++;
if (inxt >= iData.size()) inxt = 0;
if (calibrated[j]) {
mean += pdata[j];
calibrationCount++;
}
}
mean = mean/calibrationCount;
w.println("\tMean\t\t\t" + mean);
w.flush();
}
w.flush();
}
} |
cd7a5d58-e32d-4fc7-b946-77bf891b7f7b | 3 | public String getWhois(final String domainName) {
StringBuilder result = new StringBuilder("");
try {
WhoisClient whois = new WhoisClient();
whois.connect(WhoisClient.DEFAULT_HOST);
// whois =google.com
String whoisData = whois.query("=" + domainName);
result.append(whoisData);
whois.disconnect();
// get the google.com whois server - whois.markmonitor.com
String whoisServerUrl = getWhoisServer(whoisData);
if (!whoisServerUrl.equals("")) {
// whois -h whois.markmonitor.com google.com
result.append("\n").append(queryWithWhoisServer(domainName, whoisServerUrl));
}
} catch (SocketException e) {
} catch (IOException e) {
}
return result.toString();
} |
874c9087-0c7e-4a4f-b411-c207efb17a74 | 1 | protected static boolean resetProtection(Path file) {
assert FileUtil.control(file);
boolean ret = false;
String cmdTmp = RESTOREACL_CMD_1 + file.getParent().toString() + RESTOREACL_CMD_2 + acl
+ file.getFileName().toString().replaceAll("\\.", "") + RESTOREACL_CMD_3;
try {
ret = ProgramLauncher.start(SystemInformation.getCMD(), cmdTmp, true, ERROR_IDENTIFIER);
} catch (InterruptedException
| IOException e) {
ret = false;
}
return ret;
} |
ccd48ee0-ef41-4bf1-b065-633a1b1d66dc | 6 | public static String fold( List valueList, final String token )
{
String lastToken = token;
while( true )
{
String foldedToken = foldImpl( valueList, lastToken );
if( foldedToken.equals( lastToken ) )
{
break;
}
else
{
lastToken = foldedToken;
}
}
if( lastToken.length() > LIBINJECTION_SQLI_MAX_TOKENS )
{
lastToken = lastToken.substring( 0, LIBINJECTION_SQLI_MAX_TOKENS );
}
//do some work after folding
//Check for magic PHP backquote comment
if( lastToken.length() > 1 )
{
int lastIndex = lastToken.length() - 1;
if( lastToken.charAt( lastIndex ) == 'n'
&& valueList.get( lastIndex ).equals( "`" )
)
{
lastToken = lastToken.substring( 0, lastIndex ) + "c";
}
}
return lastToken;
} |
2f26ea44-ba19-4765-b1ca-0dab80cb183f | 3 | public String getTypeSignature() {
switch (typecode) {
case TC_LONG:
return "J";
case TC_FLOAT:
return "F";
case TC_DOUBLE:
return "D";
default:
return "?";
}
} |
16a1716d-29a5-4a48-bf3c-c8a00bde2706 | 4 | public Console registerShorcut() {
Event.addNativePreviewHandler(new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getTypeInt() == Event.ONKEYDOWN && event.getNativeEvent().getShiftKey() && event.getNativeEvent().getAltKey()
&& event.getNativeEvent().getKeyCode() == KEY_C) {
toggleDisplay();
}
}
});
return this;
} |
ba715a95-a95a-4227-ab1c-0b6b7f672468 | 6 | @EventHandler
public void WitchInvisibility(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.getWitchConfig().getDouble("Witch.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getWitchConfig().getBoolean("Witch.Invisibility.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getWitchConfig().getInt("Witch.Invisibility.Time"), plugin.getWitchConfig().getInt("Witch.Invisibility.Power")));
}
} |
e6fb3bd2-5525-42a9-8b65-f4379ece7355 | 8 | public boolean hasNext() {
if (matcher == null) {
return false;
}
if (delim != null || match != null) {
return true;
}
if (matcher.find()) {
if (returnDelims) {
delim = input.subSequence(lastEnd, matcher.start()).toString();
}
match = matcher.group();
lastEnd = matcher.end();
} else if (returnDelims && lastEnd < input.length()) {
delim = input.subSequence(lastEnd, input.length()).toString();
lastEnd = input.length();
// Need to remove the matcher since it appears to automatically
// reset itself once it reaches the end.
matcher = null;
}
return delim != null || match != null;
} |
a0e49d7e-8565-432f-a78f-f1fe75d06117 | 8 | @Override
public ArrayList<Chromosome<T>> update()
{
if(chromoPool.size() % 2 != 0)
{
throw new RuntimeException("Gene pool size is not dividable by 2");
}
ArrayList<Chromosome<T>> newChromoList = new ArrayList<Chromosome<T>>();
double totalFitness = 0;
for(Chromosome<T> chromosome : chromoPool)
{
totalFitness += chromosome.getFitness();
}
avgFitness = totalFitness/chromoPool.size();
for(int i = chromoPool.size(); i > 0; i -= 2)
{
Chromosome<T> c1 = pickChromosome(chromoPool);
Chromosome<T> c2 = pickChromosome(chromoPool);
if(Math.random() <= crossOverRate)
{
if(c1.getLength() != c2.getLength())
{
throw new RuntimeException("Chromosome lengths do not match, can not crossover");
}
int crossOverPoint = (int) Math.floor(Math.random() * c1.getLength());
c1.crossOver(crossOverPoint, c2);
}
newChromoList.add(c1);
newChromoList.add(c2);
}
chromoPool.clear();
for(Chromosome<T> chromosome : newChromoList)
{
for(int i = 0; i <= chromosome.getLength() - 1; i++)
{
if(Math.random() <= mutationRate)
{
chromosome.mutate(i);
}
}
}
return newChromoList;
} |
31d37c46-1340-4c7b-927e-9d61bc5e0f76 | 1 | public void visit_newarray(final Instruction inst) {
final Type type = (Type) inst.operand();
if (type.isReference()) {
final int index = constants.addConstant(Constant.CLASS, type);
addOpcode(Opcode.opc_anewarray);
addShort(index);
} else {
addOpcode(Opcode.opc_newarray);
addByte(type.typeCode());
}
stackHeight += 0;
} |
c0786d88-0ac4-46af-84b7-60cb5449a35b | 6 | public Gezin addOngehuwdGezin(Persoon ouder1, Persoon ouder2) {
if (ouder1 == ouder2) {
return null;
}
Calendar nu = Calendar.getInstance();
if (ouder1.isGetrouwdOp(nu) || (ouder2 != null
&& ouder2.isGetrouwdOp(nu))
|| ongehuwdGezinBestaat(ouder1, ouder2)) {
return null;
}
Gezin gezin = new Gezin(nextGezinsNr, ouder1, ouder2);
nextGezinsNr++;
gezinnen.add(gezin);
ouder1.wordtOuderIn(gezin);
if (ouder2 != null) {
ouder2.wordtOuderIn(gezin);
}
return gezin;
} |
0965e76a-bfbe-468d-bc2c-b5026a6dde0c | 9 | public static void runRace() {
try {
while (!exit && !goToMainMenu && !goToPostRaceScreen && !restart) {
// If the display isn't visible (minimised), delay the game more
if (!Display.isVisible()) {
Thread.sleep(200);
}
// If the display is requested to close, exit the program
else if (Display.isCloseRequested()) {
exit = true;
}
// If program has to go to the prompt screen, set it up and run
// it
else if (goToPromptScreen) {
goToPromptScreen = false;
resume = false;
goToMainMenu = false;
restart = false;
setupExitPrompt();
runExitPrompt();
initGL();
}
// If none of those things occur (The race is running normally)
else {
// Add a little delay to let the other threads catch up
Thread.sleep(1);
// Update the timer, handle the inputs, draw and update the
// screen
updateTimer();
handleInputs();
update();
draw();
Display.update();
// If the race is done, end the race
if (currentLap > 3) {
endRace();
}
}
}
} catch (Exception exception) {
System.out.println("RacingApp.run() error: " + exception);
}
} |
d248a202-49af-45b7-8efc-81bb4e6876ee | 7 | public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
a03aeccb-6da4-47b6-9e75-4435d52782fc | 3 | public final int readShort() throws IOException {
int ch1 = readByte();
int ch2 = readByte();
if(ch1 < 0)
ch1 = BYTE_MAX + ch1;
if(ch2 < 0)
ch2 = BYTE_MAX + ch2;
if ((ch1 | ch2) < 0)
throw new EOFException();
return (ch1 << 8) + (ch2);
} |
13161d77-18db-4509-bc3b-0ff9e93a5e68 | 6 | public void testRetainAllArray() {
int element_count = 20;
int ints[] = new int[element_count];
for ( int i = 0; i < element_count; i++ ) {
ints[i] = i;
}
TIntList list = new TIntLinkedList( 20 );
for ( int i = 0; i < element_count; i++ ) {
list.add( i );
}
assertEquals( element_count, list.size() );
assertFalse( list.retainAll( ints ) );
assertEquals( element_count, list.size() );
for ( int i = 0; i < list.size(); i++ ) {
assertEquals( i , list.get( i ) );
}
ints = new int[( element_count - 4 )] ;
for ( int i = 0, j = 0; i < ints.length; i++, j++ ) {
if ( i % 4 == 0 ) {
j++;
}
ints[i] = j;
}
assertTrue( list.retainAll( ints ) );
int expected = element_count - 4;
assertEquals( expected, list.size() );
for ( int i = 0; i < list.size(); i++ ) {
expected = ( int ) Math.floor( i / 4 ) + i + 1;
assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list,
expected , list.get( i ) );
}
} |
0759e7c4-88d4-4cac-a0a8-40dab94731d1 | 6 | public Object getValueAt(int lin, int col) {
Object o=null;
switch (col) {
case 0 : o=lancamentos.get(lin).contaDe;
break;
case 1 : o=lancamentos.get(lin).contaPara;
break;
case 2 : o=String.format("%1$td/%1$tm/%1$tY",lancamentos.get(lin).dataIni);//.getTime();
break;
case 3 : o=String.format("%1$td/%1$tm/%1$tY",lancamentos.get(lin).dataVenc);//.getTime();
break;
case 4 : o=lancamentos.get(lin).historico;
break;
case 5 : o=String.format("%,.2f",lancamentos.get(lin).valor);
break;
}
return o;
} |
ddd6227f-a9ca-4034-a96f-2c74de23e8da | 0 | public String getAddress() {
return address;
} |
167ff5b9-7c15-4c17-9cef-e459b869580d | 1 | public static void saveObject(Object object, String file_name) {
try {
ObjectOutputStream oos =
new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(new File(file_name))));
oos.writeObject(object);
oos.close();
}
catch (IOException e) {
System.err.println("Exception writing file " + file_name + ": " + e);
}
} |
45dc1526-c120-4170-a950-a052b479cd78 | 0 | public Iterator getSprites() {
return sprites.iterator();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.