method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
28914580-d917-436c-b4dc-4361a7d6db39 | 3 | public void loadDictionary(File dictionary) throws Exception {
try {
BufferedReader is = null;
try {
is = new BufferedReader (new FileReader(dictionary));
String line = null;
while ((line = is.readLine()) != null) {
this.attach(line);
}
} finally {
is.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
} |
023f292a-76e0-4f90-a681-e97c9cee669a | 5 | @Override
public int compare(Set lhs, Set rhs) {
Iterator<State> li = lhs.iterator();
Iterator<State> ri = rhs.iterator();
while (li.hasNext() && ri.hasNext()) {
int res = li.next().compareTo(ri.next());
if (res != 0)
return res;
}
if (li.hasNext())
return 1;
if (ri.hasNext())
return -1;
return 0;
} |
9992f18d-07d3-4285-ac13-30fff62fbce5 | 7 | public void update(int dt) {
double[] jerk = getRandUnitVector();
ax = jerk[0]*force;
ay = jerk[1]*force;
ArrayList<int[]> gs = ScreenSaver.getCentersOfGravity();
double grav = ScreenSaver.getGravity();
for(int[] g : gs)
if(g[0] >= 0) {
double[] r = new double[]{g[0]-centerx, g[1]-centery};
double rmag = Math.sqrt(r[0]*r[0] + r[1]*r[1]);
double[] rhat = new double[]{r[0]/rmag, r[1]/rmag};
if(rmag != 0) {
ax += grav*rhat[0]*.0001;
ay += grav*rhat[1]*.0001;
}
}
else
ay -= g[2]*.001;
vx += ax*dt;
vy += ay*dt;
double dx = vx*dt;
double dy = vy*dt;
int xLimit = ScreenSaver.getSpaceWidth()-(int)getWidth();
int yLimit = ScreenSaver.getHeight()-(int)getHeight();
if( rx + dx < 0 || rx + dx > xLimit ) {
dx = 0;
vx = -vx;
}
if( ry + dy < 0 || ry + dy > yLimit) {
dy = 0;
vy = -vy;
}
rx += dx;
ry += dy;
centerx = rx+length/2;
centery = ry+length/2;
x = (int)rx;
y = (int)ry;
pastLocs.add( new int[]{x+length/2,y+length/2} );
} |
8afd676a-8e49-47c6-a98c-b159e99192cf | 8 | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
/*Informs the SMS API that the request has been received*/
resp.setStatus(HttpServletResponse.SC_OK);
String number=req.getParameter("msisdn").toString();
try{
String request=req.getParameter("text").toString();
request=URLDecoder.decode(request, "UTF-8");
if(!request.equals(null))
{
String[] smsmsg=splitMsg(request, number);
if(smsmsg[0].length()!=0)
{
if(smsmsg.length==1)
{
SendSMS(number, smsmsg[0]);
if(smsmsg[0].equals("No vaccine found at the moment."))
{
storeSMS(req);
}
}
else
{
String txt="";
String txt2="";
for(int x=0;x<smsmsg.length;x++)
{
txt+=smsmsg[x];
}
//take sms length into consideration
int count=txt.length()/140;
int count2=0;
for(int x=0;x<txt.length();x+=140)
{
if(count2<count){
txt2=txt.substring(x, x+140);
SendSMS(number,txt2 );
}
else{
txt2=txt.substring(x);
SendSMS(number,txt2 );
}
count2++;
}
}
}
}
}catch (Exception e){
SendSMS(number, "There was a problem fulfilling your request, please try again later.");
}
} |
9b07c5fa-fa81-4c3b-901a-f227dbfdcf51 | 5 | public final void method44(int i, AbstractToolkit var_ha) {
anInt10092++;
Object object = null;
r var_r;
if (aR10094 == null && aBoolean10064) {
Class2 class2 = method2481(true, 262144, -4, var_ha);
var_r = class2 == null ? null : ((Class2) class2).aR118;
} else {
var_r = aR10094;
aR10094 = null;
}
if (var_r != null)
Class130.method1130(var_r, ((Class318_Sub1) this).mapHeightLevel,
((Class318_Sub1) this).xHash,
((Class318_Sub1) this).anInt6388, null);
if (i != 836)
aR10094 = null;
} |
83d48323-5238-4754-b43f-69874f2103fc | 2 | public void exec(){
try {
ArrayList<String> erg = util.networkCommand("free");
MemTotal = Double.parseDouble(erg.get(1).split("\\s+ ")[1]) / 1024;
MemUsed = Double.parseDouble(erg.get(1).split("\\s+ ")[2]) / 1024;
SwapTotal = Double.parseDouble(erg.get(3).split("\\s+ ")[1]) / 1024;
SwapUsed = Double.parseDouble(erg.get(3).split("\\s+ ")[2]);
if(SwapUsed != 0)
SwapUsed /= 1024;
System.out.println(MemTotal + " " + MemUsed);
System.out.println(SwapTotal + " " + SwapUsed);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} |
dd8dccdb-3119-426b-a2cb-87c93402a3b5 | 6 | protected void func_48458_a(int par1, int par2, Chunk par3Chunk)
{
Profiler.endStartSection("tickChunk");
par3Chunk.updateSkylight();
Profiler.endStartSection("moodSound");
if (this.ambientTickCountdown == 0)
{
this.updateLCG = this.updateLCG * 3 + 1013904223;
int var4 = this.updateLCG >> 2;
int var5 = var4 & 15;
int var6 = var4 >> 8 & 15;
int var7 = var4 >> 16 & 127;
int var8 = par3Chunk.getBlockID(var5, var7, var6);
var5 += par1;
var6 += par2;
if (var8 == 0 && this.getFullBlockLightValue(var5, var7, var6) <= this.rand.nextInt(8) && this.getSavedLightValue(EnumSkyBlock.Sky, var5, var7, var6) <= 0)
{
EntityPlayer var9 = this.getClosestPlayer((double)var5 + 0.5D, (double)var7 + 0.5D, (double)var6 + 0.5D, 8.0D);
if (var9 != null && var9.getDistanceSq((double)var5 + 0.5D, (double)var7 + 0.5D, (double)var6 + 0.5D) > 4.0D)
{
this.playSoundEffect((double)var5 + 0.5D, (double)var7 + 0.5D, (double)var6 + 0.5D, "ambient.cave.cave", 0.7F, 0.8F + this.rand.nextFloat() * 0.2F);
this.ambientTickCountdown = this.rand.nextInt(12000) + 6000;
}
}
}
Profiler.endStartSection("checkLight");
par3Chunk.enqueueRelightChecks();
} |
62d0c63d-d2fe-440e-83fa-ff9b31b3a2ed | 5 | public Object getObjectInstance( Object object, Name name, Context context,
Hashtable< ?, ? > enviroment )
throws Exception
{
if ( object instanceof Reference )
{
Reference reference = ( Reference ) object;
if ( reference.getClass( ).equals( WarehouseConfig.class ) )
{
RefAddr maxItemAmountRef = reference.get( WarehouseConfig.MAX_ITEM_AMOUNT );
RefAddr maxOneTypeItemAmountRef = reference.get( WarehouseConfig.MAX_ONE_TYPE_ITEM_AMOUNT );
RefAddr nomenclatureUpdateFrequencyRef = reference.get( WarehouseConfig.NOMENCLATURE_UPDATE_FREQUENCY );
RefAddr nameRef = reference.get( WarehouseConfig.NAME );
if ( GeneralUtil.areNotNull( maxItemAmountRef, maxOneTypeItemAmountRef, nomenclatureUpdateFrequencyRef, name ) )
{
return new WarehouseConfig(
getIntegerContent( maxItemAmountRef ),
getIntegerContent( maxOneTypeItemAmountRef ),
getIntegerContent( nomenclatureUpdateFrequencyRef ),
getContent( nameRef ) );
}
}
}
return null;
} |
be5d8d6e-fcef-4883-9233-d691cab665b6 | 8 | public int[] predict(MaltFeatureNode[] x) {
final double[] dec_values = new double[nr_class];
final int[] predictionList = Util.copyOf(labels, nr_class);
final int n = (bias >= 0)?nr_feature + 1:nr_feature;
// final int nr_w = (nr_class == 2 && solverType != SolverType.MCSVM_CS)?1:nr_class;
final int xlen = x.length;
// int i;
// for (i = 0; i < nr_w; i++) {
// dec_values[i] = 0;
// }
for (int i=0; i < xlen; i++) {
if (x[i].index <= n) {
final int t = (x[i].index - 1);
if (w[t] != null) {
for (int j = 0; j < w[t].length; j++) {
dec_values[j] += w[t][j] * x[i].value;
}
}
}
}
double tmpDec;
int tmpObj;
int lagest;
final int nc = nr_class-1;
for (int i=0; i < nc; i++) {
lagest = i;
for (int j=i; j < nr_class; j++) {
if (dec_values[j] > dec_values[lagest]) {
lagest = j;
}
}
tmpDec = dec_values[lagest];
dec_values[lagest] = dec_values[i];
dec_values[i] = tmpDec;
tmpObj = predictionList[lagest];
predictionList[lagest] = predictionList[i];
predictionList[i] = tmpObj;
}
return predictionList;
} |
62e0bddd-f92a-4eed-ba71-adbda8ff75d8 | 0 | @Before
public void Init() {
board = new Board(numberOfPawns, xSize, ySize, xBonusSquare, yBonusSquare);
} |
7e2d86a7-26bd-485e-b50c-2b071e27e762 | 2 | public LocalInfo findLocal(String name) {
for (int i = 0; i < count; i++)
if (locals[i].getName().equals(name))
return locals[i];
return null;
} |
4243ab35-53e5-405b-b6a4-b0149a205e3f | 0 | public Client getClient() {
return this.client;
} |
0b685e47-63f6-46bd-a5a2-bd0cad63564c | 1 | public void setPouvoirsDispo(List<Class<? extends Pouvoir>> pouvoirsDispo) {
this.pouvoirsDispo = pouvoirsDispo;
} |
4f8ea84b-3130-4af7-8cbe-44588214f6d8 | 8 | public static ResponseDTO execute(RequestDTO reqObj) throws BookingTicketException {
log.debug("Start: execute()");
PassengerDAO passengerDAO = new PassengerDAO(ENTITY_MANAGER_FACTORY);
StationInRouteDAO sirDAO = new StationInRouteDAO(ENTITY_MANAGER_FACTORY);
StationDAO stationDAO = new StationDAO(ENTITY_MANAGER_FACTORY);
TicketDAO ticketDAO = new TicketDAO(ENTITY_MANAGER_FACTORY);
TrainDAO trainDAO = new TrainDAO(ENTITY_MANAGER_FACTORY);
//Determines what kind of server was required.
Constants.ClientService reqService = reqObj.getService();
if (reqService == Constants.ClientService.getScheduleFromAtoB) {
log.debug("Start: getScheduleFromAtoB");
return StationInRouteService.scheduleFromAtoB(reqObj, sirDAO);
}
else if (reqService == Constants.ClientService.scheduleForStation) {
log.debug("Start: scheduleForStation");
return StationInRouteService.scheduleForStation(reqObj, sirDAO);
}
else if (reqService == Constants.ClientService.buyTicket) {
log.debug("Start: buyTicket");
return TicketService.bookTicket(reqObj, passengerDAO, ticketDAO, trainDAO, sirDAO);
}
else if (reqService == Constants.ClientService.addTrain) {
log.debug("Start: buyTicket");
return TrainService.addTrain(reqObj, trainDAO);
}
else if (reqService == Constants.ClientService.addStation) {
log.debug("Start: addStation");
return StationService.addStation(reqObj, stationDAO);
}
else if (reqService == Constants.ClientService.addRoute) {
log.debug("Start: addRoute");
return StationInRouteService.addRoute(reqObj, sirDAO);
}
else if (reqService == Constants.ClientService.viewPassangers) {
log.debug("Start: viewPassangers");
return PassengerService.showPassengers(reqObj, passengerDAO);
}
else if (reqService == Constants.ClientService.viewTrains) {
log.debug("Start: viewTrains");
return TrainService.viewAllTrains(trainDAO);
}
else return null;
} |
d6fa8003-2035-423b-a6ab-d28c00cfe605 | 2 | public static Properties neuesspiel() throws IOException{
Properties neuesspiel = loadProperties("neuesspiel.txt");
if(neuesspielbutton == true) {
Properties spielstand = loadProperties("spielstand.txt");
spielername1 = spielstand.getProperty("spielername1", "Nicht vorhanden");
spielername2 = spielstand.getProperty("spielername2", "Nicht vorhanden");
}
String string_restkartentisch = neuesspiel.getProperty("restkartentisch", "24");
restkartentisch = Integer.parseInt(string_restkartentisch);
jLabelRestkartenTisch.setText("Resttische: "+restkartentisch);
String string_restkartengast = neuesspiel.getProperty("restkartengast", "0");
restkartengast = Integer.parseInt(string_restkartengast);
jLabelRestkartenGast.setText("Restgäste: "+restkartengast);
String string_restbarplaetze = neuesspiel.getProperty("restbarplaetze", "21");
restbarplaetze = Integer.parseInt(string_restbarplaetze);
jLabelRestbarplaetze.setText("Barplätze übrig: "+restbarplaetze);
String string_punktespieler1 = neuesspiel.getProperty("punktespieler1", "0");
punktespieler1 = Integer.parseInt(string_punktespieler1);
jLabelPunkteSpieler1.setText("Punkte "+spielername1+": "+punktespieler1);
String string_punktespieler2 = neuesspiel.getProperty("punktespieler2", "0");
punktespieler2 = Integer.parseInt(string_punktespieler2);
jLabelPunkteSpieler2.setText("Punkte "+spielername2+": "+punktespieler2);
String string_spieler = neuesspiel.getProperty("spieler", "1");
spieler = Integer.parseInt(string_spieler);
if(spieler == 1){
jLabelSpieler.setText("Am Zug: "+spielername1);
}
else{
jLabelSpieler.setText("Am Zug: "+spielername2);
}
System.out.println("("+ausgabenummer+") "+"Neues Spiel gestartet"); ausgabenummer += 1;
return neuesspiel;
} |
826321c5-32f7-40b9-9a25-a1910876e54c | 0 | public int getAge() {
return age;
} |
6a69d25f-0bcb-401e-a77b-75a6ee0329bf | 8 | public String readLine() throws IOException {
StringBuffer line = new StringBuffer();
char ch = read();
try {
while (ch != '\n' && ch != '\r') {
if (hasComments) {
if (ch == lineComment) {
skipComments(ch);
break;
}
if (ch == startComment) {
skipComments(ch);
ch = read();
}
}
line.append(ch);
ch = read();
}
// accommodate DOS line endings..
if (ch == '\r') {
if (next() == '\n') read();
}
lastDelimiter = ch;
} catch (EOFException e) {
// We catch an EOF and return the line we have so far
// encounteredEndOfFile();
}
return line.toString();
} |
9e119691-e9d5-4597-8a06-57748aedee6e | 1 | public Camera(GameWorld gameWorld, Ticker ticker, FrameBuffer buffer) {
this.gameWorld = gameWorld;
this.ticker = ticker;
this.cam = gameWorld.getWorld().getCamera();
mouseListener = new MouseListener(buffer);
if(!fixedOrientation)
mouseListener.hide();
height = buffer.getOutputHeight();
width = buffer.getOutputWidth();
} |
9a644c99-14e5-4905-9331-13a5a4b49e2e | 0 | public PBKDF2ParameterType createPBKDF2ParameterType() {
return new PBKDF2ParameterType();
} |
3e2e264a-3878-4f7d-a9b3-827bc4ab18fe | 2 | private void LoadFriendRequests() throws SQLException
{
Grizzly.GrabDatabase().SetQuery("SELECT * FROM server_friendships_pending WHERE reciever_id = '" + this.ID + "'");
if (Grizzly.GrabDatabase().RowCount() > 0)
{
ResultSet Pending = Grizzly.GrabDatabase().GrabTable();
while(Pending.next())
{
FriendRequests.put(
new Integer(Pending.getInt("id")),
UserHandler.GenerateUser(Pending.getInt("sender_id")));
}
}
} |
827a340f-18d6-4788-bc0a-3f83aed407a1 | 0 | @Test
public void testSave() throws Exception {
User user = new User();
user.setLoginno("12345");
user.setLoginpwd("45678");
user = repository.save(user);
repository.delete(user.getId());
} |
fd47f56b-d2c9-4764-bf08-4adb4b933a01 | 6 | public String gravarUSuario (String nome, String senha, String email, String login) {
String resposta = "";
System.out.println("Iniciando inserçao de usuario");
if(!nome.equals(null) || !senha.equals(null) || email.equals(null) || login.equals(null)){
Usuario usuario = new Usuario ();
if (senha.length() > 15) {
int tamanhoDaSenha = senha.length();
System.out.println("sua senha deve conter no maximo 15 caracteres, mas contem " + tamanhoDaSenha);
resposta = "sua senha deve conter no maximo 15 caracteres";
return resposta;
}
System.out.println("preenchendo campos");
usuario.setNome(nome);
usuario.setSenha(senha);
usuario.setEmail(email);
usuario.setLogin(login);
if (comparar(usuario)) {
resposta = "Login ja existente, por favor, escolha um login diferente";
return resposta;
}
UsuarioDAO dao = new UsuarioDAO();
System.out.println("persistindo usuario");
dao.testeDeInserção(usuario);
resposta = "salvo com sucesso";
} else {
resposta = "valores nulos";
}
return resposta;
} |
44fcd167-c289-4c57-bd99-a5c9c92e16e0 | 1 | public void add(Word wordObject){
Node newNode = new Node();
newNode.data = wordObject;
newNode.left = null;
newNode.right = null;
if (root == null) {root = newNode;}else {root.addNode(newNode);}
fixAfterAdd(newNode);
} |
0cc8f0e3-febf-45f5-bf02-b034f307eee2 | 6 | public boolean remove(int userId) {
Contact contact = userIdMap.get(userId);
if (contact == null)
return false;
userIdMap.remove(userId);
if (contact.displayName != null)
displayNameMap.get(contact.displayName).remove(contact);
if (contact.firstName != null)
firstNameMap.get(contact.firstName).remove(contact);
if (contact.lastName != null)
lastNameMap.get(contact.lastName).remove(contact);
if (contact.email != null)
emailMap.get(contact.email).remove(contact);
if (contact.phoneNumber != null)
phoneNumberMap.get(contact.phoneNumber).remove(contact);
// return the user ID to be reused
userIdMinHeap.add(userId);
return true;
} |
435dd1ec-8280-42d7-b0e1-68d638b1a549 | 2 | public int getHeadNode(int id){
conn = new SQLconnect().getConnection();
int headnodeId = 0;
try {
String sql = "select * from worlds where display = 'true' and id ="+id;
Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象
ResultSet rs = st.executeQuery(sql); // 执行查询操作的sql语句,并返回插入数据的个数
while (rs.next())
{
headnodeId = rs.getInt("time_headnode");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return headnodeId;
} |
605729c8-19a9-414d-a5d1-68a90d045336 | 0 | @Column(name = "PRP_MOA_TIPO")
@Id
public String getPrpMoaTipo() {
return prpMoaTipo;
} |
db49bcf8-c342-46f5-8a36-33288566fd60 | 6 | public void paintThumb(Graphics g) {
Icon icon = null;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
if (isRollover && slider.isEnabled()) {
icon = getThumbHorIconRollover();
} else {
icon = getThumbHorIcon();
}
} else {
if (isRollover && slider.isEnabled()) {
icon = getThumbVerIconRollover();
} else {
icon = getThumbVerIcon();
}
}
Graphics2D g2D = (Graphics2D) g;
Composite savedComposite = g2D.getComposite();
if (!slider.isEnabled()) {
g.setColor(AbstractLookAndFeel.getBackgroundColor());
g.fillRect(thumbRect.x + 1, thumbRect.y + 1, thumbRect.width - 2, thumbRect.height - 2);
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2D.setComposite(alpha);
}
icon.paintIcon(null, g, thumbRect.x, thumbRect.y);
g2D.setComposite(savedComposite);
} |
0fabcc88-6a45-4cf7-a12b-cd29651d7fef | 2 | public static void main(String[] args) {
System.out.println("Введіть к-сть чисел -->");
Scanner in = new Scanner (System.in);
int count = in.nextInt();
int max = 0, min = 0, var = 0;
for (int i=0; i < count; i++ ) {
System.out.println("Введіть число");
var=in.nextInt();
if (var > min) {max=var; min=var;}
}
System.out.println("Маскимальне число="+max);
} |
32e9f204-7c17-4676-96ca-7ef95bb68b5b | 5 | private void PrintCurrentRoomContainers() {
Iterator<String> iter = currentRoom.GetContainers().iterator();
while (iter.hasNext()) {
System.out.print(iter.next());
if (iter.hasNext()) {
System.out.print(", ");
}
}
// Set up to print the creatures
if (! currentRoom.GetCreatures().isEmpty()) {
if ( !currentRoom.GetItems().isEmpty() || !currentRoom.GetContainers().isEmpty()) {
System.out.print(", ");
}
}
} |
1e170057-53d3-447f-9f60-2541bcb3e68f | 7 | ImagePanel(String name, final JFrame f) {
this.add(new JLabel(name));
try {
img = ImageIO.read(new File(name));
this.setPreferredSize(new Dimension(
img.getWidth(), img.getHeight()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//declares and adds the Quit and To Home JButtons
JButton quitButton = new JButton("Quit");
JButton toHomeButton = new JButton("To Home");
quitButton.setFont(new Font("American Typewriter", Font.PLAIN, 15));
toHomeButton.setFont(new Font("American Typewriter", Font.PLAIN, 15));
setLayout(null);
toHomeButton.setLocation(560,530);
toHomeButton.setSize(100,50);
quitButton.setLocation(350,530);
quitButton.setSize(100,50);
this.add(toHomeButton);
this.add(quitButton);
//exits application when clicked
quitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.exit(0);
}
});
//show Home Page card in CardLayout implementation
toHomeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(Client.sendMsg("LEAVE_SCOREBOARD").contains("FAILURE")){
JOptionPane.showMessageDialog(null,"Nah, I won't let you.", "Oops! Try again.", JOptionPane.NO_OPTION);
} else {
new JoinGameGUI();
f.dispose();
}
}
});
String[][] rowData = new String[usernames.size()][7];
String[]columnNames = { "Username", "Character", "Damage","Comets Sucked In","Total Deaths","Power Ups Used","Max Velocity"};
for (int i=0;i<usernames.size();i++){
rowData[i][0] = usernames.get(i);
rowData[i][1] = characters.get(i);
rowData[i][2] = damages.get(i);
rowData[i][3] = comets.get(i);
rowData[i][4] = deaths.get(i);
rowData[i][5] = powerups.get(i);
rowData[i][6] = maxvels.get(i);
}
for (int i=0;i<usernames.size();i++){
for (int j=0;j<6;j++){
System.out.println(rowData[i][j]+"");
}
}
//System.out.println(rowData);
JTable myTable = new JTable(rowData, columnNames);
myTable.setFont(new Font("American Typewriter",Font.ITALIC,14));
myTable.setForeground(Color.WHITE);
myTable.setOpaque(false);
((DefaultTableCellRenderer) myTable.getDefaultRenderer(Object.class)).setOpaque(false);
JScrollPane scrollpane = new JScrollPane(myTable);
scrollpane.setOpaque(false);
scrollpane.getViewport().setOpaque(false);
scrollpane.setBounds(70,50,800,400);
this.add(scrollpane);
//Player1:
/*
ImageIcon img1 = getImageIcon(characterP1);
Image image1 = img1.getImage();
Image newImage1 = image1.getScaledInstance(100,100, java.awt.Image.SCALE_SMOOTH);
img1 = new ImageIcon(newImage1);
JLabel label1 = new JLabel(img1);
label1.setSize(60,50);
label1.setLocation(95,300);
this.add(label1);
*/
//Other players:
for(int i=0; i< characters.size(); i++){
System.out.println(characters.get(i));
ImageIcon img = getImageIcon(characters.get(i));
Image image = img.getImage();
Image newImage = image.getScaledInstance(100,100, java.awt.Image.SCALE_SMOOTH);
img = new ImageIcon(newImage);
JLabel label = new JLabel(img);
label.setSize(60,50);
label.setLocation(95,300);
//this.add(label);
}
} |
7484d8a1-219f-4797-a5bb-db6e9b745a15 | 9 | public void target() {
GameActor t = getTargetedActor();
if(t != null) {
PhysicsComponent tPC = (PhysicsComponent)t.getComponent("PhysicsComponent");
if(tPC != null) {
PhysicsComponent ownPC = (PhysicsComponent)getOwningActor().getComponent("PhysicsComponent");
if(ownPC != null) {
if(ownPC.getTargetX() != tPC.getX() || ownPC.getTargetY() != tPC.getY()) {
ownPC.setTarget(tPC.getX(), tPC.getY());
}
if(ownPC.getAngleRad() < ownPC.getTargetAngle() + 0.1 && ownPC.getAngleRad() > ownPC.getTargetAngle() - 0.1) {
WeaponsComponent wc = (WeaponsComponent)getOwningActor().getComponent("WeaponsComponent");
if(wc != null) {
if(wc.ready()) {
Application.get().getEventManager().queueEvent(new FireWeaponEvent(owner));
}
}
}
}
}
}
} |
c42e00a4-59bb-4c37-b98e-c920544f1233 | 6 | public void render()
{
int i, j, k;
for (j = 0; j < MAPHEIGHT; ++j)
for (i = 0; i < MAPWIDTH; ++i)
if (MainFrame[i][j] == true)
{
// render only the frames that are within the radius of the MainFrame
// all other frames remain un-drawn
FrameMatrix[i][j].draw(xRef + (i * SCREENWIDTH), yRef + (j * SCREENHEIGHT));
if (TERRAINBOXES)
{
for (k = 0; k < map.blockDepth(); ++k)
BlockArtist.draw(map.block(i, j, k));
}
MainFrame[i][j] = false;
}
if (HITBOXES)
{
BlockArtist.draw(rChar.getBox());
}
Character.draw(rChar.getX(), rChar.getY());
//Character.draw(xChar, yChar);
} |
301f26da-1104-4494-9339-d751ecc1e761 | 1 | public Object saveOps() {
Stack state = new Stack();
int pos = currentLine.length();
while (currentBP.parentBP != null) {
state.push(new Integer(currentBP.breakPenalty));
/* We don't want parentheses or unconventional line breaking */
currentBP.options = DONT_BREAK;
currentBP.endPos = pos;
currentBP = currentBP.parentBP;
}
return state;
} |
17b8405c-fae9-4808-a279-3fd68beb3fbb | 6 | public static List<String> genPar(int l, int r){
ArrayList<String> result = new ArrayList<String>();
if(l == 0){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < r; i++)
sb.append(")");
result.add(sb.toString());
return result;
}
if(l >= 1){
for(String val : genPar(l-1, r))
result.add("(" + val);
}
if(r>l){
for(String val : genPar(l, r-1))
result.add(")" + val);
}
return result;
} |
51363e8b-1073-4653-aeda-96d98641a87c | 7 | public static Set<Long> findNewFriend(TwitterBrain brain, Twitter twi,
int count) {
int total = count;
ArrayList<Long> located = new ArrayList<Long>();
try {
brain.updateFollowers();
for (Long id : brain.getFollowers()) {
IDs ids = twi.getFollowersIDs(id, -1);
for (Long l : ids.getIDs()) {
User user = twi.showUser(l);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (brain.isUserOk(user)) {
count--;
located.add(l);
logger.info((total - count) + "/" + total);
}
if (count == 0) {
break;
}
}
if (count == 0) {
break;
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
HashSet<Long> result = new HashSet<Long>(located);
result.removeAll(brain.getFollowers());
result.remove(brain.getMyId());
return result;
} |
414c1c9a-72cd-44c6-9fa5-af0cf5033319 | 5 | final void method3396(int i, int i_96_) {
if (i_96_ > -5)
aClass223_7175 = null;
anInt7146++;
if ((i & ~0x7f) != 0) {
if ((i & ~0x3fff ^ 0xffffffff) != -1) {
if ((~0x1fffff & i ^ 0xffffffff) != -1) {
if ((i & ~0xfffffff) != 0)
putByte(0x80 | i >>> 1028243868);
putByte(0x80 | i >>> 955016565);
}
putByte((0x2000f4 | i) >>> -1096734770);
}
putByte(0x80 | i >>> -541352473);
}
putByte(i & 0x7f);
} |
b119f8d7-150f-4561-abc5-9e952abf8d1f | 9 | private boolean generateAndSearchXDLRC(){
BufferedReader input;
String[] tokens;
String line;
try {
for(String part : partNames){
if(!new File(part+".xdlrc").exists()){
xdlrcFileNames.add(part+".xdlrc");
if(!RunXilinxTools.generateBriefXDLRCFile(part,part+".xdlrc")){
return false;
}
}
input = new BufferedReader(new FileReader(part + ".xdlrc"));
while((line = input.readLine()) != null){
tokens = line.split("\\s+");
if(tokens.length > 1 && tokens[1].equals("(tile")){
this.tileSet.add(tokens[5]);
//this.tileSet.add(this.removeCoordinates(tokens[4]));
}
else if(tokens.length > 1 && tokens[1].equals("(primitive_def")){
this.primitiveSet.add(tokens[2]);
}
}
}
}
catch (IOException e) {
System.out.println("XDLRC Generation failed");
return false;
}
return true;
} |
2df28348-4e1f-4ee7-96c2-72da9448a951 | 8 | public LongSet parseString(String txt)
{
intArray=new int[0];
longArray=new long[0];
txt=txt.trim();
if(txt.length()==0)
return null;
if((!txt.startsWith("{"))&&(!txt.endsWith("}")))
return null;
final int x=txt.indexOf("},{");
if(x<0)
return null;
if(x>1)
{
final String[] strs=txt.substring(1,x).split(",");
intArray=new int[strs.length];
for(int v=0;v<strs.length;v++)
{
intArray[v]=Integer.parseInt(strs[v].trim());
}
}
if(x+3<txt.length()-1)
{
final String[] strs=txt.substring(x+3,txt.length()-1).split(",");
longArray=new long[strs.length];
for(int v=0;v<strs.length;v++)
{
longArray[v]=Long.parseLong(strs[v].trim());
}
}
return this;
} |
a1ba0abe-6107-47f0-b2f0-fa205dfd7f8a | 7 | @Override
public Query parse() {
if(!this.prepared) {
this.prepared = true;
StringBuilder sB = new StringBuilder();
sB.append("UPDATE ");
sB.append(table.replace("#__", this.db.getPrefix()));
sB.append("\n");
sB.append(" SET ");
int s = this.set.size();
for(int i = 0; i < s; ++i) {
if(i > 0) {
sB.append(", ");
}
Elem e = this.set.get(i);
String v = e.getValue() == null ? "" : e.getValue();
ValueType vT = e.getValueType();
String vTS = vT.getTextual().replace("%1", e.getField().replace("#__", this.db.getPrefix()));
vTS = vTS.replace("%2", v.replace("#__", this.db.getPrefix()));
sB.append(vTS);
}
sB.append("\n");
if(this.where.size() > 0) {
sB.append(" WHERE ");
Iterator<Group> whereIterator = this.where.iterator();
while(whereIterator.hasNext()) {
Group g = whereIterator.next();
if(!g.isParsed()) {
g.parse();
}
sB.append(g.getType().getTextual());
sB.append(g.getParsedGroup());
}
sB.append("\n");
}
this.query = sB.toString();
}
return this;
} |
cd7beada-d3d3-4d85-9731-b36a68fb0b37 | 5 | @Command(name = "help")
public void helpCommand(CommandSender sender, CommandArgs args)
{
if (args.size() > 0)
{
String commandName = args.getString(0);
SubCommand command = getCommand(commandName);
if (command != null)
{
sender.sendMessage("/" + args.getBaseLabel() + " " + args.getString(0) + " " + command.getUsage());
sender.sendMessage(" " + _(command.getName() + "_description"));
}
else
{
sender.sendMessage(_("help_cmdnotfound", args.getString(0)));
}
}
else
{
sender.sendMessage(_("help_listofcommands"));
sender.sendMessage(" ");
List<SubCommand> subCommands = new ArrayList<SubCommand>(args.getBaseCommand().getAllSubCommands());
Collections.sort(subCommands, SubCommand.COMPARATOR);
for (SubCommand command : subCommands)
{
if (command.getPermission() != null && !sender.hasPermission(command.getPermission()))
{
continue;
}
sender.sendMessage("/" + args.getBaseLabel() + " " + command.getName() + " " + command.getUsage());
sender.sendMessage(" " + _(command.getName() + "_description"));
sender.sendMessage(" ");
}
}
} |
71b2bd5a-363b-4388-8f9f-cb6595af9306 | 7 | public void stworzPolaGry(String _nazwaPola, boolean _czyRysowacSymbole, boolean _czyPrzerysowac, JLabel[][] _pola, int _szerPojPola, int _wysPojPola, int _skok, JPanel _obszarPol, JPanel _obszarLiter, JPanel _obszarCyfr, int _szer, int _wys)
{
JLabel lb_litery[] = new JLabel[10];
JLabel lb_cyfry[] = new JLabel[10];
_pola = new JLabel[10][10];
String litery[] = {"A","B","C","D","E","F","G","H","I","J"};
int x = 0, y = 0;
/*if(_czyRysowacSymbole)
{
x = _skok*(-1); y = _skok*(-1);
}
else
{*/
x = 0; y = 0;
//}
for(int i = 0;i < 10; i++)
{
//if(_czyRysowacSymbole)
//x = _skok*(-1);
//else
x = 0;
y+=_skok;
for(int j = 0;j < 10; j++)
{
x+=_skok;
_pola[j][i] = new JLabel();
if(!_nazwaPola.equals("pole gracza"))
_pola[j][i].setBounds(x-1, y, _szerPojPola, _wysPojPola);
else
_pola[j][i].setBounds(x+1, y+1, _szerPojPola, _wysPojPola);
if(_czyRysowacSymbole)
_pola[j][i].setText(String.valueOf(j)+String.valueOf(i));
//if(_czyRysowacSymbole)
_pola[j][i].setOpaque(false);
//_pola[j][i].setBorder(BorderFactory.createLineBorder(new Color(240, 240, 240), 3));
_pola[j][i].setHorizontalAlignment(SwingConstants.CENTER);
_pola[j][i].setVerticalAlignment(SwingConstants.CENTER);
//_pola[j][i].setBorder(BorderFactory.createLineBorder(Color.RED, 1));
_pola[j][i].addMouseListener(this);
_obszarPol.add(_pola[j][i]);
if(_nazwaPola.equals("pole gracza"))
{
if(widokGry.uzytkownik.plansza.l_polaPlanszy_GRACZ[j][i].getRodzajPola().equals("1"))
_pola[j][i].setIcon(img_statek2);
else
_pola[j][i].setIcon(img_zwyklePole2);
}
/*if(_czyRysowacSymbole)
{
lb_cyfry[i] = new JLabel();
lb_cyfry[i].setBounds(x+3, 0, _szer, _wys);
lb_cyfry[i].setFont(new Font("Verdana", Font.BOLD, 11));
lb_cyfry[i].setText(String.valueOf(j+1));
lb_cyfry[i].setHorizontalTextPosition(SwingConstants.CENTER);
//lb_cyfry[i].setBorder(BorderFactory.createLineBorder(Color.RED, 1));
_obszarCyfr.add(lb_cyfry[i]);
}*/
}
/*if(_czyRysowacSymbole)
{
lb_litery[i] = new JLabel();
lb_litery[i].setBounds(0, y+3, _szer, _wys);
lb_litery[i].setFont(new Font("Verdana", Font.BOLD, 11));
lb_litery[i].setText(litery[i]);
lb_litery[i].setHorizontalAlignment(SwingConstants.RIGHT);
//lb_litery[i].setBorder(BorderFactory.createLineBorder(Color.RED, 1));
_obszarLiter.add(lb_litery[i]);
}*/
}
if(_czyPrzerysowac)
{
przerysujPlanszeGRACZA(_pola);
lb_polaGry_GRACZ = _pola;
}
else
{
lb_polaGry_PRZECIWNIK = _pola;
}
} |
c284b212-11ba-4dca-9b45-3122ef05374e | 7 | public List<Property<?>> getProperty(String name){
List<Property<?>> ret = new ArrayList<Property<?>>();
if(name == null){
return ret;
}
for(Property<?> property : properties){
if(name.equals(property.getName())){
ret.add(property);
}
}
return ret;
} |
8be80e99-93fb-45c4-9d44-c995574dd613 | 8 | @EventHandler
public void onPotionSplashEvent(PotionSplashEvent e ) {
for (Entity entity : e.getAffectedEntities()) {
if (entity instanceof Player) {
Player p = (Player) entity;
if (!UVampires.vampires.containsKey(p)) return;
if (UVampires.vampires.get(p)) {
if (e.getPotion().getEffects().equals(PotionEffectType.HEAL)) {
p.addPotionEffect(new PotionEffect(PotionEffectType.HARM, 0, 3));
}
if (e.getPotion().getEffects().equals(PotionEffectType.HARM)) {
p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 0, 3));
}
if (e.getPotion().getEffects().equals(PotionEffectType.REGENERATION)) {
p.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 2, 5));
}
if (e.getPotion().getEffects().equals(PotionEffectType.POISON)) {
p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 2, 5));
}
}
}
}
} |
a84570c8-1099-466c-a26e-d0a17a1b55ec | 3 | public int doCCIR493_160FFT (CircularDataBuffer circBuf,WaveData waveData,int start) {
// Get the data from the circular buffer
double samData[]=circBuf.extractDataDouble(start,80);
int a;
double datar[]=new double[FFT_160_SIZE];
for (a=0;a<datar.length;a++) {
if ((a>=60)&&(a<120)) datar[a]=samData[a-60];
else datar[a]=0.0;
datar[a]=windowBlackman(datar[a],a,datar.length);
}
fft160.realForward(datar);
double spec[]=getSpectrum(datar);
int freq=getFFTFreq (spec,waveData.getSampleRate());
return freq;
} |
b9297f72-81a9-497b-875a-4fa765be6868 | 1 | public Object get(String key) {
return key == null ? null : mMap.get(key);
} |
6fbf1eaa-cf4d-4dfa-9c73-6e553967f3ba | 8 | private boolean isScrambleCore(String s1, String s2) {
boolean result = false;
List<String> key = new ArrayList<String>();
key.add( s1 );
key.add( s2 );
if( cache.containsKey( key ) ) return cache.get( key );
if( s1.equals(s2) ) {
cache.put( key, true );
return true;
}
if( s1.length() == 1 ) {
cache.put( key, false );
return false;
}
int n = s1.length();
for( int i = 0; i < n - 1; i++ ) {
// forward
String s11 = s1.substring(0, i+1);
String s12 = s1.substring(i+1);
String s21 = s2.substring(0, i+1);
String s22 = s2.substring( i + 1 );
if( isScrambleCore(s11, s21 ) && isScrambleCore( s12, s22 ) ) {
result = true;
break;
}
// backward
s21 = s2.substring(0, n - 1 - i );
s22 = s2.substring(n - 1 - i );
if( isScrambleCore(s11, s22 ) && isScrambleCore( s12, s21 ) ) {
result = true;
break;
}
}
cache.put( key, result );
return result;
} |
48fd9ec7-2dd8-4ed5-8177-59a0a266811d | 7 | private void run()
{
isRunning = true;
int frames = 0;
long frameCounter = 0;
game.init();
double lastTime = TimeHelper.getTime();
double unprocessedTime = 0;
while ( isRunning )
{
if ( Display.wasResized() )
{
reshape( Display.getWidth(), Display.getHeight() );
}
boolean render = false;
double startTime = TimeHelper.getTime();
double passedTime = startTime - lastTime;
lastTime = startTime;
unprocessedTime += passedTime;
frameCounter += passedTime;
while ( unprocessedTime > frameTime )
{
render = true;
unprocessedTime -= frameTime;
if ( Window.isCloseRequested() )
stop();
game.input( (float) frameTime );
Input.update();
debug();
game.update( (float) frameTime );
game.physic( physicsEngine, (float) frameTime );
if ( frameCounter >= 1.0 )
{
System.out.println( frames );
frames = 0;
frameCounter = 0;
}
}
if ( render )
{
game.render( renderEngine );
Window.render();
frames++;
}
else
{
try
{
Thread.sleep( 1 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
}
cleanUp();
} |
73f05c42-9345-47a5-868f-88025a8284a6 | 5 | public static Hashtable<Integer, Double> GrowthSort(int start, int range, int averageCount)
{
Random rnd = new Random();
Hashtable<Integer, Double> NTable = new Hashtable<Integer, Double>();
//Go through the range
for (int n = start; n < range+1; n+=50000)
{
int warm = 0;
while (warm < 10000)
{ warm++; /*Let the thread warm up.*/ System.nanoTime(); }
//Take the average algorithm time at range r
long algorithmTime = 0;
for (int a = 0; a < averageCount; a++)
{
//Timing
ArrayBasedCollection<Integer> arr = new ArrayBasedCollection<Integer>();
arr.addAll(permuteInts(n));
long warmUptime = System.nanoTime();
//Run the algorithm
arr.toSortedList(new IntegerComparator());
long sortTime = System.nanoTime();
//OVERHEAD
for(int i = 1; i<n; i++){
int j;
for(j = i-1; j>=0; j--);
}
long overHead = System.nanoTime();
//Calculate time
algorithmTime += (sortTime - warmUptime) - (overHead - sortTime);
}
System.out.println(n + "\t" + (double) algorithmTime/averageCount);
NTable.put(n ,(double) (algorithmTime/averageCount));
}
return NTable;
} |
310079f8-3b8e-4f33-a505-ad8295200d4a | 5 | public void removeAllNonCreativeModeEntities() {
for(int var1 = 0; var1 < this.width; ++var1) {
for(int var2 = 0; var2 < this.depth; ++var2) {
for(int var3 = 0; var3 < this.height; ++var3) {
List var4 = this.entityGrid[(var3 * this.depth + var2) * this.width + var1];
for(int var5 = 0; var5 < var4.size(); ++var5) {
if(!((Entity)var4.get(var5)).isCreativeModeAllowed()) {
var4.remove(var5--);
}
}
}
}
}
} |
27920089-2b8f-499b-ab34-9c86f9287d8c | 5 | @Override
public void receiveProtocol(AsynchronousConnection asynchronousConnection) throws IOException {
while (asynchronousConnection.getReader().getBuffer().hasRemaining()) {
if (getOpcode() == -1) {
setOpcode(asynchronousConnection.getReader().getBuffer().get() - asynchronousConnection.getSecureRead().getNextValue() & 0xFF);
setLength(Constants.PACKET_SIZES[getOpcode()]);
}
if (getLength() == -1) {
if (!asynchronousConnection.getReader().getBuffer().hasRemaining()) {
asynchronousConnection.getReader().getBuffer().clear();
return;
}
setLength(asynchronousConnection.getReader().getBuffer().get() & 0xFF);
}
if (asynchronousConnection.getReader().getBuffer().remaining() < getLength()) {
asynchronousConnection.getReader().getBuffer().compact();
return;
}
byte[] payloadSize = new byte[getLength()];
asynchronousConnection.getReader().getBuffer().get(payloadSize);
ByteBuffer packetPayload = ByteBuffer.allocate(getLength());
packetPayload.put(payloadSize);
packetPayload.flip();
IncomingPacket packetRead = new IncomingPacket(packetPayload, getOpcode(), getLength());
IncomingPacketRegistration.dispatchToListener(packetRead, asynchronousConnection.getPlayer());
setOpcode(-1);
setLength(-1);
}
} |
9e4b4fe8-ba9c-438e-a41d-ef6a65bc89aa | 1 | @Override
Integer redactEntity(Criteria criteria, AbstractDao dao) throws DaoException {
Integer idHotel = (Integer) criteria.getParam(DAO_ID_HOTEL);
if (idHotel != null) {
return updateHotel(criteria, dao);
} else {
return createHotel(criteria, dao);
}
} |
33d38557-2db3-4646-86ae-a25712528e67 | 9 | public void updatePosition() {
if (xPos < xDestination)
xPos++;
else if (xPos > xDestination)
xPos--;
if (yPos < yDestination)
yPos++;
else if (yPos > yDestination)
yPos--;
if (xPos == xDestination && yPos == yDestination) {
if (command==Command.GoToSeat) agent.msgAnimationFinishedGoToSeat();
else if(command == Command.PayForMeal){
agent.msgAnimationFinishedGoToCashier();
}
else if (command==Command.LeaveRestaurant) {
agent.msgAnimationFinishedLeaveRestaurant();
////System.out.println("about to call gui.setCustomerEnabled(agent);");
isHungry = false;
//gui.setCustomerEnabled(agent);
}
command=Command.noCommand;
}
} |
710ee307-1fbd-4333-9a0b-cd072cabaceb | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
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,null,this,verbalCastCode(mob,null,auto),auto?L("Something is happening!"):L("^S<S-NAME> begin(s) to chant...^?"));
if(mob.location().okMessage(mob,msg))
{
final int mana=mob.curState().getMana();
mob.location().send(mob,msg);
for(int i=0;i<(adjustedLevel(mob,asLevel)/2);i++)
CMLib.threads().tickAllTickers(mob.location());
if(mob.curState().getMana()>mana)
mob.curState().setMana(mana);
mob.location().show(mob,null,this,verbalCastCode(mob,null,auto),auto?L("It stops."):L("^S<S-NAME> stop(s) chanting.^?"));
}
}
else
beneficialVisualFizzle(mob,null,L("<S-NAME> chant(s), but nothing happens."));
return success;
} |
5858e186-f73e-438e-83fd-867a25d194db | 8 | public void moveSideways(int move)
{
int unit;
boolean left;
if(move >= 0)
{
unit = 1;
left = false;
}
else
{
unit = -1;
left = true;
}
if(!currentCreatedAndMovable)
return;
try
{
lock.acquire();
}
catch (InterruptedException e)
{
return;
}
for(int h = 0; h < Math.abs(move); h++)
{
for(int i = 0; i < currentBlock.length; i++)
{
if(!isAbleToMove(currentBlock[i], currentBlock[i].getRowIndex(), currentBlock[i].getColumnIndex() + unit))
{
lock.release();
return;
}
}
for(int i = 0; i < currentBlock.length; i++)
{
if(left)
currentBlock[i].moveLeft(1);
else
currentBlock[i].moveRight(1);
}
currentChanged = true;
}
lock.release();
} |
003e2206-70c2-487f-8a19-0dc5ac31963f | 4 | public void entrenar(String[][] entradas){
boolean finalizado = false;
int y = 0;
double error = 0, errorCuadraticoMedio = 0, valorActivacion = 0;
this.numeroEpocasFinal = 0;
this.errores.clear();
while(!finalizado){
for(int n = 0; n < entradas.length; n++){
System.out.println("ENTRADA " + (n+1) + " ------------------------------------------");
//Calcular todos los n (a) (salidas de cada neurona de cada capa) dada una entrada
this.feedForward(Arrays.copyOfRange(entradas[n], 0, entradas[n].length-1));
//Ejecutar el Adaline con la salida del feed y los pesos asignados
valorActivacion = this.obtenidaAdaline(this.salidasPorCapa[this.getNumeroCapasOcultas() - 1]);
y = Integer.valueOf(entradas[n][entradas[n].length-1]); //Clase esperada
System.out.println("Clase esperada " + y);
//Calculo del error de neurona final
error = y - valorActivacion;
System.out.println("Error: " + error);
//Calcular sensibilidad (backward), repartir el error
this.calcularSensibilidad(valorActivacion, error, entradas[n].length-1);
//Ajuste de pesos, mando el numero de elementos por entrada y la entrada inicial
this.ajustarPesos(entradas[n].length-1, Arrays.copyOfRange(entradas[n], 0, entradas[n].length-1));
errorCuadraticoMedio = Math.pow(error, 2); //Error cuadratico
this.errorDeseadoFinal +=errorCuadraticoMedio; //Error acumulado
}
this.numeroEpocasFinal++;
this.errorDeseadoFinal /= entradas.length;
//Guardar el error para la grafica
this.errores.add(this.errorDeseadoFinal);
System.out.println("["+ this.numeroEpocasFinal +"] Error Esperado: " + this.errorDeseadoFinal);
if(this.numeroEpocasFinal >= this.limiteEpocas || this.errorDeseadoFinal <= this.errorDeseado)
finalizado = true;
else
this.errorDeseadoFinal = 0;
}
} |
2e9b81fc-068b-4d9a-8183-41b4b7f3edea | 6 | @SuppressWarnings("unchecked")
public List<String> asStringArray(RuleContext ruleContext)
{
if (ruleContext.getEvents().isDebugEnabled())
{
ruleContext.getEvents().debug(" " + TYPE + ".asStringArray: input model path=" + mPath);
}
Element collection = (Element) ruleContext.getInputModel().selectSingleNode(mPath);
if (null == collection)
{
if (ruleContext.getEvents().isWarnEnabled())
{
ruleContext.getEvents().warn(" " + TYPE + ": Path specified not found in the input model:" + mPath);
}
return new ArrayList<String>();
}
List<Element> valueElements = collection.elements(CompareTypeCollection.ELEMENT_ENTRY);
if (null != valueElements)
{
// a_List of entries
ArrayList<String> values = new ArrayList<String>(valueElements.size());
for (Element e : valueElements)
{
values.add(e.getText());
}
return values;
}
// a_Comma delimited
ArrayList<String> values = new ArrayList<String>();
StringTokenizer tokens = new StringTokenizer(collection.getText());
while (tokens.hasMoreTokens())
{
values.add(tokens.nextToken());
}
return values;
} |
860897ff-6a5b-49ec-a0cb-71771211a043 | 8 | protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String funcion = request.getParameter("funcion");
if (funcion == null){
//error
}else{
if(funcion.equals("alta"))
{
boolean respuesta;
respuesta = NuevoProducto(request, response);
if (respuesta) {
request.getSession().setAttribute("ABMProd", new String("Producto Registrado Correctamente"));
out.println("productos.jsp");
} else {
request.getSession().setAttribute("ABMProd", new String("Error al Registrar Producto"));
out.println("productos.jsp");
}
}
else if(funcion.equals("baja"))
{
boolean respuesta;
respuesta = EliminarProducto(request, response);
if (respuesta) {
request.getSession().setAttribute("ABMProd", new String("Producto Eliminado Correctamente"));
out.println("productos.jsp");
} else {
request.getSession().setAttribute("ABMProd", new String("Error al Eliminar Producto"));
out.println("productos.jsp");
}
}
else if(funcion.equals("modificacion"))
{
boolean respuesta;
respuesta = ModificarProducto(request, response);
if (respuesta) {
request.getSession().setAttribute("ABMProd", new String("Producto Modificado Correctamente"));
out.println("productos.jsp");
} else {
request.getSession().setAttribute("ABMProd", new String("Error al Modificar Producto"));
out.println("productos.jsp");
}
}
}
}catch (Exception ex){
}finally {
}
} |
06a70fb7-8c31-40f6-81b9-ebef40cd1d54 | 4 | @Override
public int compareTo(PlageHoraire t) {
if(this.heureFin.before(t.getHeureDebut()) || this.heureFin.equals(t.getHeureDebut())) {
return -1;
}
else if(this.heureDebut.after(t.getHeureFin()) || this.heureDebut.equals(t.getHeureFin())) {
return 1;
}
else {
return 0;
}
} |
2c4e73ce-4fc7-4cba-9127-f0b5a4741950 | 5 | @Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "Код группы";
case 1:
return "Номер группы";
case 2:
return "Год поступления";
case 3:
return "Код факультета";
case 4:
return "Факультет";
default:
return null;
}
} |
a39d0260-fc6a-4bd8-a990-d24477f988f2 | 1 | public ImagePanel() {
try {
image = ImageIO.read(new File("src/snake.bmp")); // for IDE
//image = ImageIO.read(this.getClass().getResource("snake.bmp")); // for Jar'archive
} catch (IOException ex) {
System.out.print(ex);
}
} |
bf7f37c7-b06b-41e7-9997-e6c28669722a | 0 | public void mouseExited(MouseEvent e)
{
String str = "The mouse has left the Frame !";
System.out.println(str);
} |
2eeea60d-8cdd-404c-ba83-220cbd36c1ac | 1 | private void write_Compressed() {
try {
WriteHand = new BufferedWriter(new FileWriter("comp.txt"));
WriteHand.write(mydata_coded);
WriteHand.flush();
WriteHand.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} |
dd1a58ba-609c-464a-bcfe-8e54fee769bb | 2 | private String nodeText(Node node){
Node valueNode = node.getChildNodes().item(0);
if (valueNode != null && valueNode.getNodeType() == Node.TEXT_NODE){
return valueNode.getNodeValue();
}
return null;
} |
b0b6185f-c99b-4b91-8163-38bb8573a55f | 8 | public void renderBasicObjects()
{
for (BasicObject bo : basic)
{
int[] image = bo.getPixles();
for (int y = 0; y < bo.getHeight(); y++)
{
for (int x = 0; x < bo.getWidth(); x++)
{
if(x < 0 || x > width || y < 0 || y >= height )break;
if (image[x + y * bo.getWidth()] != ScreenManager.getInstance().getOmmitColor())
pixels[width * (y + bo.getY()) + (x + bo.getX())] = image[x + y * bo.getWidth()];
}
}
}
} |
4dfae0f5-acdd-4bbc-81fd-794fed167e6e | 1 | @Test
public void insertTest() {
for (int i = 1; i < 8; i++) {
System.out.println("");
printTime(testArrayListInserts(100000 * (int) Math.pow(2, i)));
printTime(testDynamicArrayInserts(100000 * (int) Math.pow(2, i)));
}
} |
f8dcd742-7378-4ea2-be35-6c7f8c6c454b | 8 | static double incompleteGammaComplement( double a, double x ) {
double ans, ax, c, yc, r, t, y, z;
double pk, pkm1, pkm2, qk, qkm1, qkm2;
if( x <= 0 || a <= 0 ) return 1.0;
if( x < 1.0 || x < a ) return 1.0 - incompleteGamma(a,x);
ax = a * Math.log(x) - x - lnGamma(a);
if( ax < -MAXLOG ) return 0.0;
ax = Math.exp(ax);
/* continued fraction */
y = 1.0 - a;
z = x + y + 1.0;
c = 0.0;
pkm2 = 1.0;
qkm2 = x;
pkm1 = x + 1.0;
qkm1 = z * x;
ans = pkm1/qkm1;
do {
c += 1.0;
y += 1.0;
z += 2.0;
yc = y * c;
pk = pkm1 * z - pkm2 * yc;
qk = qkm1 * z - qkm2 * yc;
if( qk != 0 ) {
r = pk/qk;
t = Math.abs( (ans - r)/r );
ans = r;
} else
t = 1.0;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if( Math.abs(pk) > big ) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
} while( t > MACHEP );
return ans * ax;
} |
434028a2-ff38-4053-b6c0-6a9dc3bc18e0 | 5 | public void start() {
try {
ExecutorService executor = Executors.newFixedThreadPool(numbersOfThreads);
File file = new File(outputPath);
if (!file.isDirectory()) {
file.mkdirs();
}
Calendar start = Calendar.getInstance();
for (int i = 0; i < numbersOfThreads; i++) {
MultiThreadTestCase obj = (MultiThreadTestCase) testingClass.newInstance();
obj.setMyName("id" + (i + 1));
obj.setExecutionTimes(executionTimes);
obj.setOutputPath(outputPath);
executor.execute(obj);
}
executor.shutdown();
executor.awaitTermination(1000, TimeUnit.HOURS);
Calendar end = Calendar.getInstance();
System.out.println("execution finished...");
long time = end.getTimeInMillis()-start.getTimeInMillis();
System.out.println("execution time(seconds): \t"+(time/1000D));
System.out.println("single thread execution time (seconds): \t"+(time/numbersOfThreads/1000D));
System.out.println("single process execution time (seconds): \t"+(time/numbersOfThreads/executionTimes/1000D));
varify();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
759999df-cff3-4e8d-901a-1767072c5b5d | 5 | public Agent(Simulation controller, int i, String s) {
scape = controller;
id = i;
score = 0;
encounters = 0;
average = 0;
strategy = s;
hasMoved = false;
//Agent.memory records the past 10 actions of the
//encountered agents against this agent.
//memory[agentID][0] contains the most recent encounter.
memory = new int[scape.numAgents][10];
for (int m = 0; m < memory.length; m++) {
for (int n = 0; n < memory[m].length; n++) {
memory[m][n] = 0;
}
}
//Agent.memoryOwnActions records the past 10 actions of this agent
//against encountered agents.
//memoryOwnActions[agentID][0] contains the most recent encounter.
memoryOwnActions = new int[scape.numAgents][10];
for (int m = 0; m < memoryOwnActions.length; m++) {
for (int n = 0; n < memoryOwnActions[m].length; n++) {
memoryOwnActions[m][n] = 0;
}
}
//memoryEncounters[agentID] contains the amount of encounters with this agent.
memoryEncounters = new int[scape.numAgents];
for (int n = 0; n < memoryEncounters.length; n++) {
memoryEncounters[n] = 0;
}
} |
fa3cd6d3-307d-4f43-b4e4-a63e3fd01cda | 4 | private void anecdote(Actor actor, Actor other) {
//
// Pick a random recent activity and see if the other also indulged in it.
// If the activity is similar, or was undertaken for similar reasons,
// improve relations.
// TODO: At the moment, we just compare traits. Fix later.
final Trait comp = (Trait) Rand.pickFrom(actor.traits.personality()) ;
if (comp == null) {
return ;
}
final float
levelA = actor.traits.scaleLevel(comp),
levelO = actor.traits.scaleLevel(comp),
effect = 0.5f - (Math.abs(levelA - levelO) / 1.5f) ;
final String desc = actor.traits.levelDesc(comp) ;
other.mind.incRelation(actor, effect) ;
actor.mind.incRelation(other, effect) ;
utters(actor, "It's important to be "+desc+".") ;
if (effect > 0) utters(other, "Absolutely.") ;
if (effect == 0) utters(other, "Yeah, I guess...") ;
if (effect < 0) utters(other, "No way!") ;
} |
43f86899-b173-4cf1-ad02-6d260fee26b8 | 6 | public boolean intersects(double x0, double y0, double z0, double x1, double y1, double z1) {
if (x1 <= x - xr || x0 > x + xr || y1 <= y - yr || y0 > y + yr || z1 <= z || z0 > z + zh) return false;
return true;
} |
2088df3d-72cc-4c77-93f1-74be67723cbf | 6 | @Override public void run ( ) {
if ( Core.first ) {
Core.moves = this.main.computeFirstMove ( ) ;
} else {
Core.moves = this.main.commuteNextMove ( ) ;
}
this.moves = Core.moves ;
if ( this.moves.isEmpty ( ) ) {
if ( this.main.hand.isEmpty ( ) ) {
GUI.write ( "Use the command, 'draw <character sequence>', "
+ "to add words to your hand." ) ;
}
GUI.write ( "No Words Found" ) ;
} else {
Collections.sort ( this.moves ) ;
GUI.gui.setWordList ( this.moves ) ;
Vector<Move> mcpy = new Vector<Move> ( 10 ) ;
int i = 0 ;
for ( ; i < 10 && this.moves.size ( ) > i ; i++ ) {
mcpy.add ( this.moves.get ( i ) ) ;
}
Collections.reverse ( mcpy ) ;
for ( final Move m : mcpy ) {
GUI.write ( String.format ( "%3d", i ) + ": " + m.toFullString ( ) ) ;
i-- ;
}
GUI.write ( "The scores and positions have been given. "
+ "Type 'place #' to place the word on the board." ) ;
GUI.write ( "The following are the words that have been found and, "
+ "which can be places on this board." ) ;
}
this.console.getToolkit ( ).beep ( ) ;
this.frame.setVisible ( false ) ;
this.frame.setEnabled ( false ) ;
} |
6ebc16aa-e99f-439c-8a49-1fb7e02e1f29 | 5 | private boolean marginBuildings(int x, int y, int m) {
for (int dx = x - m; dx < x + m; dx++) {
for (int dy = y - m; dy < y + m; dy++) {
if (dx > 0 && dy > 0 && buildings[dx][dy] != null) {
return true;
}
}
}
return false;
} |
fa755615-a43a-4bc5-8e9d-923e22945cc3 | 7 | public boolean compDistribution() {
bDeadline = true;
boolean bUsedNewResource = false;
double tmp = 0, rest = 0;
/* distribute tasks according to the sort */
int k;
double lastAllocation;
for (int i = 0; i < iClass; i++) {
System.out.print(iStage + "Distribution[" + i + "]");
tmp = 0;
rest = iaTask[i];
for (int j = 0; j < iSite; j++) {
if (rest != 0) {
// the first site to distribute
k = (int) dmRankResource[i][j];
if (dmAlloc[i][k] == -1) {
lastAllocation = iaCPU[j];
bUsedNewResource = true;
} else {
lastAllocation = dmAlloc[i][k];
}
tmp = dDeadline * lastAllocation / dmPrediction[i][k];
if (rest > tmp) {
dmDist[i][k] = tmp;
rest = rest - tmp;
} else {
dmDist[i][k] = rest;
rest = 0;
continue;
}
} else {
k = (int) dmRankResource[i][j];
dmDist[i][k] = 0;
}
}
/* after distribution, the deadline can not be fulfilled */
if (rest > 0) {
bDeadline = false;
return true;
}
for (int j = 0; j < iSite; j++) {
System.out.print(dmDist[i][j] + ", ");
}
System.out.println();
}
return bUsedNewResource;
} |
08fd891f-a326-4a90-a572-9103b0cc99bc | 6 | private static double[][] sortByRank(double[][] A, int aug){
int index = 0;
for(int i = 0; i < A.length-index; i++){
boolean zeroRow = true;
for(int j = 0; j<aug; j++){
if(A[i][j] != 0)
zeroRow = false;
}
if(zeroRow){
for(int k = i; k<A.length-1; k++){
for(int j = 0; j <A[0].length; j++){
double T = A[k][j];
A[k][j] =A[k+1][j];
A[k+1][j] = T;
}
}
index ++;
}
}
return A;
} //end sortByRank method |
0c0f9385-1c2f-4162-88c6-193b985489f0 | 5 | private void collectCategoryChanges(CourseModel model,
ArrayList<Change> list) {
HashSet<String> newIds = new HashSet<String>();
for (Object id : this.categories.keySet()) {
newIds.add((String) id);
}
for (DescRec rec : model.getCategories(Source.COURSERA)) {
if (!newIds.contains(rec.getId())) {
list.add(DescChange.delete(DescChange.CATEGORY, rec));
} else {
HashMap<String, Object> map = this.categories.get(rec.getId());
String newName = (String) map.get("name");
if (Change.fieldChanged(rec.getName(), newName)) {
list.add(DescChange.setName(rec, newName));
}
}
newIds.remove(rec.getId());
}
for (String id : newIds) {
HashMap<String, Object> map = this.categories.get(id);
list.add(DescChange.add(DescChange.CATEGORY, Source.COURSERA, id,
(String) map.get("name"), (String) map.get("description")));
}
} |
5a1c2269-6407-4470-bb96-80607534ef0b | 8 | public static HashMap<Long, LinkedList<Long>> readAndMapTestFile (String filePath, boolean indexByUser) throws FileNotFoundException{
HashMap<Long, LinkedList<Long>> userItemPair = new HashMap<Long, LinkedList<Long>>();
Scanner scan = new Scanner(new File(filePath));
String line = null;
//read and ignore first line (headers)
line = scan.nextLine();
do {
line = scan.nextLine();
String[] pair = line.split(",");
if(pair.length != 2){
System.err.println("Error: test file has wrong format. It must be a 2-column CSV.");
System.exit(1);
}
long item = Long.parseLong(pair[0].trim());
long user = Long.parseLong(pair[1].trim());
if(indexByUser){
if(userItemPair.containsKey(user) && !userItemPair.get(user).contains(item)){
userItemPair.get(user).add(item);
}
else{
LinkedList<Long> ll = new LinkedList<Long>();
ll.add(item);
userItemPair.put(user, ll);
}
}
else{
if(userItemPair.containsKey(item) && !userItemPair.get(item).contains(user)){
userItemPair.get(item).add(user);
}
else{
LinkedList<Long> ll = new LinkedList<Long>();
ll.add(user);
userItemPair.put(item, ll);
}
}
} while (scan.hasNext());
//sort each list
for(long element : userItemPair.keySet()){
Collections.sort(userItemPair.get(element));
}
return userItemPair;
} |
2c51ac81-6acb-47a1-9185-5f67f0566ef2 | 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 Observacion)) {
return false;
}
Observacion other = (Observacion) object;
if ((this.idObservacion == null && other.idObservacion != null) || (this.idObservacion != null && !this.idObservacion.equals(other.idObservacion))) {
return false;
}
return true;
} |
debd83ac-4bb6-4452-a948-dd60445236c9 | 4 | public static void SmithWaterman(AlignmentGraphBasic matrix)
{
int x,y;
matrix.setMatrix(0,0,0);
for(x=1;x<matrix.getMatrixXLength();x++)
{
matrix.setMatrix(0, x, Math.max(matrix.getMatrix(0, x-1)+matrix.getEffort()[0], 0));
}
for(y=1;y<matrix.getMatrixYLength();y++)
{
matrix.setMatrix(y, 0, Math.max(matrix.getMatrix(y-1, 0)+matrix.getEffort()[1], 0));
}
//Berechnung des inneren
for(y=1;y<matrix.getMatrixYLength();y++)
{
for(x=1;x<matrix.getMatrixXLength();x++)
{
matrix.setMatrix(y,x,calcSmithWaterman(y,x,matrix));
//Berechne Wert für stelle matrix[y][x]);
}
}
} |
13066ce5-3b20-4ec5-b7ac-1a744fbc9f88 | 8 | public static Measurement[] averageMeasurements(Measurement[][] toAverage) {
List<String> measurementNames = new ArrayList<String>();
for (Measurement[] measurements : toAverage) {
for (Measurement measurement : measurements) {
if (measurementNames.indexOf(measurement.getName()) < 0) {
measurementNames.add(measurement.getName());
}
}
}
GaussianEstimator[] estimators = new GaussianEstimator[measurementNames
.size()];
for (int i = 0; i < estimators.length; i++) {
estimators[i] = new GaussianEstimator();
}
for (Measurement[] measurements : toAverage) {
for (Measurement measurement : measurements) {
estimators[measurementNames.indexOf(measurement.getName())]
.addObservation(measurement.getValue(), 1.0);
}
}
List<Measurement> averagedMeasurements = new ArrayList<Measurement>();
for (int i = 0; i < measurementNames.size(); i++) {
String mName = measurementNames.get(i);
GaussianEstimator mEstimator = estimators[i];
if (mEstimator.getTotalWeightObserved() > 1.0) {
averagedMeasurements.add(new Measurement("[avg] " + mName,
mEstimator.getMean()));
averagedMeasurements.add(new Measurement("[err] " + mName,
mEstimator.getStdDev()
/ Math
.sqrt(mEstimator
.getTotalWeightObserved())));
}
}
return averagedMeasurements
.toArray(new Measurement[averagedMeasurements.size()]);
} |
946570f0-1318-4e07-8de8-fca4843c9e8d | 4 | public void writeResultForMap(OpenCellIdCell originalCell, DefaultCell chosenHeuristicCell, DefaultCell otherHeuristicCell, double error) {
try {
jg.writeObjectFieldStart("cell");
jg.writeObjectField("lon", originalCell.getCellTowerCoordinates().getX());
jg.writeObjectField("lat", originalCell.getCellTowerCoordinates().getY());
jg.writeEndObject();
jg.writeObjectFieldStart("calculatedCell");
// if(chosenHeuristicCell == null) {
//
// }
// else {
jg.writeObjectField("lon", chosenHeuristicCell.getCellTowerCoordinates().getX());
jg.writeObjectField("lat", chosenHeuristicCell.getCellTowerCoordinates().getY());
jg.writeObjectField("errorDist", error);
// }
jg.writeEndObject();
if(otherHeuristicCell != null) {
jg.writeObjectFieldStart("otherCalculatedCell");
jg.writeObjectField("lon", otherHeuristicCell.getCellTowerCoordinates().getX());
jg.writeObjectField("lat", otherHeuristicCell.getCellTowerCoordinates().getY());
jg.writeEndObject();
}
jg.writeArrayFieldStart("measurements");
for(Measurement measurement : originalCell.getMeasurements()) {
jg.writeStartObject();
jg.writeObjectField("lon", measurement.getCoordinates().getX());
jg.writeObjectField("lat", measurement.getCoordinates().getY());
jg.writeEndObject();
}
jg.writeEndArray();
iAmDoneWriting();
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
52b5ddec-2787-4096-9f46-f39e7a107806 | 6 | public void get(int key) {
HashPrinter.tryGet(key);
/** Run along the array */
int runner = 0;
int hash = (key % table.length);
while (table[hash] != null && runner < table.length) {
if (table[hash].getKey() == key) {
break;
}
runner++;
hash = ((key + runner) % table.length);
}
if (runner == table.length || table[hash].getKey() != key) {
HashPrinter.notFound(key);
} else if (table[hash].getKey() == key) {
HashPrinter.found(table, key, hash);
}
} |
306ad929-36df-4a71-b10d-ad0b7852a912 | 3 | @Override
protected Object doInBackground() throws Exception {
addPropertyChangeListener(this);
try{
if (op.equals(Operation.LOAD))aDoc.load(fis, append, this);
if (op.equals(Operation.SAVE))aDoc.save(fos, this);
} catch (Exception e){
pw.close();
this.exception = e;
e.printStackTrace();
}
return null;
} |
7719870b-2db9-43a3-b9c4-c0b9ea54db51 | 4 | @Override
public String buscarDocumentoPorEstado(String estado) {
ArrayList<Compra> geResult= new ArrayList<Compra>();
ArrayList<Compra> dbCompras = tablaCompras();
String result="";
try{
for (int i = 0; i < dbCompras.size() ; i++){
if(dbCompras.get(i).getEstado().equalsIgnoreCase(estado)){
geResult.add(dbCompras.get(i));
}
}
}catch (NullPointerException e) {
result="No existe la compra con el estado: "+estado;
}
if (geResult.size()>0){
result=imprimir(geResult);
} else {
result="No se ha encontrado ningun registro";
}
return result;
} |
c585608a-0c12-407c-825f-d6424402bcbe | 9 | public static void main(String[] args) {
// TODO Auto-generated method stub
/*for(int cnt=1;cnt<6;cnt++){
for(int cnt2=0;cnt2<cnt;cnt2++);{
System.out.println("*");
*/
int lim;
lim = 5; //ループ回数
//*が1つから増えて行くループ
for(int cnt1=0;cnt1<lim;cnt1++){
for(int cnt2=-1;cnt2<cnt1;cnt2++){
System.out.print("*");
}
System.out.println();
}
//////////////////////////////////////////////////次の文との空白
System.out.println();
//*が5つから減って行くループ
for(int cnt1=lim;cnt1>0;cnt1--){
for(int cnt2=0;cnt2<cnt1;cnt2++){
System.out.print("*");
}
System.out.println();
}
/////////////////////////////////////////////////次の文との空白
System.out.println();
//空白と*を決めた個数並べるループ
for(int cnt1 =0;cnt1<lim;cnt1++){
//ループ1・・・空白を表示する
for(int cnt2=4;cnt2>cnt1;cnt2--){
System.out.print(" ");
}
//////////////////////////////////////////奇数分表示
//cnt2を1ずらすことで描画する数を奇数に
for(int cnt2=0;cnt2<=cnt1;cnt2++){
System.out.print("*");
}
for(int cnt2=1;cnt2<=cnt1;cnt2++){
System.out.print("*");
}
//////////////////////////////////////
for(int cnt2=4;cnt2>cnt1;cnt2--){
System.out.print(" ");
}
System.out.println("");
}
} |
41f68690-230d-44af-af4b-08b41b018b22 | 2 | public final Object opt(int index) {
return (index < 0 || index >= length()) ?
null : this.myArrayList.get(index);
} |
daa0999d-a5a7-405a-817b-16268abb7ee0 | 8 | private int draw_stats(Graphics g, int i, int w, int offset) {
g.setColor(COLORS[(i+1)%COLORS.length]);
offset += 10;
g.drawString("Player "+i+": "+game.getAgent(i).getLabel(), w, offset);
int team = 0;
for (int j = 0; j < game.pgs.teams.size(); j++) {
if (game.pgs.teams.get(j).contains(i)) {
team = j;
break;
}
}
offset += 20;
g.setColor(COLORS[(1+team)%COLORS.length]);
g.drawString("Team: "+team, w, offset);
g.setColor(Color.white);
offset += 20;
g.drawString("Score: "+game.pgs.scores.get(i), w, offset);
offset += 20;
g.drawString("Resources: "+game.pgs.resources.get(i), w, offset);
offset += 20;
g.drawString("Kills: "+game.pgs.kills.get(i), w, offset);
offset += 20;
g.drawString("Deaths: "+game.pgs.deaths.get(i), w, offset);
offset += 20;
g.drawString("Units:", w, offset);
ArrayList<Integer> units = new ArrayList<Integer>();
ArrayList<Integer> buildings = new ArrayList<Integer>();
for (int j = 0; j < game.pgs.unitDefinitions.building_defs.get(i).size(); j++) {
buildings.add(0);
}
for (int j = 0; j < game.pgs.unitDefinitions.unit_defs.get(i).size(); j++) {
units.add(0);
}
for (int j = 0; j < game.pgs.armies.get(i).size(); j++) {
if (game.pgs.armies.get(i).get(j).isBuilding()) {
buildings.set(game.pgs.armies.get(i).get(j).getType(), buildings.get(game.pgs.armies.get(i).get(j).getType())+1);
} else {
units.set(game.pgs.armies.get(i).get(j).getType(), units.get(game.pgs.armies.get(i).get(j).getType())+1);
}
}
for (int j = 0; j < units.size(); j++) {
offset += 20;
g.drawString(" "+game.pgs.unitDefinitions.unit_defs.get(i).get(j).label+": "+units.get(j), w, offset);
}
offset += 20;
g.drawString("Buildings:", w, offset);
for (int j = 0; j < buildings.size(); j++) {
offset += 20;
g.drawString(" "+game.pgs.unitDefinitions.building_defs.get(i).get(j).label+": "+buildings.get(j), w, offset);
}
return offset+10;
} |
291253d3-d3d8-4b4d-ac8a-eebbcaa21e7e | 8 | protected void defineWorld(int worldType) {
world = new HashMap<Position,Tile>();
String[] layout;
if ( worldType == 1 ) {
layout = new String[] {
"...ooMooooo.....",
"..ohhoooofffoo..",
".oooooMooo...oo.",
".ooMMMoooo..oooo",
"...ofooohhoooo..",
".ofoofooooohhoo.",
"...ooo..........",
".ooooo.ooohooM..",
".ooooo.oohooof..",
"offfoooo.offoooo",
"oooooooo...ooooo",
".ooMMMoooo......",
"..ooooooffoooo..",
"....ooooooooo...",
"..ooohhoo.......",
".....ooooooooo..",
};
} else {
layout = new String[] {
"...ooo..........",
".ooooo.ooohooM..",
".ooooo.oohooof..",
"offfoooo.offoooo",
"oooooooo...ooooo",
".ooMMMoooo......",
".....ooooooooo..",
"...ooMooooo.....",
"..ohhoooofffoo..",
"...ofooohhoooo..",
".oooooMooo...oo.",
".ooMMMoooo..oooo",
".ofoofooooohhoo.",
"..ooooooffoooo..",
"....ooooooooo...",
"..ooohhoo.......",
};
}
String line;
for ( int r = 0; r < GameConstants.WORLDSIZE; r++ ) {
line = layout[r];
for ( int c = 0; c < GameConstants.WORLDSIZE; c++ ) {
char tileChar = line.charAt(c);
String type = "error";
if ( tileChar == '.' ) { type = GameConstants.OCEANS; }
if ( tileChar == 'o' ) { type = GameConstants.PLAINS; }
if ( tileChar == 'M' ) { type = GameConstants.MOUNTAINS; }
if ( tileChar == 'f' ) { type = GameConstants.FOREST; }
if ( tileChar == 'h' ) { type = GameConstants.HILLS; }
Position p = new Position(r,c);
world.put( p, new StubTile(p, type));
}
}
} |
447d5efa-0c6c-43c2-a9de-421bd07eaf6a | 4 | public static ClientSender make(String comandStr) {
RequestCommand comandInt = RequestCommand.valueOf(comandStr);
ClientSender clientSender = null;
switch (comandInt.toInt()) {
case RequestCommand.LOG_FILE:
clientSender = new LogFileStructureSender();
break;
case RequestCommand.FILE_CONTENT:
clientSender = new TailFileContentSender();
break;
case RequestCommand.SEARCH_FILE_CONTENT:
clientSender = new SearchFileContentSender();
break;
case RequestCommand.GZ_FILE:
clientSender = new GzFileStructureSender();
break;
default:
break;
}
return clientSender;
} |
fb081cea-c24c-4921-b12b-ac342196a795 | 7 | public static void startupLists() {
if (Stella.currentStartupTimePhaseP(0)) {
if (!(Stella.NIL_LIST != null)) {
Stella.NIL_LIST = new List();
}
Stella.NIL_LIST.theConsList = Stella.NIL;
}
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
Stella.SGT_STELLA_STELLA_HASH_TABLE = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("STELLA-HASH-TABLE", null, 1)));
Stella.SGT_STELLA_KEY_VALUE_MAP = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("KEY-VALUE-MAP", null, 1)));
Stella.SYM_STELLA_STARTUP_LISTS = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-LISTS", null, 0)));
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupLists.helpStartupLists1();
_StartupLists.helpStartupLists2();
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NIL-LIST LIST NULL :PUBLIC? TRUE)");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
87bf2941-e319-4163-a031-1e8dfe09c0e4 | 2 | public void update()
{
float movAmt = (float)(MOVE_SPEED * Time.getDelta());
movementVector.setY(0);
Vector3f oldPos = Transform.getCamera().getPos();
Vector3f newPos = oldPos.add(movementVector.normalized().mul(movAmt));
Vector3f collisionVector = Game.getLevel().checkCollisions(oldPos, newPos, width, width);
movementVector = movementVector.normalized().mul(collisionVector);
if(movementVector.length() > 0)
playerCamera.move(movementVector, movAmt);
//Gun movement
gunTransform.setScale(1,1,1);
gunTransform.setPosition(playerCamera.getPos().add(playerCamera.getForward().normalized().mul(0.105f)));
gunTransform.getPosition().setY(gunTransform.getPosition().getY() + GUN_OFFSET);
Vector3f playerDistance = gunTransform.getPosition().sub(Transform.getCamera().getPos());
Vector3f orientation = playerDistance.normalized();
float angle = (float)Math.toDegrees(Math.atan(orientation.getZ()/orientation.getX()));
if(orientation.getX() > 0)
angle = 180 + angle;
gunTransform.setRotation(0,angle + 90,0);
} |
b68ee499-e883-4376-b5a0-011d31001e03 | 1 | private static String extractPureNumbers(String word) {
StringBuilder sb = new StringBuilder();
Matcher m = allNumsPtn.matcher(word);
while (m.find()) {
sb.append(m.group());
// System.out.println(m.group());
}
return sb.toString();
} |
58676172-72ad-483d-ba17-1ee210cd46a1 | 3 | /* */ @EventHandler
/* */ public void onMobTarget(EntityTargetEvent event)
/* */ {
/* 422 */ if ((event.getEntity() instanceof Monster))
/* */ {
/* 424 */ if ((event.getTarget() instanceof Player))
/* */ {
/* 426 */ if (Main.getAPI().isSpectating((Player)event.getTarget()))
/* */ {
/* 428 */ event.setCancelled(true);
/* */ }
/* */ }
/* */ }
/* */ } |
4dc4429f-ea8c-4b45-92c8-9e63f5445277 | 7 | public int getBlockTextureFromSideAndMetadata(int par1, int par2)
{
return par1 != 1 && (par1 != 0 || par2 != 1 && par2 != 2) ? (par1 == 0 ? 208 : (par2 == 1 ? 229 : (par2 == 2 ? 230 : 192))) : 176;
} |
0e94e2fc-6891-43d6-8ee3-e64d316b1f4b | 7 | @Override
public void i3channelListen(MOB mob, String channel)
{
if((mob==null)||(!i3online()))
return;
if((channel==null)||(channel.length()==0))
{
mob.tell(L("You must specify a channel name listed in your INI file."));
return;
}
if(Intermud.getLocalChannel(channel).length()==0)
{
if(Intermud.registerFakeChannel(channel).length()>0)
mob.tell(L("Channel was not officially registered."));
else
mob.tell(L("Channel listen failed."));
}
final ChannelListen ck=new ChannelListen();
ck.sender_name=mob.Name();
ck.channel=channel;
ck.onoff="1";
try
{
ck.send();
}catch(final Exception e){Log.errOut("IMudClient",e);}
} |
4f0ca4f7-ba65-4120-b16a-8e46969ac056 | 8 | public boolean kingIsInCheck(int color) {
boolean check = false;
int y = kingPositions[color].y;
int x = kingPositions[color].x;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (chessBoard[i][j].color != color && !(chessBoard[i][j] instanceof Empty)) {
if (chessBoard[i][j].isLegalCapturingMove(y, x)) {
check = true;
for (Coordinate c : chessBoard[i][j].getPath(y, x)) {
if (!(chessBoard[c.y][c.x] instanceof Empty)) {
check = false;
}
}
if (check) {
return check;
}
}
}
}
}
return check;
} |
8b112869-8b05-49f6-aad3-3aa6ab6d1eda | 2 | @EventHandler(priority = EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent event){
if(plugin.isEnabled() == true){
Block block = event.getBlock();
Player player = event.getPlayer();
if(!event.isCancelled())
blockCheckQuest(player, block, "blockdestroy", 1);
}
} |
4752687e-49e1-4020-85aa-750c147e8681 | 3 | public static void main(String[] args) {
try {
String str = "\\s \"werj 9234 \\3";
System.out.println("Original: " + str);
System.out.println("Got escaped result: " + StringUtils.escapeDoubleQuotes(str));
} catch (Exception e) {
e.printStackTrace();
}
StringBuffer ex_ascii =new StringBuffer("abc&289;");
ex_ascii.append((char)0xac);
System.out.println("Original: " + ex_ascii.toString()+"|");
System.out.println("Sublisp Unicode escaped: |" + StringUtils.unicodeEscaped(ex_ascii.toString())+"|");
String tests[]={"simple","&","abc&a","@","@","sadf&whatever;sdfsd","","&u64;"};
for(int i=0;i<tests.length;i++){
try{
System.out.println("DeEscape: org: |"+tests[i]+"| deEscaped: |"+deEscapeHTMLescapedString(tests[i])+"|.");
} catch(Exception e){
e.printStackTrace();
}
}
System.exit(0);
} |
e18de856-9ebe-49b2-9395-649ddb133e9c | 8 | public void execute() {
// Initialize the matrix.
int firstSize, secondSize;
firstSize = s1.size();
secondSize = s2.size();
// Let's see if we're just being silly...
if (firstSize < 2 || secondSize < 2) {
throw new IllegalArgumentException("Oh come on, do you really need a computer to align those sequences...?");
}
// We'll use multiple matrices, because it's easier to debug our work
// if we don't throw away data. A simple optimization would be to
// just use one matrix.
matrix = new int[firstSize][secondSize];
finalScores = new int[firstSize][secondSize];
traceback = new int[firstSize][secondSize];
// Fill with comparison values.
for (int i=0; i < firstSize; i++) {
for (int j=0; j < secondSize; j++) {
matrix[i][j] = comparator.compare((Monomer)s1.get(i),(Monomer)s2.get(j));
}
}
// We've already got something interesting, and printing it out would let us
// eyeball the final solution. Now for the actual dynamic programming.
// Uncomment one of the following to dump a matrix to stdout, for debugging.
System.out.println("Original matrix:"); dumpMatrix(matrix);
// The edges are pretty easy.
for (int i=0; i < matrix.length; i++) {
finalScores[i][0] = matrix[i][0] - gapPenalty(i);
}
for (int j=1; j < matrix[0].length; j++) {
finalScores[0][j] = matrix[0][j] - gapPenalty(j);
}
// Now do the math for the interior spaces.
for (int i=1; i < matrix.length; i++) {
for (int j=1; j < matrix[0].length; j++) {
int thisScore = calculateScoreAt(i,j);
finalScores[i][j] = thisScore;
}
}
// The penalties at the other end are handled by the doTracebackAt method.
// Uncomment the following if you want more debugging.
System.out.println("Final scores (except along lower/right edges):"); dumpMatrix(finalScores);
// Now, do the traceback and find the best score.
// There will always be at least one alignment.
numberOfAlignments = 1;
// If a traceback turns up a branch, it'll increase the number of alignments.
score = doTracebackAt(29,29);
// Uncomment this to see the traceback matrix.
//dumpMatrix(traceback);
} |
90c1fbf5-2d6a-4a45-906c-f8a351c21647 | 7 | private void unknowCommand(String command) {
System.out.println("Current command is " + currentCommand);
if (currentCommand.equalsIgnoreCase("follow")) {
if (command.equals("reset")) {
currentCommand = "";
sendToUser("Server Working ... ");
} else {
this.follow(command);
}
} else if (currentCommand.equalsIgnoreCase("checkportfolio")) {
this.checkportfolio();
} else if (currentCommand.equalsIgnoreCase("buy")) {
if (command.equals("reset")) {
currentCommand = "";
sendToUser("Server Working ... ");
} else {
this.buy(command);
}
} else if (currentCommand.equalsIgnoreCase("SELL")) {
if (command.equals("reset")) {
currentCommand = "";
sendToUser("Server Working ... ");
} else {
this.sell(command);
}
} else {
currentCommand = "";
sendToUser("Invalid command");
}
} |
6b214295-d858-4ab2-9eff-fb9a0cd8fab9 | 2 | public static void main(String[] args) {
String reactomeDir = Gpr.HOME + "/snpEff/db/reactome/txt/";
String geneIdsFile = Gpr.HOME + "/snpEff/db/reactome/gene_ids/biomart_query_uniq.txt";
String gtexDir = Gpr.HOME + "/snpEff/db/GTEx";
String gtexSamples = gtexDir + "/GTEx_Analysis_Annotations_Sample_DS__Pilot_2013_01_31.txt";
String gtexData = gtexDir + "/gtex_norm.10.txt";
// Load reactome data
Timer.showStdErr("Loading reactome data");
Reactome reactome = new Reactome();
reactome.setVerbose(true);
reactome.load(reactomeDir, geneIdsFile);
// Load GTEX data
Timer.showStdErr("Loading GTEx data");
Gtex gtex = new Gtex();
gtex.setVerbose(true);
gtex.load(gtexSamples, gtexData);
reactome.simplifyEntities();
// Simulate
Timer.showStdErr("Running");
reactome.run(gtex, null);
// Save results
String file = Gpr.HOME + "/circuit.txt";
Timer.showStdErr("Saving results to '" + file + "'");
if (reactome.monitor != null) reactome.monitor.save(file);
if (reactome.monitorTrace != null) reactome.monitorTrace.save(file);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.