method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
41bcc68b-b093-4b27-ba5b-c3d432a375e4
| 8
|
public TimeLine(final SampleLog log) {
this.log = log;
this.samples = log.samples;
setPreferredSize(new Dimension(samples.size(), 100));
addMouseWheelListener( new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
scale += e.getUnitsToScroll() * 0.10f;
validateValues();
}
});
addMouseListener( new MouseListener() {
public void mouseReleased(MouseEvent e) {
if( isDragging ) {
isDragging = false;
selectionStart = samples.get(selectDragStart);
selectionEnd = samples.get(selectDragEnd);
validateValues();
ViewList.this.update();
}
}
public void mousePressed(MouseEvent e) {
if( e.getButton() == MouseEvent.BUTTON1 ) {
int x = (int) (e.getX() / scale);
if( x > 0 && x < samples.size() ) {
isDragging = true;
selectDragStart = x;
selectDragEnd = x;
validateValues();
}
}
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
addMouseMotionListener( new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
if( isDragging == false ) return;
int x = (int) (e.getX() / scale);
if( x > 0 && x < samples.size() ) {
if( x < selectDragStart ) {
selectDragStart = x;
} else {
selectDragEnd = x;
}
validateValues();
}
}
});
}
|
7bce5936-b541-4652-9ea2-1f71579c9279
| 6
|
public void greedyLetterSplit(List<String> motifList) {
String substring;
for (String s : motifList) {
for (int i = 0; i < 4; i++) {
substring = s.substring(i, i + 1);
switch (i) {
case 0:
this.A.add(Double.valueOf(substring));
break;
case 1:
this.C.add(Double.valueOf(substring));
break;
case 2:
this.G.add(Double.valueOf(substring));
break;
case 3:
this.T.add(Double.valueOf(substring));
break;
}
}
}
}
|
14b78770-9b18-494a-9124-5b02b57a1e49
| 6
|
public boolean valid() {
if (actor == null) return super.valid() ;
//
// TODO: Try to make this whole process more elegant. Establish the
// basic harvest-item from the beginning?
if (type == TYPE_HARVEST) {
if (actor.gear.amountOf(PROTEIN) > 0) return true ;
}
if (type == TYPE_PROCESS || type == TYPE_SAMPLE) {
final Item sample = Item.withReference(SAMPLES, prey) ;
if (actor.gear.amountOf(sample) > 0) return true ;
}
return super.valid() ;
}
|
0ca896b7-bb9b-4b61-8d34-9ef9e514b74c
| 5
|
@Override
protected ClosingsModel doInBackground() throws Exception {
closingsModel = new ClosingsModel();
Document schools = null;
try {
schools = Jsoup.connect(
bundle.getString("ClosingsURL"))
.timeout(10000)
.get();
Element table = schools.select("table").last();
Elements rows = table.select("tr");
for (int i = 1; i < rows.size(); i++) { //Skip header row
Element row = rows.get(i);
orgNames.add(row.select("td").get(0).text());
orgStatuses.add(row.select("td").get(1).text());
}
}catch (IOException e) {
//Connectivity issues
closingsModel.error = bundle.getString("WJRTConnectionError");
cancel(true);
}catch (NullPointerException | IndexOutOfBoundsException e) {
/* This shows in place of the table (as plain text)
if no schools or institutions are closed. */
if (schools != null && !schools.text().contains("no closings or delays")) {
//Webpage layout was not recognized.
closingsModel.error = bundle.getString("WJRTParseError");
cancel(true);
}
}finally{
parseClosings();
}
return closingsModel;
}
|
f0e2fbe7-df8b-4d0a-a81a-b3df1f1e9223
| 5
|
@SafeVarargs
public static final <T> boolean ins(T value, T... array) {
if (value == null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
return true;
}
}
} else {
for (int i = 0; i < array.length; i++) {
if (value.equals(array[i])) {
return true;
}
}
}
return false;
}
|
31bb3ec5-8f86-4c44-b131-44a07024b3b8
| 7
|
public String getCurrentDayTime(LocalTime time){
String interpretedDaytime = "";
LocalTime currentTime = time;
if(currentTime.isBefore(morningStart)){
interpretedDaytime = "night";
}
else if(currentTime.isAfter(morningStart)){
interpretedDaytime = "morning";
if(currentTime.isAfter(forenoonStart)){
interpretedDaytime = "forenoon";
if(currentTime.isAfter(lunchtimeStart)){
interpretedDaytime = "lunchtime";
if(currentTime.isAfter(afternoonStart)){
interpretedDaytime = "afternoon";
if(currentTime.isAfter(eveningStart)){
interpretedDaytime = "evening";
if(currentTime.isAfter(nightStart)){
interpretedDaytime = "night";
}
}
}
}
}
}
return interpretedDaytime;
}
|
b17c53e7-a0e3-4d91-9d47-8d46b28caa54
| 2
|
public static void main (String[] args) throws IOException, ParserConfigurationException, SAXException {
Parser ps = new Parser();
// File indirectory = new File("/home/dharmesh/aditya/author_profiling/pan_author_profiling_training_data/en/");
// File outdirectory = new File("/home/dharmesh/aditya/author_profiling/pan_author_profiling_training_data/enoutput/");
// File indirectory = new File("/home/dharmesh/aditya/author_profiling/pan_author_profiling_training_data/es/");
// File outdirectory = new File("/home/dharmesh/aditya/author_profiling/pan_author_profiling_training_data/esoutput/");
// File indirectory = new File("/home/dharmesh/aditya/sampler/");
// File outdirectory = new File("/home/dharmesh/aditya/sampleroutput/");
{
File indirectory = new File(args[0]+"/en");
File outdirectory = new File(args[1]+"/en");
outdirectory.mkdirs();
File[] inarray;
inarray=new File[10];
inarray=indirectory.listFiles();
System.out.println("starting");
for (int j = 0; j < inarray.length; j++)
{
File path=inarray[j];
String name = path.getName();
String filepath = indirectory+"/"+name;
ps.parse(filepath);
String trimname = name.substring(0,name.lastIndexOf('.'));
String outfilepath = "/"+trimname+".txt";
File outfile = new File(outdirectory, outfilepath);
BufferedWriter bout = new BufferedWriter(new FileWriter(outfile));
bout.write(conversationdata);
bout.close();
ps.temp="";
System.out.println(j);
}
}
{
File indirectory = new File(args[0]+"/es");
File outdirectory = new File(args[1]+"/es");
outdirectory.mkdirs();
File[] inarray;
inarray=new File[10];
inarray=indirectory.listFiles();
System.out.println("starting");
for (int j = 0; j < inarray.length; j++)
{
File path=inarray[j];
String name = path.getName();
String filepath = indirectory+"/"+name;
ps.parse(filepath);
String trimname = name.substring(0,name.lastIndexOf('.'));
String outfilepath = "/"+trimname+".txt";
File outfile = new File(outdirectory, outfilepath);
BufferedWriter bout = new BufferedWriter(new FileWriter(outfile));
bout.write(conversationdata);
bout.close();
ps.temp="";
System.out.println(j);
}
}
System.out.println("finished");
}
|
6a73dbae-13f7-40e7-9753-bec7097e3faf
| 2
|
public boolean canScroll(Direction scrollDirection) {
Point robot = model.getRobotLocation();
int topBorder = Math.abs(panel.getScroll());
int bottomBorder = Math.abs(panel.getScroll()) + panel.getHeight();
switch(scrollDirection) {
case DOWN:
return robot.y <= (topBorder + 50);
case UP:
return robot.y >= (bottomBorder - 50);
}
return false;
}
|
5c63d632-22b5-4d17-9fda-00342702eb6e
| 1
|
public static void setPointLights(PointLight[] pointLights) {
if (pointLights.length > MAX_POINT_LIGHTS) {
System.err
.println("Error: You passed in too many point lights. Max allowed is "
+ MAX_POINT_LIGHTS
+ ", you passed in "
+ pointLights.length);
new Exception().printStackTrace();
System.exit(1);
}
PhongShader.pointLights = pointLights;
}
|
ae39b47b-2d8a-48b6-b451-459450e6b1bd
| 8
|
synchronized public void startServer() {
try {
System.out.println("Server started");
do {
Socket accept = server.accept();
protocol = protocol.getClass().getConstructor(Socket.class).newInstance(accept);
new Thread(protocol).start();
} while (!isClosed);
} catch (NoSuchMethodException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ProtocolServer.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException();
}
}
|
d25d6524-de47-4f02-851f-a0d0268c69de
| 6
|
public void clicked() throws RealPlayerException {
Player realPlayer = null;
try {
realPlayer = Game.getInstance().getPlayerManager().getRealPlayer();
} catch (RealPlayerException e) {
e.printStackTrace();
return;
}
Base selectedBases = realPlayer.getSelectedBases();
// 1st case : the player doesn't have any selected base, so current one become his selected base (if it's his base) !
if(selectedBases == null) {
// if he selects a neutral base : nothing is done
if(this.getPlayer() == null){
System.out.println("1st case : it's a neutral base, you can't select it !");
}
// if he selects the base of an other player : nothing is done
else if((this.getPlayer().getName() != realPlayer.getName())){
System.out.println("1st case : it's not your base, you can't select it !");
}
// if he selects one of his base : we add the command selection
else if((this.getPlayer().getName() == realPlayer.getName())) {
SelectBase selectionCommand = new SelectBase(realPlayer, this);
Engine.getInstance().getCommands().add(selectionCommand);
//it sets the first point of Line, which is the coordinate of the first Base, i.e the SelectedBase
AppliWindow.getInstance().getLine().displayFirstPoint(this);
}
}
// 2nd case : current base is already selected by the realPlayer : nothing is done
else if (selectedBases.equals(this)) {
System.out.println("2nd case : Base from : "+realPlayer.getSelectedBases().getName()+" already selected.");
}
// 3rd case : the realPlayer has an other base selected : agents can go from the selected base to current one ! (and we deselect the base)
else {
Move moveCommand = new Move(realPlayer, selectedBases, this);
Engine.getInstance().getCommands().add(moveCommand);
}
System.out.println("J'ai cliqué sur la base numéro "+this.getId());
// Since a Base has the focus, we give back to the content the focus
System.out.println("Le Panel content reprend le focus");
AppliWindow.getInstance().getContent().requestFocusInWindow();
}
|
3e6281c8-2aea-49bd-91b1-d3fc78e63b57
| 4
|
private int jjMoveStringLiteralDfa34_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 33);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 33);
}
switch(curChar)
{
case 53:
return jjMoveStringLiteralDfa35_0(active0, 0x800000000000000L);
case 55:
return jjMoveStringLiteralDfa35_0(active0, 0x7ffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 34);
}
|
3e6a036b-46a9-4729-bd74-0d6c22d079d0
| 4
|
public void saveStatus(){
// EDebug.print("I have been called upon");
if (wait){
wait = false;
return;
}
// EDebug.print("\nFirst place");
// for (int i = 0; i < myDeck.size(); i++)
// EDebug.print(((LinkedList)myDeck).get(i).hashCode());
// if (myDeck.size() > 0)
// EDebug.print("The top of deck hash is " + myDeck.peek().hashCode());
myDeck.push((Automaton)myMaster.clone()); //push on head
// EDebug.print("The master that is getting pushed on has hascode = " + myMaster.hashCode());
System.out.println();
// EDebug.print("Second place");
// for (int i = 0; i < myDeck.size(); i++)
// EDebug.print(((LinkedList)myDeck).get(i).hashCode());
//
// EDebug.print("\n");
if (myDeck.size() >= 2)
{
Automaton first = myDeck.pop();
Automaton second = myDeck.pop();
// EDebug.print("The first is " + first.hashCode() + "While the second is " + second.hashCode());
if (first.hashCode() == second.hashCode()){
myDeck.push(first);
}
else{
myDeck.push(second);
myDeck.push(first);
myBackDeck.clear();
}
}
// EDebug.print("Third place");
// for (int i = 0; i < myDeck.size(); i++)
// EDebug.print(((LinkedList)myDeck).get(i).hashCode());
// EDebug.print(myDeck.size());
while (myDeck.size() > numUndo) myDeck.removeLast();
}
|
cd48235d-7be8-4c61-a7ca-bfd6e14e963f
| 9
|
public static void inspectObject(Object o) {
Class clazz = o.getClass();
Field[] fields = clazz.getDeclaredFields();
System.out.println("pola w klaise:");
for(Field f : fields) {
System.out.println(f.getName() + " typu: " + f.getType());
}
Method[] methods = clazz.getMethods();
System.out.println("metody w klasie");
for (Method m : methods) {
System.out.println(m.getName());
}
Constructor[] constructors = clazz.getConstructors();
System.out.println("konstruktory: ");
for(Constructor c : constructors) {
System.out.println(c.getName() + " " + Arrays.toString(c.getParameterTypes()) );
}
try {
Method m = clazz.getMethod("setName", String.class);
m.invoke(o, "Alicja");
Field f = clazz.getDeclaredField("name");
f.setAccessible(true);
f.set(o, "Jan");
} catch (NoSuchMethodException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(ReflectionTest.class.getName()).log(Level.SEVERE, null, ex);
}
Departament d = (Departament)o;
System.out.println(d.getName());
}
|
5cebc462-7cf5-4a11-b301-be8936e6bb63
| 2
|
public List<Room> getRoomList()
{
List<Room> list = new ArrayList<Room>();
try {
PreparedStatement ps = con.prepareStatement("SELECT * FROM rooms");
ResultSet rs = ps.executeQuery();
while( rs.next() )
{
list.add(getRoomFromRS(rs));
}
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
|
d507b089-7097-4258-a854-9fd103f464f5
| 3
|
private void editProjektledare() {
int val = JOptionPane.showConfirmDialog(null, "Om du tar bort personen som projektledare kommer alla projekt som denna personen hade att bli projektledarlösa.", "Är du säker?", JOptionPane.OK_CANCEL_OPTION);
if (val == JOptionPane.OK_OPTION) {
try {
String query = "Update spelprojekt set aid=null where aid=" + selectedAnstalld;
DB.update(query);
} catch (InfException e) {
e.getMessage();
}
try {
String query = "Delete from projektledare where aid=" + selectedAnstalld;
DB.delete(query);
} catch (InfException e) {
e.getMessage();
}
}
}
|
a2c33cb3-cbff-4d19-a997-c2f7107dce8b
| 2
|
public static BiCubicSpline zero(int nP, int mP){
if(nP<3 || mP<3)throw new IllegalArgumentException("A minimum of three x three data points is needed");
BiCubicSpline aa = new BiCubicSpline(nP, mP);
return aa;
}
|
1c80964a-dd54-4fa4-8535-4ea81cc031f8
| 0
|
public int getS1() {
return this.state1;
}
|
333a2471-4e1e-42c9-ac69-eb3230172b53
| 3
|
@Override
public Component getListCellRendererComponent( JList list,
Object value,
int index,
boolean selected,
boolean hasFocus ) {
JLabel result;
ItemObject itemObject;
ImageIcon icon;
String toolTip;
int width, height;
int labelWidth, iconGap;
FontMetrics fontMetrics;
result = (JLabel) super.getListCellRendererComponent( list, value, index,
selected, hasFocus );
if ( value instanceof ItemObject ) {
itemObject = (ItemObject) value;
icon = itemObject.getItemImage();
result.setBorder( GUI.borderList );
toolTip = "<html><font color=\"" + GUI.colorTipItemName + "\"><b>" +
itemObject.getItemName() + "</b></font><br/>" +
"<font color=\"" + GUI.colorTipItemType + "\">" +
ItemTypes.ITEM_TYPES[itemObject.getItemType()] + "</font></html>";
result.setToolTipText( toolTip );
result.setBackground( GUI.colorItemCell );
if ( itemObject.equals( _currentObject ) ) {
result.setBackground( GUI.colorItemSelCell );
} // if
if ( selected ) {
result.setBackground( GUI.colorItemFocusCell );
} // if
// this standardizes the alignment of the label in the list
result.setFont( GUI.fontSsB14 );
result.setIcon( icon );
iconGap = 5 + (GUI.DIM_ICON.width - icon.getIconWidth());
result.setIconTextGap( iconGap );
// this increases the width of the label to account for the icon and spacing
fontMetrics = result.getFontMetrics( result.getFont() );
labelWidth = fontMetrics.stringWidth( result.getText() );
width = (GUI.DIM_ICON.width * 2) + labelWidth;
height = GUI.DIM_ICON.height;
result.setPreferredSize( new Dimension( width, height ) );
result.setMinimumSize( new Dimension( width, height ) );
result.setMaximumSize( new Dimension( width, height ) );
} // if
return result;
} // getListCellRendererComponent --------------------------------------------
|
e50acff0-08e3-4f1d-8190-29524ba58b37
| 8
|
protected void compareDatasets(Instances data1, Instances data2)
throws Exception {
if (!data2.equalHeaders(data1)) {
throw new Exception("header has been modified\n" + data2.equalHeadersMsg(data1));
}
if (!(data2.numInstances() == data1.numInstances())) {
throw new Exception("number of instances has changed");
}
for (int i = 0; i < data2.numInstances(); i++) {
Instance orig = data1.instance(i);
Instance copy = data2.instance(i);
for (int j = 0; j < orig.numAttributes(); j++) {
if (orig.isMissing(j)) {
if (!copy.isMissing(j)) {
throw new Exception("instances have changed");
}
} else if (orig.value(j) != copy.value(j)) {
throw new Exception("instances have changed");
}
if (orig.weight() != copy.weight()) {
throw new Exception("instance weights have changed");
}
}
}
}
|
dc007b76-4ab5-4f41-8203-8f2774556ce6
| 1
|
public Key max()
{
if (N == 0)
throw new RuntimeException("Priority Queue Underflow");
return pq[1];
}
|
f7e43c59-244d-4657-aa53-0c1ca7fbb019
| 3
|
int writeUntilPattern(OutputStream streamOut, byte[] pattern)
throws IOException {
int indexOfPattern;
int bytesWritten = 0;
do {
int bytesRead = fillFromStream();
indexOfPattern = indexOf(pattern);
if (indexOfPattern == -1) { // No patterns in buffer
if (bytesRead == 0) { // End of stream
throw new IOException("Pattern not found.");
}
// Here we try to be clever by leaving pattern.length-1 bytes
// unwritten. That way, if we have part of the pattern at the
// end of the buffer, it will be joined with the other part
// when we fill the buffer again, making a whole pattern,
// which will be detected in the next call to indexOf(pattern).
bytesWritten += writeToStream(
streamOut,
virtualSize - (pattern.length - 1));
}
} while (indexOfPattern == -1);
// Write out the rest until the pattern, then skip the pattern.
bytesWritten += writeToStream(streamOut, indexOfPattern);
skip(pattern.length);
return bytesWritten;
}
|
ccc3cf6a-4525-4d3b-a24c-ed2d561e51ca
| 7
|
public void deleteFromCursor(int par1)
{
if (text.length() == 0)
{
return;
}
if (selectionEnd != cursorPosition)
{
writeText("");
return;
}
boolean flag = par1 < 0;
int i = flag ? cursorPosition + par1 : cursorPosition;
int j = flag ? cursorPosition : cursorPosition + par1;
String s = "";
if (i >= 0)
{
s = text.substring(0, i);
}
if (j < text.length())
{
s = (new StringBuilder()).append(s).append(text.substring(j)).toString();
}
text = s;
if (flag)
{
func_73784_d(par1);
}
}
|
a32d8bc9-7ba5-4e36-b206-20ea7b56e8b9
| 9
|
public void processResult(int rc, String path, Object ctx, Stat stat) {
boolean exists;
switch (rc) {
case Code.Ok:
exists = true;
break;
case Code.NoNode:
exists = false;
break;
case Code.SessionExpired:
case Code.NoAuth:
needReInit = true;
// listener.closing(rc);
exe.execute(onClosing);
return;
default:
// Retry errors
zk.exists(znode, true, this, null);
return;
}
byte b[] = null;
if (exists) {
b=currentData();
}
Long hash = hash(b);
if ((b == null && null != prevDataHash)
|| (b != null && !hash.equals(prevDataHash))) {
final byte[] data = b;
exe.execute(new Runnable() {
@Override
public void run() {
listener.onDataChanged(data);
}
});
prevDataHash = hash;
}
}
|
3a43782f-0f58-4f0f-9137-3d4273756340
| 5
|
public static int search(String source, String pattern) {
int index = -1;
int sLen = source.length();
int pLen = pattern.length();
int i = 0;
while (i <= sLen - pLen) {
int j = 0;
while (j < pLen && source.charAt(i + j) == pattern.charAt(j)) {
j++;
}
if (j == pLen) {
return i;
} else if (j == 0) {
i++;
} else {
i = i + j - 1 - partialMatchTable[j - 1];
}
}
return index;
}
|
b9d4306e-93b2-4352-be95-b79062f1267b
| 0
|
public void resizeWatcher(){
this.addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentResized(ComponentEvent event)
{
environment.resizeSplit();
}
});
}
|
00c0df76-1e99-4624-aa89-5fca2c9fae1a
| 6
|
void removeAgent(int memberId, int memberType, String userName)
{
switch (memberType)
{
case GameController.passiveUser: case GameController.userContributor: case GameController.userBugReporter:
case GameController.userTester: case GameController.userCommitter: case GameController.userLeader:
gameController.Print("Server: User " + userName + " with the ID " + memberId + " has been Disconnected to server");
break;
default:
gameController.Print("Server: Agent " + memberId + " Disconnected to server");
break;
}
}
|
b473d225-7941-47ed-891a-a494df1e051d
| 2
|
public static void printBoolVal(String pre, char str, String suf){
if(str == '0' ){
System.out.printf(pre+"false"+suf);
}
else if(str == '1' ){
System.out.printf(pre+"true"+suf);
}
else{
System.out.printf("Error occured, printed "+str+"\n");
}
}
|
9320fad4-5be1-471a-835f-15f86f68d9c9
| 7
|
public void renderLevel() {
int pixelIndex;
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
int xAbs = x + cameraXCoord;
int yAbs = y + cameraYCoord;
pixelIndex = (x + cameraXCoord) + (y + cameraYCoord) * SpriteSheets.mainStage.getXSheetSize();
if(xAbs > 0 && yAbs > 0 && xAbs < SpriteSheets.mainStage.getXSheetSize() && yAbs < SpriteSheets.mainStage.getYSheetSize()) {
if(SpriteSheets.mainStage.getSpriteSheetsPixels(pixelIndex) != 0xffff00ff) {
pixels[x + y * width] = SpriteSheets.mainStage.getSpriteSheetsPixels(pixelIndex);
}
}
}
}
}
|
36e5905e-9e8a-4370-80e7-86117c3d12de
| 3
|
public Polynomial(long[] coeff) {
int len = 0;
for (int i = coeff.length - 1; i >= 0; i--) { // remove heading zeroes
if (coeff[i] != 0) {
len = i + 1;
break;
}
}
if (len < coeff.length) {
long[] new_coeff = new long[len];
System.arraycopy(coeff, 0, new_coeff, 0, len);
coeff = new_coeff;
}
this.coeff = coeff;
}
|
f92d95ff-efbf-4c1e-b269-86e937e99dc6
| 9
|
@Override
public int isInside(int p_x, int p_y)
{
for (Rectangle r : rectList)
{
if((r.getX()<p_x && p_x<(r.getX()+width)) && (r.getY()<p_y && p_y<(r.getY()+height)))
{
return rectList.indexOf(r);
}
}
if((getX()<p_x && p_x<(getX()+width)) && (getY()<p_y && p_y<(getY()+height)))
{
return 10; //is in canvas
}
else
{
return -1; //not inside of anything
}
}
|
b0d5ac79-1b86-4c69-91ac-852c93ab851b
| 5
|
public static BrazilianAnalyzer getAnalyzer(boolean stopwords, boolean stemming) {
if(stemming) {
if(stopwords) {
return new BrazilianAnalyzer(Version.LUCENE_48);
}
else {
Analyzer a = new SnowballAnalyzer(Version.LUCENE_48, "Portuguese");
if(a instanceof BrazilianAnalyzer) {
System.out.println("IsTrue");
}
else if(a instanceof PortugueseAnalyzer) {
System.out.println("IsTrue2");
}
else {
System.out.println("Fudeu");
}
return new BrazilianAnalyzer(Version.LUCENE_48, CharArraySet.EMPTY_SET);
}
}
else {
if(stopwords) {
return new BrazilianAnalyzer(Version.LUCENE_48, BrazilianAnalyzer.getDefaultStopSet(), CharArraySet.EMPTY_SET);
}
else {
return new BrazilianAnalyzer(Version.LUCENE_48, CharArraySet.EMPTY_SET, CharArraySet.EMPTY_SET);
}
}
}
|
48cd020c-b422-4fc4-adaf-afb022e07c35
| 3
|
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
}
|
cd27276d-f138-433b-8397-ada8a07ebc5c
| 1
|
private synchronized static void createInstance() {
if (instance == null) {
instance = new BookingService();
}
}
|
48e78214-7162-4dd7-be8b-2d94a80a184b
| 6
|
private MalformedJsonException jsonError(String msg, boolean printAll){
if(printAll){
//SB for faster error print! Not like that it'd matter...
//MAX size (can be smaller): text before current text after \n spaces before ^
StringBuilder err = new StringBuilder(ERR_PRINT_BEFORE + 1 + ERR_PRINT_AFTER + 1 + ERR_PRINT_BEFORE + 1);
//1st line: error + nearby text
for (Object o:errBuffer.getElements()) err.append(o); //h4x
for(int i=0; i<ERR_PRINT_AFTER; i++){
int c;
try{
c = INPUT.read();
}catch(Exception ignored){
break;
}
if (c==-1) break;
err.append((char)c);
}
err.append('\n');
//2nd line: mark the place
for (int i=1; i<errBuffer.size(); i++) err.append(' ');
err.append('^');
return new MalformedJsonException("JSON malformed: "+msg+"\n"+err);
}else{
return new MalformedJsonException("JSON malformed: "+msg);
}
}
|
74982b59-0f27-4554-a1f0-fc3da24e44c5
| 2
|
public static double viscosity(double temperature){
double[] tempc = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100};
double[] visc = {0.0017921, 0.0017313, 0.0016728, 0.0016191, 0.0015674, 0.0015188, 0.0014728, 0.0014284, 0.001386, 0.0013462, 0.0013077, 0.0012713, 0.0012363, 0.0012028, 0.0011709, 0.0011404, 0.0011111, 0.0010828, 0.0010559, 0.0010299, 0.001005, 0.000981, 0.0009579, 0.0009358, 0.0009142, 0.0008937, 0.0008737, 0.0008545, 0.000836, 0.000818, 0.0008007, 0.000784, 0.0007679, 0.0007523, 0.0007371, 0.0007225, 0.0007085, 0.0006947, 0.0006814, 0.0006685, 0.000656, 0.0006439, 0.0006321, 0.0006207, 0.0006097, 0.0005988, 0.0005883, 0.0005782, 0.0005683, 0.0005588, 0.0005494, 0.0005404, 0.0005315, 0.0005229, 0.0005146, 0.0005064, 0.0004985, 0.0004907, 0.0004832, 0.0004759, 0.0004688, 0.0004618, 0.000455, 0.0004483, 0.0004418, 0.0004355, 0.0004293, 0.0004233, 0.0004174, 0.0004117, 0.0004061, 0.0004006, 0.0003952, 0.00039, 0.0003849, 0.0003799, 0.000375, 0.0003702, 0.0003655, 0.000361, 0.0003565, 0.0003521, 0.0003478, 0.0003436, 0.0003395, 0.0003355, 0.0003315, 0.0003276, 0.0003239, 0.0003202, 0.0003165, 0.000313, 0.0003095, 0.000306, 0.0003027, 0.0002994, 0.0002962, 0.000293, 0.0002899, 0.0002868, 0.0002838};
double[] deriv = {0, 1.78373e-006, 6.66507e-006, 3.55981e-007, 3.911e-006, 2.60001e-006, 1.28896e-006, 1.84413e-006, 3.3345e-006, 4.1785e-007, 2.7941e-006, 1.00576e-006, 1.58285e-006, 1.66282e-006, 1.36586e-006, 1.27374e-006, 7.39187e-007, 1.76951e-006, 5.82755e-007, 1.29947e-006, 8.1938e-007, 8.23013e-007, 1.28857e-006, 2.27218e-008, 1.62055e-006, 9.50918e-008, 9.99086e-007, 7.08563e-007, 3.66662e-007, 8.24789e-007, 5.34182e-007, 6.38482e-007, 5.1189e-007, 3.13959e-007, 6.32274e-007, 7.56944e-007, -6.00505e-008, 6.83258e-007, 3.27018e-007, 4.08669e-007, 4.38304e-007, 2.38113e-007, 4.09244e-007, 5.24909e-007, -1.08882e-007, 5.10619e-007, 4.66404e-007, 2.3763e-008, 6.38544e-007, -1.77938e-007, 6.73209e-007, -1.14896e-007, 3.86377e-007, 3.69389e-007, -6.39346e-008, 4.86349e-007, -8.14616e-008, 4.39497e-007, 1.23473e-007, 2.66612e-007, 1.00779e-008, 2.93076e-007, 1.76187e-008, 2.36449e-007, 2.36584e-007, 1.72156e-008, 2.94554e-007, 4.56925e-009, 2.87169e-007, 4.67538e-008, 1.25815e-007, 4.99845e-008, 2.74247e-007, 5.30292e-008, 1.13637e-007, 9.24242e-008, 1.16667e-007, 4.09095e-008, 3.19695e-007, -1.19691e-007, 1.59069e-007, 8.34135e-008, 1.07277e-007, 8.74801e-008, 1.42803e-007, -5.86918e-008, 9.19641e-008, 2.90835e-007, -5.53049e-008, -6.96157e-008, 3.33768e-007, -6.54552e-008, -7.19471e-008, 3.53244e-007, -1.41027e-007, 2.10865e-007, -1.02433e-007, 1.98866e-007, -9.30309e-008, 1.73258e-007, 0};
double viscosity;
int n = tempc.length;
if(temperature>=tempc[0] && temperature<=tempc[n-1]){
viscosity=CubicSpline.interpolate(temperature, tempc, visc, deriv);
}
else{
throw new IllegalArgumentException("Temperature outside the experimental data limits");
}
return viscosity;
}
|
21851c7f-e554-496a-86d0-3cc5a0b270e2
| 8
|
public static int getLevenshteinDistance(String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
The difference between this impl. and the previous is that, rather
than creating and retaining a matrix of size s.length()+1 by t.length()+1,
we maintain two single-dimensional arrays of length s.length()+1. The first, d,
is the 'current working' distance array that maintains the newest distance cost
counts as we iterate through the characters of String s. Each time we increment
the index of String t we are comparing, d is copied to p, the second int[]. Doing so
allows us to retain the previous cost counts as required by the algorithm (taking
the minimum of the cost count to the left, up one, and diagonally up and to the left
of the current cost count being calculated). (Note that the arrays aren't really
copied anymore, just switched...this is clearly much better than cloning an array
or doing a System.arraycopy() each time through the outer loop.)
Effectively, the difference between the two implementations is this one does not
cause an out of memory condition when calculating the LD over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
|
3d8f8ad0-4223-408f-992a-2f45012f304c
| 1
|
public void override(Identificador id, int nivel)
throws IdentificadorJaDefinidoException{
verificarIdPrograma(id);
HashMap<String, Identificador> tabelaNivel = tabela.get(nivel);
if(!tabelaNivel.containsKey(id.getNome()))
throw new RuntimeException("Este identificador não existe para ser sobreescrito");
tabelaNivel.put(id.getNome(), id);
}
|
856aa739-3c46-448f-9f7c-5efda0ef44d6
| 1
|
public void testConstructor_ObjectStringEx1() throws Throwable {
try {
new LocalDateTime("1970-04-06T+14:00");
fail();
} catch (IllegalArgumentException ex) {}
}
|
7e2b67d7-4ce9-4189-8386-a8bd8f8cc9d4
| 3
|
public Move chooseMove(State s) {
// remember who we are so we can correctly evaluate states
me = s.whoseTurn();
// The rest of this function looks a lot like evalMove, except
// that it doesn't just track the minimaxvalue, but also the
// best move itself.
// get a list of possible moves
MyList moves = s.findMoves();
Collections.shuffle(moves);
// shuffle so we don't always take the same maximum
// return if there are no moves
if (moves.size() == 0)
return null;
// Iterate over all moves
Iterator it = moves.iterator();
// We already know there is at least one move, so use it to
// initialize minimaxvalue
Move bestMove = (Move) it.next();
int minimaxvalue = evalMove(bestMove, s, maxdepth);
// now the rest of the moves
while (it.hasNext()) {
Move move = (Move) it.next();
int eval = evalMove(move, s, maxdepth);
// if we found a better move, remember it
if (eval > minimaxvalue) {
minimaxvalue = eval;
bestMove = move;
}
}
return bestMove;
}
|
d443c97a-ca3e-417b-bfaf-3683ff803e6d
| 6
|
public void kill(String target) {
if(target.equals("No thx")) {
DataOutputStream dOut = this.outputs.get(firstPlayer);
String msg = "WHO_FIRST_PLAYER";
Set<Player> pSet= outputs.keySet();
for(Player p : pSet)
{
if(!p.getName().equals(renfield.getName()))
{
if(firstPlayer.getName() != p.getName()) {
msg += ";" + p.getName();
}
}
}
System.out.println(msg);
try {
dOut.writeUTF(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
String role = getPlayerByName(target).getRole();
if(role.equals(GameBoard.VAMPIRE)) {
sendToAll("HUNTERS_WIN");
}
else {
sendToAll("VAMPIRE_SECOND_WIN:" + target);
}
}
}
|
0826a76e-032e-40ab-b227-b9f810e4fe2e
| 6
|
public static void main(String[] args) {
// create random bipartite graph with V vertices and E edges; then add F random edges
int V = Integer.parseInt(args[0]);
int E = Integer.parseInt(args[1]);
int F = Integer.parseInt(args[2]);
Graph G = new Graph(V);
int[] vertices = new int[V];
for (int i = 0; i < V; i++) vertices[i] = i;
StdRandom.shuffle(vertices);
for (int i = 0; i < E; i++) {
int v = StdRandom.uniform(V/2);
int w = StdRandom.uniform(V/2);
G.addEdge(vertices[v], vertices[V/2 + w]);
}
// add F extra edges
for (int i = 0; i < F; i++) {
int v = (int) (Math.random() * V);
int w = (int) (Math.random() * V);
G.addEdge(v, w);
}
StdOut.println(G);
Bipartite b = new Bipartite(G);
if (b.isBipartite()) {
StdOut.println("Graph is bipartite");
for (int v = 0; v < G.V(); v++) {
StdOut.println(v + ": " + b.color(v));
}
}
else {
StdOut.print("Graph has an odd-length cycle: ");
for (int x : b.oddCycle()) {
StdOut.print(x + " ");
}
StdOut.println();
}
}
|
df027416-9f71-407d-947f-8d2794e01882
| 0
|
public void setFunAaaa(Integer funAaaa) {
this.funAaaa = funAaaa;
}
|
7c60bc74-e189-4c4e-8690-a14e0f5418ed
| 9
|
public static Vector<String> getNasdaqSymbols()
{
String strUrl = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
Vector<String> symbols = new Vector<String>();
String line;
URL url;
InputStream is = null;
BufferedReader br;
String currentSymbol=null;
try
{
url = new URL(strUrl);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null)
{
currentSymbol=line.split(",")[0];
if(currentSymbol.contains(" "))
{
currentSymbol = (currentSymbol.split(" ")[0]).concat("\"");
}
if(currentSymbol.contains("^"))
{
currentSymbol = currentSymbol.replace('^', ' ');
currentSymbol = (currentSymbol.split(" ")[0]).concat("\"");
}
else if(currentSymbol.contains("/"))
{
currentSymbol = currentSymbol.replace('/', ' ');
currentSymbol = (currentSymbol.split(" ")[0]).concat("\"");
}
else if(currentSymbol.contains("$"))
{
currentSymbol = currentSymbol.replace('$', ' ');
currentSymbol = (currentSymbol.split(" ")[0]).concat("\"");
}
if(!symbols.contains(currentSymbol) && !currentSymbol.equals("\"Symbol\""))
{
symbols.add(currentSymbol);
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
symbols.remove(0);
return symbols;
}
|
438c8ab6-8280-4a16-b38b-54f7b8d83f62
| 2
|
public Grille incrementGeneration(double nbrGenerations) {
while (nbrGenerations >= 1) {
generation += 1.0;
nbrGenerations -= 1.0;
grid = nextGeneration();
}
if (generation + nbrGenerations >= Math.floor(generation) + 1) {
// Une dernière fois
grid = nextGeneration();
}
generation += nbrGenerations;
return this;
}
|
c884dd00-c4a1-40a5-82cf-5221a10767ad
| 7
|
public List<Command> compile(String code) {
if (!validCharSet(code) || !validBrackets(code)) {
System.out.println("Compilation error.\n");
return null;
}
List<Command> commands = new ArrayList<>(); // output
Deque<Cycle> cyclesStack = new ArrayDeque<>();
Cycle currentCycle = null;
char[] chars = code.toCharArray();
for (char c : chars) {
if (c == '[') { // начался цикл
Cycle cycle = new Cycle();
if (currentCycle != null) { // если true, значит новый цикл открывается внутри текущего
currentCycle.addCommand(cycle); // добвляем команду Cycle к командам текущего цикла
cyclesStack.push(currentCycle); // текущий цикл сохраняем в стек
} else // это цикл верхнего уровня, добавляем его в основные команды
commands.add(cycle);
currentCycle = cycle; // замена текущего цикла (или null-а, если цикла еще не было) - только что созданным циклом.
continue;
} else if (c == ']') { // цикл закончился
// получаем из стека предыдущий цикл (согласно вложенностям)
// если закончился цикл верхнего уровня - текущему циклу присваивается null
currentCycle = cyclesStack.poll();
continue;
}
if (currentCycle != null) // true если сейчас читаются команды внутри цикла верхнего уровня
currentCycle.addCommand(SimpleCommandsFactory.createCommand(c));
else // обычная команда (не в цикле)
commands.add(SimpleCommandsFactory.createCommand(c));
}
return commands;
}
|
e7251138-1e59-45e1-b19d-9624477b0c80
| 4
|
private void notifyMissingAuthService(String type) {
for (ComponentEntry ac : this.accessControllers.values()) {
if (ac.activeType.equals(type)) {
IAuthorization available = availableAuthorization(ac.preferredType);
if (available == null) {
available = availableAuthorization(ac.altType);
}
Message msg = new Message(Message.Type.CHANGE_AUTH, ac.id, Message.MANAGER);
String newType;
if (available != null) {
ac.activeType = available.getType().name();
newType = ac.activeType;
msg.addData(Message.Field.AUTH_TYPE, available.getType().name());
}
else {
ac.activeType = null;
newType = ComponentTypes.Authorization.NOT_AVAILABLE.name();
msg.addData(Message.Field.AUTH_TYPE, ComponentTypes.Authorization.NOT_AVAILABLE.name());
}
hydnaSvc.sendMessage(Serializer.serialize(msg));
System.out.println("Changed authorization type for "+ac.id+" to "+newType);
}
}
}
|
a1a2b97e-0753-4739-90e6-8b8cfa7ac2dd
| 9
|
public static boolean isValid( String s ){
if ( s == null )
return false;
final int len = s.length();
if ( len != 24 )
return false;
for ( int i=0; i<len; i++ ){
char c = s.charAt( i );
if ( c >= '0' && c <= '9' )
continue;
if ( c >= 'a' && c <= 'f' )
continue;
if ( c >= 'A' && c <= 'F' )
continue;
return false;
}
return true;
}
|
72c579d7-916c-47f0-b54a-55bae5778be5
| 7
|
public static Rule_dirClass parse(ParserContext context)
{
context.push("dirClass");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_StringValue.parse(context, ".class");
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_dirClass(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("dirClass", parsed);
return (Rule_dirClass)rule;
}
|
f55c8be4-c420-4ffe-92aa-2f5ccff2e73f
| 3
|
private static void inputgraph() throws FileNotFoundException {
// TODO Auto-generated method stub
int i=0;
File f = new File("src/Prim.txt");
Scanner sr = new Scanner(f);
for (i = 0; i < 502; i++) {
graph.add(new ArrayList<Integer>());
}
sr.next();
sr.next();
int l,m,n;
while(sr.hasNext()){
l = sr.nextInt();
m = sr.nextInt();
graph.get(l).add(m);
graph.get(m).add(l);
n = sr.nextInt();
edgewieght[l][m] = n;
edgewieght[m][l] = n;
}
for(i =0;i<501;i++){
System.out.print(graph.get(i));
System.out.print("\n");
}
}
|
29a9bade-60e4-4b8e-8a08-d04f3d49d685
| 7
|
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
|
89134edf-3e3c-4770-bf16-1a24f82a3502
| 1
|
public static Duration safeMinus(Duration max, Duration current) {
if (max.isShorterThan(current)) {
return new Duration(0);
} else {
return max.minus(current);
}
}
|
04f4b8ae-eff2-44d6-b72b-43d91336e862
| 6
|
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
for(int ii = 0;ii<10;ii++){
for(int i=0;i<10;i++){
x=i*BLOCK;
y=ii*BLOCK;
g2d.drawImage(bia[grid[ii][i]], x,y, this);
}
aa = MF.getArmies();
bb = MF.getBarbs();
if(aa.size()>0){
for (int i = 0; i < aa.size(); i++) {
Army a = (Army)aa.get(i);
g2d.drawImage(a.getImage(), a.getX()*BLOCK, a.getY()*BLOCK, this);
}
}
if(bb.size()>0){
for (int i = 0; i < bb.size(); i++) {
Barb b = (Barb)bb.get(i);
g2d.drawImage(b.getImage(), b.getX()*BLOCK, b.getY()*BLOCK, this);
}
}
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
|
bdb63981-194a-4d48-9d84-ae7caeefc5b5
| 9
|
public static BigInt bigIntegerMult(BigInt x, BigInt y) {
/* If one of the numbers is 0, return 0 */
if (x.size() == 1 && x.testCharZero()) {
return new BigInt("0");
}
if (y.size() == 1 && y.testCharZero()) {
return new BigInt("0");
}
/* Define result: with proper size and sign */
BigInt result = new BigInt(x.size() + y.size());
result.setSign(x.getSign() * y.getSign());
/* Iterate first over the multiplicand */
for (int i = 0; i < y.size(); i++) {
if (y.digits[i] == 0) { continue; }
int carryOn = 0;
/* Iterate second through the source */
for (int j = 0; j < x.size() || carryOn > 0; j++) {
/* Grab current value of target digit for this iteration */
int currDigit = result.digits[i + j];
if (j < x.size()) {
currDigit = currDigit + (y.digits[i] * x.digits[j]) + carryOn;
}else {
currDigit = currDigit + carryOn;
}
result.digits[i + j] = currDigit % 10;
carryOn = currDigit / 10;
}
}
result.setString(result.digitsToString());
return result;
}
|
4902f9be-a89c-4928-8936-c27849dff1f8
| 8
|
public void create(Servidor servidor) throws PreexistingEntityException, RollbackFailureException, Exception {
if (servidor.getComputadoraCollection() == null) {
servidor.setComputadoraCollection(new ArrayList<Computadora>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<Computadora> attachedComputadoraCollection = new ArrayList<Computadora>();
for (Computadora computadoraCollectionComputadoraToAttach : servidor.getComputadoraCollection()) {
computadoraCollectionComputadoraToAttach = em.getReference(computadoraCollectionComputadoraToAttach.getClass(), computadoraCollectionComputadoraToAttach.getIdComputadora());
attachedComputadoraCollection.add(computadoraCollectionComputadoraToAttach);
}
servidor.setComputadoraCollection(attachedComputadoraCollection);
em.persist(servidor);
for (Computadora computadoraCollectionComputadora : servidor.getComputadoraCollection()) {
Servidor oldServidoridServidorOfComputadoraCollectionComputadora = computadoraCollectionComputadora.getServidoridServidor();
computadoraCollectionComputadora.setServidoridServidor(servidor);
computadoraCollectionComputadora = em.merge(computadoraCollectionComputadora);
if (oldServidoridServidorOfComputadoraCollectionComputadora != null) {
oldServidoridServidorOfComputadoraCollectionComputadora.getComputadoraCollection().remove(computadoraCollectionComputadora);
oldServidoridServidorOfComputadoraCollectionComputadora = em.merge(oldServidoridServidorOfComputadoraCollectionComputadora);
}
}
em.getTransaction().commit();
} catch (Exception ex) {
try {
em.getTransaction().rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findServidor(servidor.getIdServidor()) != null) {
throw new PreexistingEntityException("Servidor " + servidor + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
|
6910cdad-ab13-42f4-9e38-5eb19df51a35
| 4
|
public static String formatTextAsString(Text text) {
StringBuilder sb = new StringBuilder();
for (Sentence textpart : text.getAllElements()) {
if (textpart.getClass().equals(Listing.class)) {
Listing listing = (Listing) textpart;
sb.append(listing.getValue());
}
for (SentencePart part : textpart.getAllElements()) {
if (part instanceof Word) {
Word word = (Word) part;
sb.append(" ").append(word.getValue());
} else {
Punctuation punctuation = (Punctuation) part;
sb.append(punctuation.getValue());
}
}
sb.append("\n");
}
return sb.toString();
}
|
0d83bd3d-12d8-4fce-b76b-262e0212f1b8
| 9
|
public void propertyChange(PropertyChangeEvent ev) {
if (!isEditing() || getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) { //NOI18N
return;
}
Component c = focusManager.getPermanentFocusOwner();
while (c != null) {
if (c == JListMutable.this) {
// focus remains inside the table
return;
} else if ((c instanceof Window) ||
(c instanceof Applet && c.getParent() == null)) {
if (c == SwingUtilities.getRoot(JListMutable.this)) {
if (!getListCellEditor().stopCellEditing()) {
getListCellEditor().cancelCellEditing();
}
}
break;
}
c = c.getParent();
}
}
|
ada38cec-3025-448f-b6b4-701d94b83e70
| 3
|
public void setUpComboBoxes(Set<Card> cards) {
for (Card card : cards) {
String name = card.getName();
if (card.getType().equals(CardType.PERSON)) {
peoplePossibilities.addItem(name);
} else if (card.getType().equals(CardType.ROOM)) {
roomsPossibilities.addItem(name);
} else {
weaponsPossibilities.addItem(name);
}
}
// -1 indicates no selection
roomsPossibilities.setSelectedIndex(-1);
peoplePossibilities.setSelectedIndex(-1);
weaponsPossibilities.setSelectedIndex(-1);
personGuess.add(peoplePossibilities);
roomGuess.add(roomsPossibilities);
weaponGuess.add(weaponsPossibilities);
}
|
03defb2f-0037-4773-b318-39a50be65b6f
| 2
|
private void calcNormals(Vertex[] vertices, int[] indices) {
for (int i = 0; i < indices.length; i += 3) {
int i0 = indices[i];
int i1 = indices[i + 1];
int i2 = indices[i + 2];
Vector3f v1 = vertices[i1].getPos().sub(vertices[i0].getPos());
Vector3f v2 = vertices[i2].getPos().sub(vertices[i0].getPos());
Vector3f normal = v1.cross(v2).normalized();
vertices[i0].setNormal(vertices[i0].getNormal().add(normal));
vertices[i1].setNormal(vertices[i1].getNormal().add(normal));
vertices[i2].setNormal(vertices[i2].getNormal().add(normal));
}
for (int i = 0; i < vertices.length; i++)
vertices[i].getNormal().set(vertices[i].getNormal().normalized());
}
|
68a2db50-91dd-4861-878e-37449a118ff8
| 5
|
private boolean sendFailures() {
int event_type;
int i,k;
int avg_event = 0;
logger.log(Level.INFO, super.get_name() + " is sending failures to " +
GridSim.getEntityName(resID) + " ...");
List<FailureEvent> events = model.generateFailure();
if(events == null) {
return false;
}
// map the node IDs to the range of 0...#nodes
Hashtable<Integer, Integer> ids = new Hashtable<Integer, Integer>();
k = 0;
for (FailureEvent ev : events){
int id = ev.getNodeID(); // node id
ids.put(id, new Integer(k));
k++;
int numEvents = ev.getnumEvent(); // number of events
avg_event += numEvents;
// logger.log(Level.INFO, "Node: " + id + " has " + ev.getnumEvent()+ " events.");
for (i=0; i<numEvents; i++){
event_type = ev.geteventType(i); // get event type
// send the resource failure event
if (event_type==0){
super.send(resID, ev.getstartTime(i),GridSimTags.GRIDRESOURCE_FAILURE, ids.get(id));
}
// send the resource recovery event
if (event_type==1){
super.send(resID, ev.getstartTime(i),GridSimTags.GRIDRESOURCE_RECOVERY, ids.get(id));
}
}
}
logger.log(Level.INFO, "Average Event per Node:" + avg_event/k);
return true;
}
|
acf7f09b-50bf-433e-9c67-75fed6ef6731
| 7
|
private ArrayList<String> parseMap(JLD raw, int layer){
ArrayList<String> out = new ArrayList<String>();
String st;
out.add(indent(layer) + "{");
layer++;
for(String key : raw.keySet()){
st = indent(layer);
if(key.contains("\""))
st += "'" + key + "' : ";
else
st += "\"" + key + "\" : ";
Object val = raw.get(key);
if(val instanceof ArrayList){
st += parseArrayList((ArrayList)val, layer+1);
st += ",";
}else if(val instanceof LinkedHashMap){
out.add(st);
JLD jldt = new JLD((LinkedHashMap)val);
ArrayList<String> nested = parseMap(jldt, layer+1);
st = "";
for(String s : nested){
st += s;
}
out.add(st);
st = out.get(out.size()-1) + ",";
out.remove(out.size()-1);
}else if(val.toString().contains("\"")){
st += "'" + val + "',";
}else{
st += "\"" + val + "\",";
}
out.add(st);
}
out.set(out.size()-1, out.get(out.size()-1).substring(0, out.get(out.size()-1).length()-1));
for(int i=0; i<out.size(); i++){
out.set(i,out.get(i)+"\r\n");
}
layer--;
out.add(indent(layer)+"}");
return out;
}
|
bd9ebf7a-ad87-40cd-9def-3cb45a0f499e
| 3
|
public static ErrorCode getCodeByName(String name) {
if (StringUtils.isEmpty(name)) {
return null;
}
for (ErrorCode code : values()) {
if (StringUtils.equals(code.name(), name)) {
return code;
}
}
return null;
}
|
3281deac-f4c2-4322-9d24-89b980062912
| 0
|
public static void main(String[] args)
{
Watched watched = new ConcreteWatched();
watched.addWatcher(new ConcreteWatcher());
watched.addWatcher(new ConcreteWatcher());
watched.addWatcher(new ConcreteWatcher());
watched.notified("Observer Test !");
}
|
84260e60-7948-4aec-88c2-7d51f19e9068
| 5
|
public static Categorie creerCategorie(Categorie categorieParent, String nom, Icone icone, Utilisateur utilisateur, Role consultationRoleMinimum, Role reponseRoleMinimum, Role sujetRoleMinimum)
throws ChampInvalideException, ChampVideException {
if (!categorieParent.peutCreerCategorie(utilisateur))
throw new InterditException("Vous n'avez pas les droits requis pour créer une catégorie");
EntityTransaction transaction = CategorieRepo.get().transaction();
Categorie c;
try {
transaction.begin();
c = genererCategorie(categorieParent, nom, icone, consultationRoleMinimum, reponseRoleMinimum, sujetRoleMinimum);
CategorieRepo.get().creer(c);
transaction.commit();
}
catch(Exception e) {
if (transaction.isActive())
transaction.rollback();
if (e instanceof ChampVideException)
throw (ChampVideException)e;
else if (e instanceof ChampInvalideException)
throw (ChampInvalideException)e;
else
throw (RuntimeException)e;
}
return c;
}
|
c57a12e7-ffd1-462c-9919-94d7cb662835
| 5
|
public static void main(String args[])
{
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable e)
{
Log.crash(e, "AMIDST has encounted an uncaught exception on thread: " + thread);
}
});
CmdLineParser parser = new CmdLineParser(Options.instance);
Util.setMinecraftDirectory();
try
{
parser.parseArgument(args);
}
catch (CmdLineException e)
{
Log.w("There was an issue parsing command line options.");
e.printStackTrace();
}
if (Options.instance.logPath != null)
{
Log.addListener("file", new FileLogger(new File(Options.instance.logPath)));
}
if (!isOSX())
{
Util.setLookAndFeel();
}
System.setProperty("sun.java2d.opengl", "True");
System.setProperty("sun.java2d.accthreshold", "0");
BiomeColorProfile.scan();
if (Options.instance.minecraftJar != null)
{
try
{
Util.setProfileDirectory(Options.instance.minecraftPath);
MinecraftUtil.setBiomeInterface(new Minecraft(new File(Options.instance.minecraftJar)).createInterface());
new FinderWindow();
}
catch (MalformedURLException e)
{
Log.crash(e, "MalformedURLException on Minecraft load.");
}
}
else
{
new VersionSelectWindow();
}
}
|
d4c887d8-e87a-4a11-994a-f478e258e91e
| 2
|
MediaElement[] getSelected(JTable table)
{
if (table == null)
table = parentTable;
MediaElement[] res = new MediaElement[table.getSelectedRowCount()];
for (int i = 0; i < table.getSelectedRowCount(); i++)
res[i] = (MediaElement) table.getModel()
.getValueAt(table.convertRowIndexToModel(table.getSelectedRows()[i]), 0);
return res;
}
|
5953144a-53e7-4564-9c25-3faf54ff9b88
| 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(chatroomGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(chatroomGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(chatroomGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(chatroomGUI.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 chatroomGUI().setVisible(true);
}
});
}
|
62ddf177-1842-4ab3-8dbb-2c037f6eb26d
| 7
|
@Override
public void doEdgeDetection() {
if (imageManager.getBufferedImage() == null) return;
WritableRaster raster = imageManager.getBufferedImage().getRaster();
double[][] dx = new double[][] {{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}};
double[][] dy = new double[][] {{-1, -2, -1},
{ 0, 0, 0},
{ 1, 2, 1}};
double[][] newPixels = new double[raster.getWidth()][raster.getHeight()];
for (int x = 1; x < raster.getWidth() - 1; x++) {
for (int y = 1; y < raster.getHeight() - 1; y++) {
double[][] N = new double[3][3];
N[2][2] = raster.getPixel(x+1, y+1, new double[3])[0];
N[0][2] = raster.getPixel(x+1, y-1, new double[3])[0];
N[2][1] = raster.getPixel(x, y+1, new double[3])[0];
N[0][1] = raster.getPixel(x, y-1, new double[3])[0];
N[2][0] = raster.getPixel(x-1, y+1, new double[3])[0];
N[0][0] = raster.getPixel(x-1, y-1, new double[3])[0];
N[1][1] = raster.getPixel(x, y, new double[3])[0];
N[1][2] = raster.getPixel(x+1, y, new double[3])[0];
N[1][0] = raster.getPixel(x-1, y, new double[3])[0];
double xGradient = multipleAndSumXderivativeKernel(dx, N)/8;
double yGradient = multipleAndSumXderivativeKernel(dy, N)/8;
double magnitude = Math.sqrt(xGradient*xGradient + yGradient*yGradient);
double[] pixel = new double[3];
// magnitude += 128;
pixel[0] = magnitude;
if (pixel[0] > 255)
pixel[0] = 255;
else if (pixel[0] < 0)
pixel[0] = 0;
pixel[1] = pixel[2] = pixel[0];
newPixels[x][y] = pixel[0];
}
}
for (int x = 1; x < raster.getWidth() - 1; x++) {
for (int y = 1; y < raster.getHeight() - 1; y++) {
double[] pixel = new double[3];
pixel[0] = pixel[1] = pixel[2] = newPixels[x][y];
raster.setPixel(x, y, pixel);
}
}
GUIFunctions.refresh();
}
|
3277a405-3db5-44f3-8110-c17f97036d93
| 0
|
public startScreen() {
Position position = new Position();
setLayout(new GridLayout(0, 1, 0, 0));
JButton btnCurrentDate = new JButton("current date");
btnCurrentDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "BinaryDate");
}
});
JButton btnAllDetailedClock = new JButton("all detailed clock");
btnAllDetailedClock.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "NotYet");
}
});
add(btnAllDetailedClock);
add(btnCurrentDate);
JButton btnCurrentTime = new JButton("current time");
btnCurrentTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "BinaryTime");
}
});
add(btnCurrentTime);
JButton btnCurrentDate_1 = new JButton("BinaryDateTime");
btnCurrentDate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "NotYet");
}
});
add(btnCurrentDate_1);
JButton btnTimer = new JButton("timer");
btnTimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "MyTimer");
}
});
add(btnTimer);
JButton btnWTC = new JButton("world time converter");
btnWTC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "WorldTimeConverter");
}
});
add(btnWTC);
}
|
a7f6afca-d0cb-4105-9e2d-5e6ed126d078
| 9
|
@Override
public PilotAction findNextAction(double s_elapsed) {
MoveDirection move = MoveDirection.NONE;
if (is_moving_forward) {
if (!is_moving_backward) {
move = MoveDirection.FORWARD;
}
}
else if (is_moving_backward) {
move = MoveDirection.BACKWARD;
}
StrafeDirection strafe = StrafeDirection.NONE;
if (is_strafing_left) {
if (!is_strafing_right) {
strafe = StrafeDirection.LEFT;
}
}
else if (is_strafing_right) {
strafe = StrafeDirection.RIGHT;
}
TurnDirection turn = TurnDirection.NONE;
if (is_turning_counter_clockwise) {
if (!is_turning_clockwise) {
turn = TurnDirection.COUNTER_CLOCKWISE;
}
}
else if (is_turning_clockwise) {
turn = TurnDirection.CLOCKWISE;
}
PilotAction action =
new PilotAction(move, strafe, turn, is_firing_cannon, is_firing_secondary, is_dropping_bomb);
is_dropping_bomb = false;
return action;
}
|
293786d7-4c66-4fcc-becb-e33295b3c7b7
| 7
|
public int paintNode(Graphics g, Node node, double timeBegin, int nLeaveAbove) {
int y=0;
if(node.isLeaf()) {
y = (int) ((height-2*yTopBranch)*((double)(nLeaveAbove))/nLeaves)+yTopBranch;
if(node.getTime()==0) {
g.fillRect(getX(node.getTime()), y-heightBranch/2, widthGeneLabels, heightBranch); //The branch
if(showTaxonNames) {
g.drawString(node.getName(), getX(node.getTime())+widthGeneLabels+5, y+5); //The name
}
}
else {
if(showTaxonNames) {
g.drawString(node.getName(), getX(node.getTime())+20, y+5); //The name
}
}
}
else {
int y1 = paintNode(g, node.getLeft(), node.getTime(), nLeaveAbove);
int y2 = paintNode(g, node.getRight(), node.getTime(), nLeaveAbove+node.getLeft().getNLeaves());
y = (y1+y2)/2;
g.fillRect(getX(node.getTime())-widthBranch/2, y1-heightBranch/2, widthBranch, (y2-y1)+heightBranch);
}
g.fillRect(getX(timeBegin), y-heightBranch/2, getX(node.getTime())-getX(timeBegin), heightBranch);
if(showBranchLengths && node != reader.getOut()) {
int n;
if(node == reader.getRoot()) {
n = (int) (100*(reader.getScale() - node.getTime()));
}
else {
n = (int) (100*(node.getFather().getTime() - node.getTime()));
}
g.drawString(""+n, (getX(timeBegin)+getX(node.getTime()))/2, y-heightBranch/2-5);
}
node.setY(y);
return y;
}
|
977f6a45-28f2-4b98-a37f-85719e5cbcf2
| 1
|
public void buildShowWords() {
showFrame = new JFrame("All words");
JPanel mainPanel = new JPanel();
allPhrases = new JTextArea(GuiBuilder.numberOfLinesInFile +2, 25);
allPhrases.setEditable(false);
JScrollPane qScroller = new JScrollPane(allPhrases);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
mainPanel.add(allPhrases);
showFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);
showFrame.setSize(420, 250);
showFrame.setVisible(true);
wordListAll = GuiBuilder.wordListAll;
allPhrases.setText("Words" + "\t" + "Translation" + "\t" + "Stats" + "\t" + "Date of addition" + "\n" );
for(int i = 0; i < GuiBuilder.wordListAll.size(); i++){
currentWord = GuiBuilder.wordListAll.get(i);
allPhrases.append(currentWord.getWord() + "\t" +
currentWord.getTranslation() + "\t" +
currentWord.getNumberOfAttempts()+ "/" +
currentWord.getNumberOfCorrect() + "/" +
currentWord.getPercentOfLearning() + "\t" +
currentWord.getSimpleDateOfAddition() + "\n");
}
}
|
1e3b581a-0421-4dac-a6b9-85cc1e78ee3c
| 7
|
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException
{
String text;
Path pt = new Path("spamlist/spamlist.txt"); //List of known spammers
FileSystem fs = FileSystem.get(new Configuration());
BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(pt)));
//Check if domain is in spam list
while (in.ready()) {
text = in.readLine();
String[] parts = (key.toString()).split("@");
String address = parts[1];
address = address.substring(0,(address.length()-1));
if (text.equals(address)){
context.write(key, new Text(" is considered a spammer because of their domain."));
return;
}
}
in.close();
//Check if subjects are similar
//Puts all subjects into a hashmap that counts the number of times the same subject appears
Map<Text, Integer> count = new HashMap<Text,Integer>();
int numEmails = 0;
for (Text value : values){
Integer i = count.get(value);
if (i == null)
i = 0;
count.put(value, i + 1);
numEmails++;
}
//Percentage of a set of similar emails out of all emails
float percentage = 0;
Iterator iter = count.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
percentage = ((float) Integer.parseInt(mEntry.getValue().toString())/numEmails) *100;
if (percentage > 60 && numEmails > 5){
context.write(key, new Text(" is considered a spammer because " + percentage + "% of their emails had the same subject."));
return;
}
}
}
|
b56d3f55-cd22-4a40-9975-b45526d1f18a
| 1
|
public ScoreList(User[] user){
scores = new Score[user.length];
for (int i = 0; i < user.length; i++) {
scores[i] = new Score(user[i]);
}
}
|
02f43e13-9154-4aab-8de4-4d034e039902
| 8
|
@EventHandler(priority = EventPriority.LOWEST)
public void vehiclePlace(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Material clickedMaterial = event.getClickedBlock().getType();
Player player = event.getPlayer();
Material materialInHand = player.getItemInHand().getType();
if (clickedMaterial == Material.RAILS
|| clickedMaterial == Material.POWERED_RAIL
|| clickedMaterial == Material.DETECTOR_RAIL) {
if (materialInHand == Material.MINECART
|| materialInHand == Material.POWERED_MINECART
|| materialInHand == Material.STORAGE_MINECART) {
prevent(event, player, "vehicle.place");
}
} else if (materialInHand == Material.BOAT) {
prevent(event, player, "vehicle.place");
}
}
}
|
4717fc51-111a-446a-b8d7-d7d94c6976a4
| 9
|
public void piirraRuutu(int x, int y, RuutuTyyli tyyli, Graphics graph){
switch(tyyli){
case Hedelma:
tyyli.drawImage(graph, x, y);
break;
case IsoHedelma:
tyyli.drawImage(graph, x, y);
break;
case LyhentavaHedelma:
tyyli.drawImage(graph, x, y);
break;
case MatoBody:
graph.setColor(Color.GREEN);
graph.fillRect(x, y, RUUDUN_KOKO, RUUDUN_KOKO);
break;
case MatoHead:
graph.setColor(Color.GREEN);
graph.fillRect(x, y, RUUDUN_KOKO, RUUDUN_KOKO);
graph.setColor(Color.BLACK);
switch(peli.getSuunta()){
case North:{
int apuY = y + SILMAT_YLHAALTA;
graph.drawLine(x + SILMAT_SIVUSTA, apuY, x + SILMAT_SIVUSTA, apuY + SILMAN_KOKO);
graph.drawLine(x + RUUDUN_KOKO - SILMAT_SIVUSTA, apuY, x + RUUDUN_KOKO - SILMAT_SIVUSTA,
apuY + SILMAN_KOKO);
break;
}
case South:{
int apuY = y + RUUDUN_KOKO - SILMAT_YLHAALTA;
graph.drawLine(x + SILMAT_SIVUSTA, apuY, x + SILMAT_SIVUSTA, apuY - SILMAN_KOKO);
graph.drawLine(x + RUUDUN_KOKO - SILMAT_SIVUSTA, apuY, x + RUUDUN_KOKO - SILMAT_SIVUSTA,
apuY - SILMAN_KOKO);
break;
}
case East:{
int apuX = x + RUUDUN_KOKO -SILMAT_YLHAALTA;
graph.drawLine(apuX, y + SILMAT_SIVUSTA, apuX - SILMAN_KOKO, y + SILMAT_SIVUSTA);
graph.drawLine(apuX, y + RUUDUN_KOKO - SILMAT_SIVUSTA, apuX - SILMAN_KOKO,
y + RUUDUN_KOKO - SILMAT_SIVUSTA);
break;
}
case West:{
int apuX = x + SILMAT_YLHAALTA;
graph.drawLine(apuX, y + SILMAT_SIVUSTA, apuX + SILMAN_KOKO, y + SILMAT_SIVUSTA);
graph.drawLine(apuX, y + RUUDUN_KOKO - SILMAT_SIVUSTA, apuX + SILMAN_KOKO,
y + RUUDUN_KOKO - SILMAT_SIVUSTA);
}
}
}
}
|
8c38687e-7feb-4d26-b19b-de38a4790fa1
| 8
|
public synchronized static void buildCategories(){
List<Fingerprint> dataset = HomeFactory.getFingerprintHome().getAll();
for (Fingerprint f : dataset) {
if (f == null || f.getLocation() == null || f.getMeasurement() == null) continue;
Integer id = ((Location)f.getLocation()).getId();
if (id == null) continue;
String locationTag = id.toString();
LocationCategorizer().AddCategory(locationTag);
Measurement m = (Measurement)f.getMeasurement();
for (WiFiReading r : m.getWiFiReadings()) {
if (r != null && r.getBssid() != null) {
BSSIDCategorizer().AddCategory(r.getBssid());
}
}
}
}
|
3b51500e-f6d7-45b3-873c-b36169c7d0ed
| 2
|
public static Choice getChoice(boolean check, boolean download) {
for (Choice c : Choice.values()) {
if (c.equals(check, download)) {
return c;
}
}
return null;
}
|
57999ba7-5368-440e-8467-ca46180f5f9c
| 7
|
private void addConditional(Vector addTo, Location loc, int x, int y) {
int newX = loc.x + x, newY = loc.y + y;
if (newX < 0 || newX >= grid.length) {
return;
}
if (newY < 0 || newY >= grid[0].length) {
return;
}
if (grid[newX][newY] == Constants.FULL_NON_PASSABLE) {
return;
}
if (isDiagonal(newX, newY)) {
if (grid[newX][newY] == Constants.DIAGONAL_NON_PASSABLE) {
return;
}
}
Node newNode = new Node();
newNode.location = new Location(newX, newY);
addTo.addElement(newNode);
}
|
ca7159ac-03c3-4570-9933-f566d776e4e2
| 7
|
static byte[] scanForOffsets(int firstAtomIndex,
int[] specialAtomIndexes,
byte[] interestingAtomIDs) {
/*
* from validateAndAllocate in AminoMonomer or NucleicMonomer extensions
*
* sets offsets for the FIRST conformation ONLY
* (provided that the conformation is listed first in each atom case)
*
* specialAtomIndexes[] corrolates with JmolConstants.specialAtomNames[]
* and is set up back in the calling frame.distinguishAndPropagateGroups
*/
int interestingCount = interestingAtomIDs.length;
byte[] offsets = new byte[interestingCount];
for (int i = interestingCount; --i >= 0; ) {
int atomIndex;
int atomID = interestingAtomIDs[i];
// mth 2004 06 09
// use ~ instead of - as the optional indicator
// because I got hosed by a missing comma
// in an interestingAtomIDs table
if (atomID < 0) {
atomIndex = specialAtomIndexes[~atomID]; // optional
} else {
atomIndex = specialAtomIndexes[atomID]; // required
if (atomIndex < 0)
return null;
}
int offset;
if (atomIndex < 0)
offset = 255;
else {
offset = atomIndex - firstAtomIndex;
if (offset < 0 || offset > 254) {
Logger.warn("Monomer.scanForOffsets i="+i+" atomID="+atomID+" atomIndex:"+atomIndex+" firstAtomIndex:"+firstAtomIndex+" offset out of 0-254 range. Groups aren't organized correctly. Is this really a protein?: "+offset);
if (atomID < 0) {
offset = 255; //it was optional anyway RMH
} else {
//throw new NullPointerException();
}
}
}
offsets[i] = (byte)offset;
}
return offsets;
}
|
ba056c12-9858-4554-b744-8c5b0216586d
| 3
|
public DoorBlock(int x, int y, int type, int direction, int roomPointer) {
super(x, y, type);
if (direction == 1) {
doorBounds = new Rectangle(getBoundsDoor().x, getBoundsDoor().y, getBoundsDoor().width, getBoundsDoor().height);
}
if (direction == 2) {
doorBounds = new Rectangle(getBoundsDoor().x, getBoundsDoor().y, getBoundsDoor().width - 20, getBoundsDoor().height);
}
if (direction == 3) {
doorBounds = new Rectangle(getBoundsDoor().x, getBoundsDoor().y, getBoundsDoor().width, getBoundsDoor().height - 20);
}
this.direction = direction;
toggleDoor(true);
setRoomPointer(roomPointer);
}
|
357de9e0-f7b5-49e1-8e30-e85537388830
| 0
|
public void setProffession(Proffession proffession) {this.proffession = proffession;}
|
77e410b0-4652-495a-802c-9dc1ceaa63bf
| 2
|
public void reply()
{
try
{
ServerSocket server = new ServerSocket(SPORT);
Socket client = server.accept();
ObjectInputStream is =
new ObjectInputStream(client.getInputStream());
Object o = is.readObject();
if (o instanceof Message)
{
Message m = (Message) o;
System.out.println(
"Server received: " + m.geContent() + " from " + m.geName());
}
ObjectOutputStream os =
new ObjectOutputStream(client.getOutputStream());
os.writeObject(new Message(this, "Server", "hello"));
os.flush();
client.close();
server.close();
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
|
0809ef0d-3d34-4cad-bdf2-b728b17f99b1
| 5
|
private int[][] subMatrix(final int[][] X, final int[][] Y) {
try {
int[][] subtraction = new int[X.length][X[0].length];
if (X.length == Y.length) {
for (int i = 0; i < X.length; ++i) {
if (X[i].length == Y[i].length) {
for (int j = 0; j < X[i].length; ++j) {
subtraction[i][j] = X[i][j] - Y[i][j];
}
} else {
System.out.println("Input matrix must have equal length of column");
return null;
}
}
return subtraction;
} else {
System.out.println("Input matrix must have equal length of row");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
|
c1d86c9e-697f-468e-9abe-582fcdd0cfd8
| 6
|
public boolean hitFoldingIcon(Object cell, int x, int y)
{
if (cell != null)
{
mxIGraphModel model = graph.getModel();
// Draws the collapse/expand icons
boolean isEdge = model.isEdge(cell);
if (foldingEnabled && (model.isVertex(cell) || isEdge))
{
mxCellState state = graph.getView().getState(cell);
if (state != null)
{
ImageIcon icon = getFoldingIcon(state);
if (icon != null)
{
return getFoldingIconBounds(state, icon).contains(x, y);
}
}
}
}
return false;
}
|
1e4af485-3201-49cf-9826-10b491e59a9f
| 8
|
public double evaluate(){ //returns distance to closest pit to the right if facing right and sim. left
if(player.getFalling())
return 0;
ArrayList<Block> blocklist = level.getBlocksOnScreen();
double width = 1;
double mariobot = player.getYpos()+player.getHeight()/2;
int direction = 0;
double xoffset = 0;
outer: for( ; ; xoffset += width*Math.pow(-1,direction)){
for(Block b: blocklist){
if(b.getCYpos()<mariobot+16 && b.getCYpos()>mariobot){
if(b.getXpos() - player.getXpos() <= xoffset && b.getXpos() - player.getXpos() + (double)b.getWidth() >= xoffset)
continue outer;
}
}
if(xoffset == 0)
return 0;
return 1/xoffset + getBias();
}
}
|
10a81fc3-eae3-4e67-82d8-2f8203164699
| 8
|
@Override
protected int findPrototypeId(String s)
{
int id;
// #generated# Last update: 2007-05-09 08:15:31 EDT
L0: { id = 0; String X = null; int c;
int s_length = s.length();
if (s_length==7) { X="valueOf";id=Id_valueOf; }
else if (s_length==8) {
c=s.charAt(3);
if (c=='o') { X="toSource";id=Id_toSource; }
else if (c=='t') { X="toString";id=Id_toString; }
}
else if (s_length==11) { X="constructor";id=Id_constructor; }
if (X!=null && X!=s && !X.equals(s)) id = 0;
break L0;
}
// #/generated#
return id;
}
|
10c18ac8-e8fd-4c3a-b3c8-ee9849c2b82c
| 4
|
* The width to be translated to a character index.
* @return Returns the given width, translated to a character index.
*/
public int line_offset_from(int line, int wid) {
int ret;
String l = code.getsb(line).toString();
int w = 0, lw = 0;
for (ret = 0; ret < l.length() && w < wid; ret++) {
lw = w;
if (l.charAt(ret) == '\t') {
final int wf = monoAdvance * Settings.indentSizeInSpaces;
w = ((w + wf) / wf) * wf;
} else {
w += monoAdvance;
}
}
if (Math.abs(lw - wid) < Math.abs(w - wid)) {
return Math.min(l.length(), ret - 1);
}
return Math.min(l.length(), ret);
}
|
744f8227-c2f6-484e-adb4-4b05f031fba8
| 0
|
@Test
public void EnsurePathMatchesAllWildCardPattern() {
Path path = new Path("alan/likes/warbyparker");
Pattern pattern = new Pattern("*,*,*");
assertTrue(path.match(pattern));
}
|
7bd8f791-7fa5-45d7-af6f-e316f971a9fc
| 9
|
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // RTT/corba/CSendHandle/collect
{
RTT.corba.CAnyArgumentsHolder args = new RTT.corba.CAnyArgumentsHolder ();
RTT.corba.CSendStatus $result = null;
$result = this.collect (args);
out = $rh.createReply();
RTT.corba.CSendStatusHelper.write (out, $result);
RTT.corba.CAnyArgumentsHelper.write (out, args.value);
break;
}
case 1: // RTT/corba/CSendHandle/collectIfDone
{
RTT.corba.CAnyArgumentsHolder args = new RTT.corba.CAnyArgumentsHolder ();
RTT.corba.CSendStatus $result = null;
$result = this.collectIfDone (args);
out = $rh.createReply();
RTT.corba.CSendStatusHelper.write (out, $result);
RTT.corba.CAnyArgumentsHelper.write (out, args.value);
break;
}
/**
* Just checks what the status is.
*/
case 2: // RTT/corba/CSendHandle/checkStatus
{
RTT.corba.CSendStatus $result = null;
$result = this.checkStatus ();
out = $rh.createReply();
RTT.corba.CSendStatusHelper.write (out, $result);
break;
}
/**
* Returns only the return value, when checkStatus() returns CSendSuccess.
* Convenient if the sent method only returns a value.
*/
case 3: // RTT/corba/CSendHandle/ret
{
org.omg.CORBA.Any $result = null;
$result = this.ret ();
out = $rh.createReply();
out.write_any ($result);
break;
}
/**
* Checks if this handle returns these arguments in collect() and collectIfDone().
* You can use this to check if collect() or collectIfDone() return what you expect.
* If no exception is thrown, the arguments are of the correct number
* and type. The values in \a args are ignored and not stored, only the types of the anys are checked.
* One could obtain the same information by using COperationInterface::getCollectType()
* for 1..COperationInterface::getCollectArity().
*/
case 4: // RTT/corba/CSendHandle/checkArguments
{
try {
org.omg.CORBA.Any args[] = RTT.corba.CAnyArgumentsHelper.read (in);
this.checkArguments (args);
out = $rh.createReply();
} catch (RTT.corba.CWrongNumbArgException $ex) {
out = $rh.createExceptionReply ();
RTT.corba.CWrongNumbArgExceptionHelper.write (out, $ex);
} catch (RTT.corba.CWrongTypeArgException $ex) {
out = $rh.createExceptionReply ();
RTT.corba.CWrongTypeArgExceptionHelper.write (out, $ex);
}
break;
}
/**
* Clients need to call this after they have finished using this
* CSendHandle object. After dispose(), this object may no longer
* be used.
*/
case 5: // RTT/corba/CSendHandle/dispose
{
this.dispose ();
out = $rh.createReply();
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
|
d1f90ab1-dce9-4fa3-83f5-4cc8a772f4fb
| 7
|
public static boolean[] shortToBoolean(short[] octets) throws SubneterException
{
if (octets.length != 4)
{
throw new SubneterException("Invalid IP adress too many or to less octets");
}
for (int i = 0; i < 4; i++)
{
if (octets[i] < 0 || octets[i] > 255)
{
throw new SubneterException("Invalid IP adress " + (i + 1) + ". octed is " + octets[i]);
}
}
boolean[] bits = new boolean[32];
for (int i = 0; i < 4; i++)
{
for (int ii = 0; ii < 8; ii++)
{
if (octets[i] >= Math.pow(2, 7 - ii))
{
bits[i * 8 + ii] = true;
octets[i] -= Math.pow(2, 7 - ii);
}
else
{
bits[i * 8 + ii] = false;
}
}
}
return bits;
}
|
22011b96-48c7-4e90-b55d-aaf8640cee8b
| 3
|
private void rotateRight(Entry<K,V> p) {
Entry<K,V> l = p.left;
p.left = l.right;
if (l.right != null) l.right.parent = p;
l.parent = p.parent;
if (p.parent == null)
root = l;
else if (p.parent.right == p)
p.parent.right = l;
else p.parent.left = l;
l.right = p;
p.parent = l;
}
|
9565423e-aac3-4f34-9de4-bc025a33c2c4
| 9
|
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {
if (lab_modo.getText().equals("Alta")){
if (camposCompletos()){
if (validarFechas()){
ocultar_Msj();
insertar();
combo_tipo.setEnabled(true);
field_desdee.setEnabled(true);
field_hasta.setEnabled(true);
menuDisponible(true);
modoConsulta();
updateTabla();
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Baja")){
if (!field_tasa.getText().equals("")){
if(!existe(Integer.parseInt(lab_ID.getText()))){
mostrar_Msj_Error("Ingrese una cuenta que se encuentre registrada en el sistema");
field_tasa.requestFocus();
}
else{
ocultar_Msj();
eliminar();
menuDisponible(true);
modoConsulta();
vaciarCampos();
updateTabla();
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Modificación")){
if (!field_tasa.getText().equals("")){
if (camposCompletos()){
ocultar_Msj();
modificar();
menuDisponible(true);
modoConsulta();
updateTabla();
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
}
}
}
|
12238f9f-19b5-426b-9839-8347e95e45c1
| 4
|
public int GetNPCID(int coordX, int coordY) {
for (int i = 0; i < server.npcHandler.maxNPCs; i++) {
if (server.npcHandler.npcs[i] != null) {
if (server.npcHandler.npcs[i].absX == coordX && server.npcHandler.npcs[i].absY == coordY) {
return server.npcHandler.npcs[i].npcType;
}
}
}
return 1;
}
|
caf79136-b96c-4cd7-9ca8-675db0694a24
| 0
|
@Override
public int getNextRound() {
return nextScheduledRound;
}
|
44b30700-72b1-42f5-9681-07b256846b0e
| 9
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(!(target instanceof Wand))
{
mob.tell(L("You can't recharge that."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> incant(s) at <T-NAMESELF> as sweat beads form on <S-HIS-HER> forehead.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if((((Wand)target).usesRemaining()+5) >= ((Wand)target).maxUses())
{
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> glow(s) brightly then disintigrates!"));
target.destroy();
}
else
{
boolean willBreak = false;
if((((Wand)target).usesRemaining()+10) >= ((Wand)target).maxUses())
willBreak = true;
((Wand)target).setUsesRemaining(((Wand)target).usesRemaining()+5);
if(!(willBreak))
{
mob.location().show(mob, target, CMMsg.MSG_OK_VISUAL, L("<T-NAME> glow(s) brightly!"));
}
else
{
mob.location().show(mob, target, CMMsg.MSG_OK_VISUAL, L("<T-NAME> glow(s) brightly and begins to hum. It clearly cannot hold more magic."));
}
}
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> incant(s) at <T-NAMESELF>, looking more frustrated every minute."));
// return whether it worked
return success;
}
|
7653a9c9-55ae-4960-8f3f-d08d02ec5c96
| 4
|
private Vector getInitVector() {
int random = (int)(Math.random() * 8);
switch (random) {
case 1: return Vector.UP;
case 2: return Vector.DOWN;
case 3: return Vector.RIGHT;
case 4: return Vector.LEFT;
}
return Vector.UP;
}
|
e1b83953-8936-412e-9a6c-44484fe094aa
| 0
|
public int hashCode() {
return super.hashCode();
}
|
5106a4f3-0bc8-4eb2-96ae-75f8c6461e8b
| 3
|
@Override
public void handleEvent(Event event) {
if (event.getType() == EventType.END_ACTION)
endActionUpdate();
else if (event.getType() == EventType.END_EFFECT)
if (isValidEndEffectEvent(event))
removeEffect();
}
|
9897110d-9ecf-4ebf-820f-c4ab77dc0bdd
| 3
|
public static int[] sort(int array[]){
for(int i = 1;i < array.length;i++){
int key = array[i];
int j = i-1;
while( j>=0 && key < array[j]){
array[j+1] = array[j];
j--;
}
array[j+1] = key;
}
return array;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.