method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
ca54bf92-07c0-495a-923f-6b42ad15a18e | 5 | public void save() {
final ColumnMapper mapper = getColumnMapper();
final ContentValues values = new ContentValues();
final Field[] fields = Reflection.getNonStaticDeclaredFields(getClass());
for (Field field : fields) {
if (!isMultiValued(field) && !isTransient(field)) {
values.put(field.getName(), mapper.getValueFromObject(field, this));
}
}
final String tableName = getTableName();
synchronized (Lock) {
SQLiteDatabase database = getHelper().getWritableDatabase();
if (_id != null) {
database.update(tableName, values, "_id=?", new String[] { _id.toString() });
} else {
final long newId = database.insertOrThrow(tableName, null, values);
if (newId != -1) {
this._id = (int) newId;
}
}
database.close();
}
} |
dade8518-e9b5-4ac0-b674-e17e8cbf5116 | 2 | public Endereco Abrir(int idEndereco){
try{
PreparedStatement comando = banco.
getConexao().prepareStatement("SELECT * FROM enderecos WHERE id =? AND ativo = 1");
comando.setInt(1, idEndereco);
ResultSet consulta = comando.executeQuery();
comando.getConnection().commit();
Endereco tmp = null;
if(consulta.first()){
tmp = new Endereco();
tmp.setBairro(consulta.getString("bairro"));
tmp.setCep(consulta.getString("cpf"));
tmp.setCidade(consulta.getString("cidade"));
tmp.setEstado(consulta.getString("estado"));
tmp.setId(consulta.getInt("id"));
tmp.setNumero(Integer.parseInt(consulta.getString("numero")));
tmp.setRua(consulta.getString("rua"));
}
return tmp;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}
} |
6f6f0bff-361d-4c2f-85f4-b70393530b57 | 2 | protected int positionsTotal(Instrument instrument) throws JFException {
int counter = 0;
for (IOrder order : engine.getOrders(instrument))
if (order.getState() == IOrder.State.FILLED) counter++;
return counter;
} |
f63c67e1-bf13-499f-bd91-14b122fd8ea6 | 4 | private boolean setDrawing(Drawing drawing) {
boolean test = false;
if (test || m_test) {
System.out.println("GameWindow :: SetDrawing() BEGIN");
}
m_drawingControl = drawing;
if (test || m_test) {
System.out.println("GameWindow :: SetDrawing() END");
}
return true;
} |
df7812c9-3f02-4e2e-9986-723f6dafaa5d | 7 | public void updateLyricsPane(final Track t) {
if(!currentTrack.equals(t)) {
currentTrack = t;
new Thread() {
@Override
public void run() {
String artist = t.get("artist");
String title = t.get("title");
String lyrics;
if(artist.equals("DOOOOOM") && title.equals("Please Give Us All An A")) {
lyrics = "Professor Bhola, give us all A's\n";
lyrics += "Because we need to graduate!\n";
lyrics += "[awesome guitar solo]\n";
lyrics += "Professor Bhola, give us all A's\n";
lyrics += "Because we need to graduate!\n";
} else {
if (artist != null && !artist.isEmpty()
&& title != null && !title.isEmpty()) {
System.out.println(".");
lyrics = LyricsFetcher.fetchLyrics(t.get("artist"), t.get("title"));
} else {
lyrics = "[lyrics unavailable]";
}
}
Platform.runLater(new Runnable() {
String lyrics;
@Override
public void run() {
lyrics_text.setText(lyrics);
}
public Runnable init(String lyrics) {
this.lyrics = lyrics;
return this;
}
}.init(lyrics));
}
}.start();
}
} |
73770f65-3704-4f81-b230-8285019b35e3 | 7 | private void generateLevel() {
doors = new ArrayList<>();
enemies = new ArrayList<>();
collisionPosStart = new ArrayList<>();
collisionPosEnd = new ArrayList<>();
medKits = new ArrayList<>();
ArrayList<Vertex> vertices = new ArrayList<>();
ArrayList<Integer> indices = new ArrayList<>();
for(int i = 0; i < level.getWidth(); i++){
for(int j = 0; j < level.getHeight(); j++){
if((level.getPixel(i, j) & 0xFFFFFF) == 0)
continue;
float[] texCoords = calcTexCoords((level.getPixel(i, j) & 0x00FF00) >> 8);
addSpecial((level.getPixel(i, j) & 0x0000FF), i, j);
//Generate floor
addFace(indices, vertices.size(), true);
addVertices(vertices, i, j, 0, false, true, true, texCoords);
//Generate ceiling
addFace(indices, vertices.size(), false);
addVertices(vertices, i, j, 1, false, true, true, texCoords);
//Generate walls
texCoords = calcTexCoords((level.getPixel(i, j) & 0xFF0000) >> 16);
if((level.getPixel(i, j - 1) & 0xFFFFFF) == 0) {
collisionPosStart.add(new Vector2f(i * SPOT_WIDTH, j * SPOT_LENGTH));
collisionPosEnd.add(new Vector2f((i + 1) * SPOT_WIDTH, j * SPOT_LENGTH));
addFace(indices, vertices.size(), false);
addVertices(vertices, i, 0, j, true, false, true, texCoords);
}
if((level.getPixel(i, j + 1) & 0xFFFFFF) == 0) {
collisionPosStart.add(new Vector2f(i * SPOT_WIDTH, (j + 1) * SPOT_LENGTH));
collisionPosEnd.add(new Vector2f((i + 1) * SPOT_WIDTH, (j + 1) * SPOT_LENGTH));
addFace(indices, vertices.size(), true);
addVertices(vertices, i, 0, (j + 1), true, false, true, texCoords);
}
if((level.getPixel(i - 1, j) & 0xFFFFFF) == 0) {
collisionPosStart.add(new Vector2f(i * SPOT_WIDTH, j * SPOT_LENGTH));
collisionPosEnd.add(new Vector2f(i * SPOT_WIDTH, (j + 1) * SPOT_LENGTH));
addFace(indices, vertices.size(), true);
addVertices(vertices, 0, j, i, true, true, false, texCoords);
}
if((level.getPixel(i + 1, j) & 0xFFFFFF) == 0) {
collisionPosStart.add(new Vector2f((i + 1) * SPOT_WIDTH, j * SPOT_LENGTH));
collisionPosEnd.add(new Vector2f((i + 1) * SPOT_WIDTH, (j + 1) * SPOT_LENGTH));
addFace(indices, vertices.size(), false);
addVertices(vertices, 0, j, (i + 1), true, true, false, texCoords);
}
}
}
Vertex[] vertArray = new Vertex[vertices.size()];
Integer[] intArray = new Integer[indices.size()];
vertices.toArray(vertArray);
indices.toArray(intArray);
mesh = new Mesh(vertArray, Util.toIntArray(intArray));
} |
18938b87-2efb-410c-b74a-a9c40368539e | 8 | public Set<Map.Entry<Float,Float>> entrySet() {
return new AbstractSet<Map.Entry<Float,Float>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TFloatFloatMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TFloatFloatMapDecorator.this.containsKey(k)
&& TFloatFloatMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Float,Float>> iterator() {
return new Iterator<Map.Entry<Float,Float>>() {
private final TFloatFloatIterator it = _map.iterator();
public Map.Entry<Float,Float> next() {
it.advance();
float ik = it.key();
final Float key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
float iv = it.value();
final Float v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Float,Float>() {
private Float val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Float getKey() {
return key;
}
public Float getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Float setValue( Float value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Float,Float> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Float key = ( ( Map.Entry<Float,Float> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Float, Float>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TFloatFloatMapDecorator.this.clear();
}
};
} |
cacac16a-4537-465f-94c0-7f14726146b3 | 0 | private Printer(){} |
87832dca-869f-4e34-9884-f2f8ef7a51d9 | 7 | private void rec(int as, int bs, int rets, int n){
if(n<=SMALL){
for(int i=0;i<2*n;++i) t[rets + i] = 0;
for(int i=0;i<n;++i)
for(int j=0;j<n;++j) t[rets + i+j] += t[as + i] * t[bs + j];
return;
}
int ar = as;
int al = as + n/2;
int br = bs;
int bl = bs + n/2;
int asum = rets + n*5;
int bsum = rets + n*5 + n/2;
int x1 = rets;
int x2 = rets + n;
int x3 = rets + n*2;
for(int i=0;i<n/2;++i){
t[asum + i] = t[al + i] + t[ar + i];
t[bsum + i] = t[bl + i] + t[br + i];
}
rec(ar, br, x1, n / 2);
rec(al, bl, x2, n / 2);
rec(asum, bsum, x3, n / 2);
for(int i=0;i<n;++i) t[x3 + i] -= t[x1 + i] + t[x2 + i];
for(int i=0;i<n;++i) t[rets + i+n/2] += t[x3 + i];
} |
2a5321a4-9da8-4649-a87f-13b2b898daa4 | 7 | public String toString() {
StringBuffer result;
int i;
int n;
boolean found;
result = new StringBuffer();
// title
result.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
result.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n");
// model
if (m_ActualClusterer != null) {
// output clusterer
result.append(m_ActualClusterer + "\n");
// clusters to classes
result.append("Clusters to classes mapping:\n");
for (i = 0; i < m_ClustersToClasses.length - 1; i++) {
result.append(" " + (i+1) + ". Cluster: ");
if (m_ClustersToClasses[i] < 0)
result.append("no class");
else
result.append(
m_OriginalHeader.classAttribute().value((int) m_ClustersToClasses[i])
+ " (" + ((int) m_ClustersToClasses[i] + 1) + ")");
result.append("\n");
}
result.append("\n");
// classes to clusters
result.append("Classes to clusters mapping:\n");
for (i = 0; i < m_OriginalHeader.numClasses(); i++) {
result.append(
" " + (i+1) + ". Class ("
+ m_OriginalHeader.classAttribute().value(i) + "): ");
found = false;
for (n = 0; n < m_ClustersToClasses.length - 1; n++) {
if (((int) m_ClustersToClasses[n]) == i) {
found = true;
result.append((n+1) + ". Cluster");
break;
}
}
if (!found)
result.append("no cluster");
result.append("\n");
}
result.append("\n");
}
else {
result.append("no model built yet\n");
}
return result.toString();
} |
f40beef8-e7f3-4efc-aee3-c62ff802a6a5 | 0 | public JTextField getjTextFieldLieux() {
return jTextFieldLieux;
} |
cd5194aa-99b3-4069-9b3e-0e07504a5e39 | 9 | public void render() {
bg.bind();
Molybdenum.GLQuad(0, 0, Display.getWidth(), Display.getHeight());
Molybdenum.setAwtColor(Color.WHITE);
Molybdenum.getText().drawStringS("Molybdenum | Properties", 16, 16, Text.LEFT, 3f,4);
Molybdenum.getText().drawStringS("Press enter to confirm a choice!", 64, 64, Text.LEFT, 2f,4);
Molybdenum.setAwtColor(Color.DARK_GRAY);
Molybdenum.getText().drawString("Version "+Molybdenum.VERSION, 0, Display.getHeight()-16, Text.LEFT, 1);
//Render all selections
Molybdenum.setAwtColor(Color.WHITE);
for(int i=0;i<items.length;i++){
String current = items[i];
int xset = 0;
if(i==item){
current = "> "+current;
xset = (int)(16*2);
}
if(i==0){
current+=" "+cUp;
}
if(i==1){
current+=" "+cDown;
}
if(i==2){
current+=" "+cLeft;
}
if(i==3){
current+=" "+cRight;
}
if(i==4){
current+=" "+cPickup;
}
if(i==5){
current+=" "+cInv;
}
if(i==6){
current+=" "+cEat;
}
Molybdenum.getText().drawStringS(current, 128-xset, 128+(32*i), Text.LEFT, 2f,4);
}
} |
e41084f7-182e-43e5-8cd1-19e2f7e0b810 | 9 | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if(sender instanceof ConsoleCommandSender)
{
getLogger().info("Console cannot use this plugin.");
return true;
}
if(args.length == 0)
return true;
if(p.has(sender, cmd, Arrays.copyOfRange(args, 0, 1), false))
{
if(cmd.getName().equalsIgnoreCase("owhquests"))
{
if(args.length > 1)
{
if(args[0].equalsIgnoreCase("addquest"))
{
return createQuest((Player)sender, Arrays.copyOfRange(args, 1, args.length));
}
}
else if(args.length > 0)
{
if(args[0].equalsIgnoreCase("book"))
{
this.toggleQuestBook((Player)sender);
return true;
}
if(args[0].equalsIgnoreCase("compass"))
{
this.toggleCompass((Player)sender);
return true;
}
}
}
}
return false;
} |
b98374dd-8cbb-4878-a558-af3e7accc015 | 0 | public String getName() {
return Name;
} |
43d5f7e9-d44b-4127-9f16-c6b143289fde | 2 | @Override
public void performUseAction(Player user, UI ui) {
Location current = user.getCurrentLoc();
for (Item item : current.getItems())
{
if (item instanceof BasiliskItem)
{
current.removeItem(item);
ui.display("A giant duck swoops through a broken window, into the hall, and sings the \"quack quack I'm a duck\" song until the basilisk dies of boredom and disgust.");
}
}
} |
943f52b3-ecac-46e3-9307-f348c1450d22 | 7 | @EventHandler
public void GhastResistance(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Ghast.Resistance.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Fireball) {
Fireball a = (Fireball) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getGhastConfig().getBoolean("Ghast.Resistance.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, plugin.getGhastConfig().getInt("Ghast.Resistance.Time"), plugin.getGhastConfig().getInt("Ghast.Resitance.Power")));
}
}
} |
c840d965-ac8b-4bf3-b79a-bb4bc16c2f5d | 7 | double gradCorrect(double g, double eta)
{
int nPos = sequence.length();
int y = sequence.getY(0);
double[] grad = new double[]{g};
updateU(grad, 0, y, 1, eta);
double sum = u[0][y];
for (int pos = 1; pos < nPos; ++pos)
{
int lasty = y;
y = sequence.getY(pos);
if (y >= 0 && lasty >= 0)
{
sum += b[pos-1][y][lasty];
}
if (y >= 0)
{
sum += u[pos][y];
}
if (y >= 0 && lasty >= 0)
{
updateB(grad, pos - 1, lasty, y, 1, eta);
}
if (y >= 0)
{
updateU(grad, pos, y, 1, eta);
}
}
return sum;
} |
9ffd0e43-7d3c-4781-a3f8-399c8e8e7095 | 6 | public EnigmaMachine(int r1, int r2, int r3, int pos1, int pos2, int pos3, String p1, String p2, String p3){
reflector = new Reflector();
if(pos1 < 26 && pos2 < 26 && pos3 < 26){
rotor1 = new Rotor(r1, pos1, null);
rotor2 = new Rotor(r2, pos2, rotor1);
rotor3 = new Rotor(r3, pos3, rotor2);
}
if(p1.length() == 2 && p2.length() == 2 && p3.length() == 2){
steckers.addStecker(p1.charAt(0) - 'a', p1.charAt(1) - 'a');
steckers.addStecker(p2.charAt(0) - 'a', p2.charAt(1) - 'a');
steckers.addStecker(p3.charAt(0) - 'a', p3.charAt(1) - 'a');
}
} |
ced57f16-f381-40ce-8e43-c5a95cea13e8 | 3 | public boolean suurempiKuin(Siirto toinen){
if (this.arvo > toinen.arvo){
return true;
} else if (this.arvo < toinen.arvo){
return false;
} else {
// jos siirroilla on sama arvo, priorisoidaan syntyneiden rivien mukaan
if (this.rivit > toinen.rivit){
return true;
} else {
return false;
}
}
} |
3322dcfb-36cc-4f24-b5b0-a74c8a95cfc9 | 5 | public void calculateLoS()
{
lineOfSight.reset();
int Xx;
int Yy;
int d;
int dr;
int dx;
int dy;
boolean yes;
int resolution = 18;
for (int i = 0; i < resolution; i++)
{
Xx = (int)world.x-world.viewX;
Yy = (int)world.y-World.head-world.viewY;
yes = true;
d = 0;
dr = i*(360/resolution);
dx = (int)world.lengthdir_x(8, dr);
dy = (int)world.lengthdir_y(8, dr);
while (yes)
{
d++;
Xx+=dx;
Yy+=dy;
if (world.isSolid(Xx+world.viewX, Yy+world.viewY))
{
lineOfSight.addPoint(Xx, Yy);
yes = false;
}
if (d>=40)
{
lineOfSight.addPoint(Xx, Yy);
yes = false;
}
}
}
hideFromMe.reset();
if (!world.dead)
{
//cantSee = new RadialGradientPaint(world.x-world.viewX,world.y-world.viewY,250f,new float[]{0f,1f},new Color[]{new Color(0,0,0,0),new Color(0,0,0,255)});
Area swag = new Area(lineOfSight);
hideFromMe.add(box);
hideFromMe.subtract(swag);
}
} |
532e24a8-3873-4ab7-a21b-920f920799de | 0 | private static void help() {
System.out.println("The allowed commands are:");
System.out.println(" n/north");
System.out.println(" s/south");
System.out.println(" e/east");
System.out.println(" w/west");
System.out.println(" h/help");
System.out.println(" f/fossil (check for fossils)");
System.out.println(" t/take (to take items where prompted)");
System.out.println(" b/buy (buying standard items in the Magic Shoppe only)");
System.out.println(" s/shop (for buying special items in the Magic Shoppe only)");
System.out.println(" m/map (to use the map once you have obtained it)");
System.out.println(" q/quit");
} |
86581b0a-bd89-463c-9ac7-e3dec0e0bd24 | 3 | public void preencherTabela() throws Exception
{
ArrayList<String> colunas = new ArrayList<String>();
colunas.add("id");
colunas.add("titulo");
colunas.add("orientador");
colunas.add("pesquisadorResponsavel");
colunas.add("colaboradores");
colunas.add("anoSubmissao");
colunas.add("tempoDuracao");
colunas.add("tipo");
colunas.add("qualificacao");
colunas.add("impactoPesquisa");
colunas.add("gerouPatente");
colunas.add("status");
colunas.add("resultado");
colunas.add("instituicaoSubmissao");
colunas.add("fonteFinanciamento");
colunas.add("areaConhecimentoCNPq");
colunas.add("palavrasChave");
colunas.add("instituicoesCooperadoras");
colunas.add("locais");
colunas.add("resumo");
Object linhas[][] = new Object[list.size()][];
int i = 0;
for (Pesquisa pesquisa : list)
{
linhas[i] = formatoTabela(pesquisa);
i++;
}
view.getTabela().setModel(
new DefaultTableModel(linhas, colunas.toArray()));
if (view.getOpcoes().getModel().getSize() == 0)
view.getOpcoes().setModel(
new DefaultComboBoxModel(colunas.toArray()));
for (int x = 0; x < view.getTabela().getColumnCount(); x++)
{
String columnName = view.getTabela().getColumnName(x);
TableColumn col = view.getTabela().getColumnModel().getColumn(x);
col.setMinWidth(new JLabel(columnName).getPreferredSize().width + 10);
}
} |
7cfecec2-9827-4dc3-96f6-086656261c5d | 6 | public void printResultTable(String queryString) {
String query = queryString;
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
// printColTypes(rsmd);
// System.out.println();
int numberOfColumns = rsmd.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print("\t");
String columnName = rsmd.getColumnName(i);
System.out.print(columnName);
}
System.out.println();
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print("\t");
String columnValue = rs.getString(i);
System.out.print(columnValue);
}
System.out.println();
}
st.close();
} catch (SQLException e) {
System.out.println("Something is wrong");
e.printStackTrace();
}
} |
6ba3a778-bd39-4b12-8a80-122526525598 | 7 | public static char[][] generate_bifid_square(String keyword)
{
boolean[] alpha=new boolean[26];
char[][] square=new char[5][5];
int cur_row=0;
int cur_col=0;
//write the keyword to the square in a clockwise spiral
for(char c:keyword.toLowerCase().toCharArray())
{
if(c=='j')
{
c='i';
//index='i'-'a';
}
int index=c-'a';
if(!alpha[index])
{
square[cur_row][cur_col]=(char)(c+'A'-'a');
//spiral
alpha[index]=true;
//modify cur_row,cur_col
Pair<Integer> next_pos=Generic_Func.traverse_spiral(cur_row, cur_col, 5);
cur_row=next_pos.get_first();
cur_col=next_pos.get_second();
}
}
for(int i=0;i<26;i++)
{
if (i==9 || alpha[i]==true)
continue;
else if(!alpha[i])
{
square[cur_row][cur_col]=(char)('A'+i);
//spiral
alpha[i]=true;
//modify cur_row,cur_col
Pair<Integer> next_pos=Generic_Func.traverse_spiral(cur_row, cur_col, 5);
cur_row=next_pos.get_first();
cur_col=next_pos.get_second();
}
}
return square;
} |
fdf36bb3-a9c5-4db7-8d97-a71362b8f463 | 7 | private JPanel getInstallationPanel(final InstallationWorker installationWorker){
JPanel installationPanel = new JPanel();
installationPanel.setBackground(Color.WHITE);
final JProgressBar installationDirectoryProgress = new JProgressBar();
// TODO: Test this width in different OS
installationDirectoryProgress.setPreferredSize(new Dimension(400,15));
installationDirectoryProgress.setToolTipText("Preparing for the installation...");
installationDirectoryProgress.setStringPainted(true);
installationDirectoryProgress.setBackground(Color.WHITE);
userActionPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
// Provide the installation property thread
installationWorker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent event) {
String propertyName = event.getPropertyName();
if(propertyName.equalsIgnoreCase("progress")){
installationDirectoryProgress.setIndeterminate(false);
installationDirectoryProgress.setValue((Integer) event.getNewValue());
// Update the Tool Tip dynamically when mouse is not in motion
installationDirectoryProgress.setToolTipText("Progress: " + (event.getNewValue()) + "%");
InstallerUtils.updateToolTipMessageDynamically(installationDirectoryProgress);
}
else if(propertyName.equalsIgnoreCase("state")){
if(event.getNewValue() instanceof SwingWorker.StateValue){
switch ((SwingWorker.StateValue) event.getNewValue()){
case DONE:
// Hide the progress bar
installationDirectoryProgress.setVisible(false);
installationDirectoryProgress.setToolTipText(null);
InstallerUtils.updateToolTipMessageDynamically(installationDirectoryProgress);
// If the installation is
if(!installationWorker.isCancelled()){
// At this point the installation has been complete successfully
isInstallationCompleted.set(true);
// Don't allow the user to go backwards but automatically go to the Complete message
executeNextState();
}
break;
case STARTED:
case PENDING:
installationDirectoryProgress.setVisible(true);
installationDirectoryProgress.setIndeterminate(true);
break;
}
}
}
}
});
// Add panels where they belong
backNextCancelPanel.add(installationDirectoryProgress,0);
return installationPanel;
} |
2deddf68-c2e3-46d5-89f9-e3523e5f4842 | 4 | public void findMostValuableCombination(int itemIndex, int price, int weight) {
if (weight <= maxWeight && price > bestFoundPrice) {
this.bestFoundPrice = price;
this.bestFoundWeight = weight;
bestSet = Arrays.copyOf(tempSet, tempSet.length);
}
int nextItemIndex = itemIndex + 1;
if (promising(itemIndex) && nextItemIndex < availableItems.length) {
Item nextItem = availableItems[nextItemIndex];
tempSet[nextItemIndex] = nextItem;
findMostValuableCombination(nextItemIndex, price + nextItem.getPrice(), weight + nextItem.getWeight());
tempSet[nextItemIndex] = null;
findMostValuableCombination(nextItemIndex, price, weight);
}
} |
d8cd2893-59bd-4135-8cde-ec8cfb2a64d6 | 6 | public void loadHighScores() throws IOException, FreeColException {
highScores = new ArrayList<HighScore>();
File hsf = FreeColDirectories.getHighScoreFile();
if (!hsf.exists()) return;
XMLInputFactory xif = XMLInputFactory.newInstance();
FileInputStream fis = null;
try {
fis = new FileInputStream(hsf);
XMLStreamReader xsr = xif.createXMLStreamReader(fis, "UTF-8");
xsr.nextTag();
while (xsr.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (xsr.getLocalName().equals("highScore")) {
highScores.add(new HighScore(xsr));
}
}
xsr.close();
Collections.sort(highScores, highScoreComparator);
} catch (XMLStreamException e) {
throw new IOException("XMLStreamException: " + e.getMessage());
} catch (Exception e) {
throw new IOException("Exception: " + e.getMessage());
} finally {
if (fis != null) fis.close();
}
} |
c86e828b-f68a-4c42-b816-b3020671c57c | 0 | public static void main(String[] args) {
List<String> list = new ArrayList<String>(
Arrays.asList("cat", "dog", "horse")
);
System.out.println(list);
String item = list.get(1);
System.out.println(item);
boolean contains = list.contains(item);
System.out.println(contains);
int index = list.indexOf(item);
System.out.println(index);
list.remove(item);
// list.remove("dog");
System.out.println(list);
list.add(1, new String("new_dog"));
System.out.println(list);
List<String> subList = list.subList(1, 3);
System.out.println(subList);
list.removeAll(subList);
System.out.println(list);
list.clear();
System.out.println(list);
} |
ddfdd96f-d008-44f5-8018-f6478eb97bcd | 5 | public static void main(String[] args){
final int N = 10;
final int[] values = new int[N];
for (int i = 0; i < N; i++) values[i] = 0;
final Frame frame = new Frame("Random test");
Canvas canvas = new Canvas(){
public void paint(Graphics g){
g.setColor(new Color(255,255,255));
g.fillRect(0,0,getWidth(),getHeight());
}
public void update(Graphics g){
int max = 0;
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
for (int i = 0; i < 1000; i++) values[(int)Math.round(Math.floor(Random.getGaussian(0, N)))] += 1;
for (int i = 0; i < N; i++) if (max < values[i]) max = values[i];
g.setColor(Color.BLACK);
for (int i = 0; i < N; i++){
g.fillRect(i * this.getWidth() / N, this.getHeight() - values[i] * this.getHeight() / max,
this.getWidth() / N, values[i] * this.getHeight() / max);
}
}
};
frame.add(canvas);
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
((Canvas) e.getSource()).repaint();
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
frame.setSize(800, 500);
frame.setVisible(true);
canvas.repaint();
} |
b033f1ac-1580-480a-9c8b-c71e66a69dc0 | 0 | ThreadDemo(String str) {
t = new Thread(this, str);
// this will call run() function
t.start();
} |
d22411f8-6f71-4197-817f-6967507957ae | 7 | private void makeConnection(ArrayList<String> connection)
{
// Check the type of gate and call the appropriate function
if (connection.get(0).equals("INVERTER"))
createInverter(connection.get(1), connection.get(2));
else if (connection.get(0).equals("AND"))
createAnd(connection.get(1), connection.get(2), connection.get(3));
else if (connection.get(0).equals("OR"))
createOr(connection.get(1), connection.get(2), connection.get(3));
else if (connection.get(0).equals("JK"))
createJK(connection.get(1), connection.get(2), connection.get(3));
else if (connection.get(0).equals("SR"))
createSR(connection.get(1), connection.get(2), connection.get(3));
else if (connection.get(0).equals("T"))
createT(connection.get(1), connection.get(2));
else if (connection.get(0).equals("D"))
createD(connection.get(1), connection.get(2));
} |
ffa0d44a-e812-424a-b575-e734175f1ae7 | 0 | public void setSootConfig(IInfoflowConfig config) {
this.sootConfig = config;
} |
dd297eaf-7226-4f12-9700-41238a4ddbca | 9 | private void onSessionClosed() {
if (this.isSendingFile) {
if (this.exceptionOccurred || this.closedByRemote) {
this.finishSendingFile(false);
this.fileSendingEventHandler.onSendingFailed(this.sendingFile);
}
} else if (this.isReceivingFile) {
if (this.exceptionOccurred || this.closedByRemote) {
this.finishReceivingFile(false);
this.fileReceivingEventHandler.onReceivingFailed(this.receivingFile, GlobalUtil.OTHE_RREASON);
}
} else {
if (this.fileSendingCancelled) {
this.finishSendingFile(false);
this.fileSendingEventHandler.onSendingCancelled(this.sendingFile);
}
}
if (this.closedByRemote) {
this.onSessionClosedByRemote();
} else if (this.exceptionOccurred) {
this.onSessionClosedByException();
} else {
this.onSessionClosedByLocal();
}
} |
90ab60e3-0104-4006-b41c-8750eb56a1ac | 7 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.out=response.getWriter();
PrintWriter out=response.getWriter();
String message=request.getParameter("msgtxt");String pnumber=request.getParameter("da");String time=request.getParameter("dtime");
String fromNumber=request.getParameter("oa");String userId=request.getParameter("userid");
Date inDate=getTimeFromString(time);Date outDate=new Date();
if(pnumber==null||pnumber=="" || pnumber==" " || inDate==null){
out.println("Status=1");
return;
}
MessageHandler mHandler=new MessageHandler(message);
IMessage messageType=mHandler.getMessageFormat();
if(!(messageType.getToContinue())){
mHandler.sendSMS(message,outDate, pnumber,mHandler.getErrorMessage(messageType),defaultLanguage);
}
if(messageType==IMessage.GET)
handleGet(mHandler,pnumber,message, inDate);
else if(messageType==IMessage.ID)
handleID(mHandler,pnumber,message, outDate);
out.println("Status=0");
} |
8c157ab1-d1ce-4dab-b740-428253afa583 | 1 | private void doLaunchButton() {
launchButton.setEnabled(false);
if (frame == null) {
frame = new Pentominos("Pentominos",8,8,true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener( new WindowAdapter() {
public void windowClosed(WindowEvent evt) {
launchButton.setText("Launch Pentominos");
launchButton.setEnabled(true);
frame = null;
}
public void windowOpened(WindowEvent evt) {
launchButton.setText("Close Pentominos");
launchButton.setEnabled(true);
}
});
frame.setVisible(true);
}
else {
frame.dispose();
}
} |
843ae99b-a94f-4582-bbcd-af384526c2a3 | 0 | public Coffee() {
this.setName("Coffee");
this.setPrice(new BigDecimal(10));
} |
930186b3-589a-44b9-bae2-666a7df1f2b3 | 6 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=iso-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
if (_jspx_meth_html_html_0(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
1ba6240c-febd-4acd-8828-166003de7536 | 0 | @Override
public String getDesc() {
return "DarknessJupitel";
} |
60722fd4-4d43-4576-8f15-945cd97fbadd | 6 | public static boolean renameTo(File file1, File file2) throws IOException {
if (!file1.exists()){
throw new IOException(file1.getAbsolutePath()+" does not exist");}
/// That's right, I can't just rename the file, i need to move and delete
if (isWindows()){
File temp = new File(file2.getAbsoluteFile() +"."+new Random().nextInt()+".backup");
if (temp.exists()){
temp.delete();}
if (file2.exists()){
file2.renameTo(temp);
file2.delete();
}
if (!file1.renameTo(file2)){
throw new IOException(temp.getAbsolutePath() +" could not be renamed to " + file2.getAbsolutePath());
} else {
temp.delete();
}
} else {
if (!file1.renameTo(file2)){
throw new IOException(file1.getAbsolutePath() +" could not be renamed to " + file2.getAbsolutePath());
}
}
return true;
} |
ed47272a-9a23-4560-9d90-ea4e2cb235b1 | 8 | private void addMarker(final MarkerTile markerTile) {
add(markerTile);
markerTile.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Position huffPosition;
board.removeMarkers();
AbstractPlay play= markerTile.getRelatedPlay();
play.execute();
log.setMessage(play.toString());//aggiorna log
if (play instanceof Capture)
turnChanger.eatIncrement();
FactoryOfPlays factory = new FactoryOfCapturingsForPiece(play.getDestination(), board);
boolean flag = true;
if (play instanceof Capture && !factory.isEmpty()){
for (AbstractPlay p : factory)
board.setMarker(p);
flag = false;
}
else {
turnChanger.next();
huffPosition = turnChanger.getHuffPosition();
if (huffPosition != null)
log.setMessage("Huff in " + huffPosition);
getContentPane().removeAll();
invalidate();
showBoard(true);
validate();
if(turnChanger.gameOver()){
flag=false;
new GameEnding(!turnChanger.getTurn(),Game.this).setVisible(true);
log.setMessage("GAME OVER");
}
else {
cpuTurn();
turnChanger.next();
huffPosition = turnChanger.getHuffPosition();
if (huffPosition != null)
log.setMessage("Huff in " + huffPosition);
if(turnChanger.gameOver()){
new GameEnding(!turnChanger.getTurn(),Game.this).setVisible(true);
log.setMessage("GAME OVER");
}
}
}
getContentPane().removeAll();
invalidate();
showBoard(flag);
validate();
}
});
} |
e6c00b63-d747-4b44-bce8-568e1eaf5671 | 3 | public static void updateCarte(Carte carte) {
PreparedStatement stat;
try {
stat = ConnexionDB.getConnection().prepareStatement("select * from carte where id_carte=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
stat.setInt(1, carte.getId_carte());
ResultSet res = stat.executeQuery();
if (res.next()) {
res.updateString("serialNumber", carte.getSerialNumber());
res.updateRow();
}
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} |
96d2c9cb-9102-456d-9921-eafbbc25ffa1 | 9 | @Override
public void actionPerformed(ActionEvent e)
{
String event = e.getActionCommand();
if(event.equals("Add item"))
{
// get description of the item
String description;
do
{
description = JOptionPane.showInputDialog(null, "Description of the item: ", "Add an item", JOptionPane.QUESTION_MESSAGE);
if(description == null)
break;
}
while(description.equals(""));
if(description != null)
{
// set price of the item
BigDecimal price = new BigDecimal("0.00");
boolean valid = true;
do
{
valid = true;
try
{
price = new BigDecimal(JOptionPane.showInputDialog(null, "Price of the item: ", "Add an item", JOptionPane.QUESTION_MESSAGE));
}
catch(NullPointerException npe)
{
break;
}
catch(NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Incorrect value!", "Error", JOptionPane.ERROR_MESSAGE);
valid = false;
}
}
while(valid == false);
if(price.compareTo(new BigDecimal("0.00")) > 0) // has to be greater than 0.00
{
itemsList.add(new GeneralItem(price, description)); // add an item
items.save(); // save
tab.updateList(); // update list of items
}
}
}
else if(event.equals("Remove item"))
{
itemsList.remove(tab.getListPosition()); // remove an item
items.save(); // save
tab.updateList(); // update list of items
}
} |
ebea42f8-c3c8-4c06-8cb2-d2dbe26a177c | 2 | public static void checkAutoBroadcastMessagesYAML() {
File file = new File(path + "AutoBroadcast/messages.yml");
if(!file.exists()) {
try {
file.createNewFile();
FileConfiguration f = YamlConfiguration.loadConfiguration(file);
List<String> messages = new ArrayList<String>();
messages.add("&lThis is the first message!");
messages.add("&dSweet! The second message was shown!");
messages.add("&6Edit in the config!");
f.set("Messages", messages);
f.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
a0432d65-ec91-4b50-9010-5b30534e9550 | 6 | public static void swapElements(Vector someVector, int indexOne, int indexTwo) {
// size is useful
int size = someVector.size() ;
// validate parameters
// also leave in identity case
if ( (someVector == null) ||
(indexOne < 0) || (indexOne >= size)||
(indexTwo < 0) || (indexTwo >= size)||
(indexOne == indexTwo) )
{
return ;
} // end if
// grab element one
Object elementOne = someVector.get(indexOne) ;
// set element two in its place
someVector.set(indexOne, someVector.get(indexTwo)) ;
// set it in element two's place
someVector.set(indexTwo, elementOne) ;
// done
return ;
} // end method swapElements |
fdb2faeb-e8b6-464e-902d-62004cec27a3 | 3 | public MeetingInvite getMeetingInviteByUsernameAndMeetingID(int meetingInviteID, String username){
for(MeetingInvite meetingInvite : meetingInvites){
if(meetingInviteID == meetingInvite.getMeetingID() && username.equals(meetingInvite.getUsername())) return meetingInvite;
}
return null;
} |
fabc44fc-9cc0-46f2-8bb1-97d312a30fd0 | 0 | public void removeOutlinerDocumentListener(DocumentListener l) {
outlinerDocumentListeners.remove(l);
} |
bc4185ca-4504-421e-94d4-53b41e69321b | 5 | @Override
public boolean equals(Object other) {
boolean isEqual = false;
if (other == this) {
isEqual = true;
} else if (other != null && other.getClass() == this.getClass()) {
Coordinate otherCoord = (Coordinate) other;
isEqual = otherCoord.x == this.x && otherCoord.y == this.y &&
otherCoord.z == this.z;
}
return isEqual;
} |
1f96a7c6-7e2a-4b2c-a7fa-a67981e87d8f | 1 | public void onRoundChanged(int round, int maxRound)
{
String text = INIT_TEXT + round;
if (maxRound != 0)
text += ADDITIONAL_OF_TEXT + maxRound;
setText(text);
} |
eac13827-5a0a-465b-aa3a-00d0fd0080c6 | 0 | @Test
public void test_movement() throws OutOfBoardException{
assertNotNull(pawn);
//Four direction
Direction dirDown = Direction.Down;
Direction dirUp = Direction.Up;
Direction dirRight = Direction.Right;
Direction dirLeft = Direction.Left;
when(board.getXSize()).thenReturn(4);
when(board.getYSize()).thenReturn(4);
pawn.move(dirDown);
assertEquals(pawn.getX(), posX);
assertEquals(pawn.getY(), posY-1);
pawn.move(dirUp);
assertEquals(pawn.getX(), posX);
assertEquals(pawn.getY(), posY);
pawn.move(dirRight);
assertEquals(pawn.getX(), posX+1);
assertEquals(pawn.getY(), posY);
pawn.move(dirLeft);
assertEquals(pawn.getX(), posX);
assertEquals(pawn.getY(), posY);
} |
fffd9b01-82f6-4dff-818a-488ac2874e0a | 8 | public void useIt(){
panel.player.equipment.remove(this);
switch(this.itemType){
case(1):
if(panel.player.energy <100){
int diff = (int) (100 - panel.player.energy);
if(diff > healthPts){
panel.player.energy += healthPts;
panel.actionMessages.add(new ActionMessage(panel,"Got " +healthPts+" HP"));
}else{
panel.player.energy += diff;
panel.actionMessages.add(new ActionMessage(panel,"Got " +diff+" HP"));
}
}
break;
case(3):
if(panel.player.energy <100){
int diff = (int) (100 - panel.player.energy);
if(diff > healthPts){
panel.player.energy += healthPts;
panel.actionMessages.add(new ActionMessage(panel,"Got " +healthPts+" HP"));
}else{
panel.player.energy += diff;
panel.actionMessages.add(new ActionMessage(panel,"Got " +diff+" HP"));
}
}
break;
case(4):
panel.player.cash += money;
panel.actionMessages.add(new ActionMessage(panel,"Got " +money+"$"));
break;
case(5):
panel.player.cash += money;
panel.actionMessages.add(new ActionMessage(panel,"Got " +money+"$"));
break;
}
} |
c90658ee-78fd-485d-89a1-adc08cd0a77d | 5 | public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (handledElements.contains(qName) && parentElement.equals(ROOT_ELEMENT)) {
currentElement = qName;
}
if (qName.equals(TRANSACTIONS_ELEMENT)) {
parentElement = TRANSACTIONS_ELEMENT;
}
if (qName.equals("transaction")) {
currentElement = "transaction";
xmlTransaction = new StringBuffer();
}
if (currentElement.equals("transaction")) {
xmlTransaction.append("<" + qName + ">");
}
} |
01768b29-ae4c-49c1-a5ac-6796dc538863 | 6 | public void capturegroup (int i, int j, int c, Node n)
// Used by capture to determine the state of the groupt at (i,j)
// Remove it, if it has no liberties and note the removals
// as actions in the current node.
{
int ii, jj;
Action a;
if (P.color(i, j) != c) return;
if ( !P.markgrouptest(i, j, 0)) // liberties?
{
for (ii = 0; ii < S; ii++)
for (jj = 0; jj < S; jj++)
{
if (P.marked(ii, jj))
{
n.addchange(new Change(ii, jj, P.color(ii, jj), P
.number(ii, jj)));
if (P.color(ii, jj) > 0)
{
Pb++;
n.Pb++;
}
else
{
Pw++;
n.Pw++;
}
P.color(ii, jj, 0);
update(ii, jj); // redraw the field (offscreen)
captured++;
capturei = ii;
capturej = jj;
}
}
}
} |
533241be-3912-4a17-9d3d-41c9327a957a | 1 | @Override
public float contains( int x, int y ) {
if( parent.getBoundaries().contains( x, y ) ) {
return 1.f;
} else {
return 0.f;
}
} |
e33405fe-1b7f-4761-9d40-27f415513e75 | 0 | public Priority getPriority() {
return priority;
} |
085a9fb9-fee9-4a0d-84a3-14de0d5305be | 8 | public void checkPurchase()
{
if(BackerGS.storeVisible)
{
if(CurrencyCounter.currencyCollected < 80)
{
if(Greenfoot.mouseClicked(this))
{
NotEnoughMoney.fade = 200;
boop.play();
}
}
}
if(CurrencyCounter.currencyCollected >= 80)
{
if(PowerUps3.powerUp3 != 0)
{
if(Greenfoot.mouseClicked(this))
{
YouAlreadyHaveThisPotion.yfade = 200;
boop.play();
}
}
if(PowerUps3.powerUp3 == 0)
{
if(Greenfoot.mouseClicked(this))
{
chaChing.play();
CurrencyCounter.currencyCollected = CurrencyCounter.currencyCollected - 80;
PowerUps3.powerUp3 = 3;
}
}
}
} |
c080a9d6-8bfe-4053-b000-48d2c0461987 | 8 | private <T extends TaobaoResponse> Map<String, Object> doPost(TaobaoRequest<T> request, String session) throws ApiException {
Map<String, Object> result = new HashMap<String, Object>();
RequestParametersHolder requestHolder = new RequestParametersHolder();
TaobaoHashMap appParams = new TaobaoHashMap(request.getTextParams());
requestHolder.setApplicationParams(appParams);
// 添加协议级请求参数
TaobaoHashMap protocalMustParams = new TaobaoHashMap();
protocalMustParams.put(METHOD, request.getApiMethodName());
protocalMustParams.put(VERSION, "2.0");
protocalMustParams.put(APP_KEY, appKey);
Long timestamp = request.getTimestamp();// 允许用户设置时间戳
if (timestamp == null) {
timestamp = new Date().getTime();
}
DateFormat df = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
df.setTimeZone(TimeZone.getTimeZone(Constants.DATE_TIMEZONE));
protocalMustParams.put(TIMESTAMP, df.format(new Date(timestamp)));// 因为沙箱目前只支持时间字符串,所以暂时用Date格式
requestHolder.setProtocalMustParams(protocalMustParams);
TaobaoHashMap protocalOptParams = new TaobaoHashMap();
protocalOptParams.put(FORMAT, format);
protocalOptParams.put(SIGN_METHOD, signMethod);
protocalOptParams.put(SESSION, session);
protocalOptParams.put(PARTNER_ID, Constants.SDK_VERSION);
requestHolder.setProtocalOptParams(protocalOptParams);
// 添加签名参数
try {
if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
protocalMustParams.put(SIGN, TaobaoUtils.signTopRequestNew(requestHolder, appSecret, false));
} else if (Constants.SIGN_METHOD_HMAC.equals(signMethod)) {
protocalMustParams.put(SIGN, TaobaoUtils.signTopRequestNew(requestHolder, appSecret, true));
} else {
protocalMustParams.put(SIGN, TaobaoUtils.signTopRequest(requestHolder, appSecret));
}
} catch (IOException e) {
throw new ApiException(e);
}
StringBuffer urlSb = new StringBuffer(serverUrl);
try {
String sysMustQuery = WebUtils.buildQuery(requestHolder.getProtocalMustParams(), WebUtils.DEFAULT_CHARSET);
String sysOptQuery = WebUtils.buildQuery(requestHolder.getProtocalOptParams(), WebUtils.DEFAULT_CHARSET);
urlSb.append("?");
urlSb.append(sysMustQuery);
if (sysOptQuery != null & sysOptQuery.length() > 0) {
urlSb.append("&");
urlSb.append(sysOptQuery);
}
} catch (IOException e) {
throw new ApiException(e);
}
String rsp = null;
try {
// 是否需要上传文件
if (request instanceof TaobaoUploadRequest) {
TaobaoUploadRequest<T> uRequest = (TaobaoUploadRequest<T>) request;
Map<String, FileItem> fileParams = TaobaoUtils.cleanupMap(uRequest.getFileParams());
rsp = WebUtils.doPost(urlSb.toString(), appParams, fileParams, connectTimeout, readTimeout);
} else {
rsp = WebUtils.doPost(urlSb.toString(), appParams, connectTimeout, readTimeout);
}
} catch (IOException e) {
throw new ApiException(e);
}
result.put("rsp", rsp);
result.put("textParams", appParams);
result.put("protocalMustParams", protocalMustParams);
result.put("protocalOptParams", protocalOptParams);
result.put("url", urlSb.toString());
return result;
} |
f06beeaa-68de-4566-ae42-ee0ea8692b3d | 6 | public void dump(DumpSource ds) {
num.setLength(0);
txt.setLength(0);
offset = 0;
try {
int b = 0;
int column = 0;
while ((b=ds.get()) != -1) {
num.append(String.format("%02x", b & 0xff));
num.append(' ');
txt.append(Character.isLetterOrDigit((char)b) ? (char)b : '.');
if (++column % BYTES_PER_LINE == 0) {
endOfLine();
}
}
for ( ; column % BYTES_PER_LINE != 0 ; column++) {
num.append(" ");
}
// if partial line, output it.
if (++column % BYTES_PER_LINE != 0) {
endOfLine();
}
System.out.println();
} catch (IOException ex) {
System.out.println("Dumper: " + ex.toString());
}
} |
c8ffc5a8-3732-4e41-88f4-b9ea98495e24 | 5 | public boolean SendHeader() throws IOException
{
File l_fileAttribute;
PrintStream l_printStream;
Scanner l_readStream;
String l_basename;
long l_fileSize;
/*
* Check if socket and/or filename are not null
*/
if( ( up_socket == null ) ||
( up_filename == null ) )
return false;
/*
* Get file attrbutes
*/
l_fileAttribute = up_filename;
if( ( ! l_fileAttribute.exists() ) ||
( ! l_fileAttribute.isFile() ) ||
( ! l_fileAttribute.canRead() ) )
{
return false;
}
l_basename = l_fileAttribute.getName();
l_fileSize = l_fileAttribute.length();
/*
* Get in/out streams
*/
l_printStream = new PrintStream( up_socket.getOutputStream() );
l_readStream = new Scanner( up_socket.getInputStream() );
/*
* Send Basename and file size
*/
l_printStream.println(l_basename);
l_printStream.println(Long.toString(l_fileSize));
/*
* Retrieve server's response
*/
up_fileSize = l_fileSize;
return l_readStream.nextLine().equals(ALLOWED);
} |
830a36ed-3efe-4e24-ad60-1fc9db8aafc0 | 7 | public boolean isContinuousExcludeTerminalsAttachToRoot() {
int lcorner = getLeftmostProperDescendant().getIndex();
int rcorner = getRightmostProperDescendant().getIndex();
if (lcorner == rcorner) {
return true;
}
TokenNode terminal = ((TokenStructure)getBelongsToGraph()).getTokenNode(lcorner);
while (terminal.getIndex() != rcorner) {
if (terminal.getParent() != null && terminal.getParent().isRoot()) {
terminal = terminal.getSuccessor();
continue;
}
PhraseStructureNode tmp = terminal.getParent();
while (true) {
if (tmp == this) {
break;
}
if (tmp == null) {
return false;
}
tmp = tmp.getParent();
}
terminal = terminal.getSuccessor();
}
return true;
} |
d1f3c7c7-7460-4625-809b-3d10b2462d74 | 5 | public boolean add(String key, String value) {
String ligne;
try {
while ((ligne = _br.readLine()) != null) {
int a = 0;
while (ligne.charAt(a) != '@') {
a++;
}
ligne = ligne.substring(0, a);
if (key.equals(ligne)) {
_br.close();
return false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("erreur de lecture de la bdd");
}
try {
_br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("erreur de fermeture de la bdd");
}
_pw.println(key + "@" + value);
_pw.close();
return true;
} |
e17bebf4-055b-4751-88d7-5ea5d721a457 | 0 | private Vecteur getVecteur(int i) {
return new Vecteur(courante.getForme().getPoints(i).get(0) + position.get(0), courante.getForme().getPoints(i).get(1) + position.get(1));
} |
15590c1c-b4d1-446d-a552-1fc3abb20c4b | 4 | FloodFill(Canvas c, BufferedImage source, Point p, int threshold)
{
this.source = source;
this.threshold = threshold;
if (p.x < 0 || p.y < 0 || p.x >= source.getWidth() || p.y >= source.getHeight()) return;
targetRGB = source.getRGB(p.x,p.y);
floodFill(p,c);
} |
8a18fcc0-af02-446a-94a7-d9f125122897 | 4 | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
if (stacksize > 1) {
sb.append(" [").append(stacksize).append("]");
}
if (price > 0) {
sb.append(" ");
int total = price * stacksize;
if (total > 1000000) {
sb.append(format.format(total / 1000000f)).append("m");
} else if (total > 1000) {
sb.append(format.format(total / 1000f)).append("k");
} else {
sb.append(format.format(total));
}
}
return sb.toString();
} |
e3168d6c-563d-400f-8c06-a137febd1e6d | 0 | public StopRange getRange() {
return this.Range;
} |
25170c2b-5c43-46f9-99cb-8e36129f0b70 | 8 | public int compare(Static o1, Static o2) {
if(tiledata != null && o1.getX() == o2.getX() && o1.getY() == o2.getY() && o1.getZ() == o2.getZ()){
ItemData t1 = tiledata.getItem(o1.getId());
ItemData t2 = tiledata.getItem(o2.getId());
if(t1 == null && t2 == null) return 0;
int t1b = (t1.getFlags().contains(TileFlag.Background) ? 1: 0);
int t2b = (t2.getFlags().contains(TileFlag.Background) ? 1: 0);
return t2b - t1b;
}
return ((o1.getX() + o1.getY()) * 22 - o1.getZ() * VERTICAL_SHIFT) - ((o2.getX() + o2.getY()) * 22 - o2.getZ() * VERTICAL_SHIFT);
} |
97c7dd17-0ada-4690-8a71-8eb835d93712 | 7 | public void chooseShape(Point.Double p) {
JRadioButton rectangle = new JRadioButton();
JRadioButton circle = new JRadioButton();
JPanel radiopanel = shapeRadioPanel(rectangle, circle);
rectangle.setSelected(true);
circle.setSelected(false);
int chooseShape = JOptionPane.showConfirmDialog(null, radiopanel, "Choose shape.", JOptionPane.OK_CANCEL_OPTION);
if (chooseShape == JOptionPane.CANCEL_OPTION || chooseShape == JOptionPane.CLOSED_OPTION) {
return;
} else if (chooseShape == JOptionPane.OK_OPTION) {
shape = temp;
}
switch (shape) {
case "Rectangle":
if (p == null) {
rectangleOptions();
} else {
rectangleOptions(p);
}
break;
case "Circle":
if (p == null) {
circleOptions();
} else {
circleOptions(p);
}
break;
}
} |
b1b3ec09-46aa-4737-803d-aca8a37f87cc | 3 | @Override
protected void resolveCollision(GameContext g,Collidable c, float percent) {
if (isGhost)
return;
setCollisionPosition(percent);
if (c instanceof Dot) {
if (((Dot)c).isGhost)
return;
g.removals.add(this);
setDead(true);
g.removals.add((Mob)c);
((Dot)c).setDead(true);
Vector newVel = Vector.add(((Mob)c).velocity,velocity);
g.additions.add(new DynamicPolygon(model,position.x,position.y,newVel.x,newVel.y,2));
g.additions.add(new Explosion(model,collisionPosition.x,collisionPosition.y,Parameters.DOT_COLOR));
}
} |
5f5029ac-305c-483c-b49c-d5cf216694e1 | 1 | @Test
public void newBoard_verifyPiecePlacement() throws Exception {
// when
final Board board = new Board();
// then
for (int i = 0; i < 8; i++) {
assertPieceTypePlacement(board, PieceType.PAWN, i);
}
assertPieceTypePlacement(board, PieceType.ROOK, 0);
assertPieceTypePlacement(board, PieceType.KNIGHT, 1);
assertPieceTypePlacement(board, PieceType.BISHOP, 2);
assertPieceTypePlacement(board, PieceType.QUEEN, 3);
assertPieceTypePlacement(board, PieceType.KING, 4);
assertPieceTypePlacement(board, PieceType.BISHOP, 5);
assertPieceTypePlacement(board, PieceType.KNIGHT, 6);
assertPieceTypePlacement(board, PieceType.ROOK, 7);
} |
235c98ad-aa7b-478e-a3e8-5dbbbb7a288a | 8 | public static boolean isTransition(char s1, char s2){
if ((s1=='A')&&(s2=='G')) return true;
if ((s1=='G')&&(s2=='A')) return true;
if ((s1=='C')&&(s2=='T')) return true;
if ((s1=='T')&&(s2=='C')) return true;
return false;
} |
38361eb8-4bd1-4645-a8c1-cd6f4821fb13 | 2 | @Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() == orderList) {
// check if order list is empty
if (orderList.getSelectedIndex() > -1) {
// separate the text in the selected list item
String[] values = orderList.getSelectedValue().split("\\t");
// JOptionPane.showMessageDialog(null, values[1]);
showOrderDetails(driver.getOrderDB().getOrderById(
Integer.parseInt(values[0].trim()),
driver.getOrderDB().getCustomerOrderList()));
}
}
} |
86754ce6-36d9-4467-8cf7-6f5e8140b582 | 9 | public int compareTo( Object obj ) {
if( obj == null ) {
return( 1 );
}
else if( obj instanceof GenKbTenantByUNameIdxKey ) {
GenKbTenantByUNameIdxKey rhs = (GenKbTenantByUNameIdxKey)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredTenantName().compareTo( rhs.getRequiredTenantName() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else if( obj instanceof GenKbTenantBuff ) {
GenKbTenantBuff rhs = (GenKbTenantBuff)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredTenantName().compareTo( rhs.getRequiredTenantName() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else {
throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(),
"compareTo",
"obj",
obj,
null );
}
} |
c0b53531-e2f8-4685-af66-47879c1465a9 | 9 | protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} |
0e90abd9-c4fa-4887-ad4d-abb28db41396 | 6 | public boolean updateLeagueHierarchyRequest(Sport sport) {
String request = null;
switch(sport) {
case NBA: case NHL:
request = "http://api.sportsdatallc.org/" + sport.getName() + "-" + access_level + sport.getVersion() + "/league/hierarchy.xml?api_key=" + sport.getKey();
Element element = send(request);
try {
Node node = null;
NodeList teamNodes = element.getElementsByTagName("team");
for (int i=0;i<teamNodes.getLength();i++) {
NamedNodeMap nodeMapTeamAttributes = teamNodes.item(i).getAttributes();
node = nodeMapTeamAttributes.getNamedItem("id");
String team_id = node.getNodeValue();
node = nodeMapTeamAttributes.getNamedItem("name");
String team_name = node.getNodeValue();
String team_city = "", team_country = "";
NodeList nodeInTeam = teamNodes.item(i).getChildNodes();
for (int j=0;j<nodeInTeam.getLength();j++) {
if (nodeInTeam.item(j).getNodeName().equals("venue")) {
NamedNodeMap nodeMapVenueAttributes = nodeInTeam.item(j).getAttributes();
node = nodeMapVenueAttributes.getNamedItem("city");
team_city = node.getNodeValue();
node = nodeMapVenueAttributes.getNamedItem("country");
team_country = node.getNodeValue();
}
}
TeamModel team = new TeamModel(team_id,team_name,team_city,team_country);
DataStore.storeTeam(team);
}
} catch (Exception e) {
System.out.println("@ erreur lors du parcours du fichier xml dans getLeagueHierarchyRequest()");
return false;
}
break;
// à compléter si besoin
default:
break;
}
return true;
} |
636cff67-d28b-4355-b233-d16b91673422 | 7 | private void initializeView()
{
this.setOpaque(true);
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createLineBorder(Color.black, BORDER_WIDTH));
label = new JLabel("Welcome to the game hub");
Font labelFont = label.getFont();
labelFont = labelFont.deriveFont(labelFont.getStyle(), LABEL_TEXT_SIZE);
label.setFont(labelFont);
subLabel = new JLabel("Join an existing game, or create your own");
labelFont = subLabel.getFont();
labelFont = labelFont.deriveFont(labelFont.getStyle(), LABEL_TEXT_SIZE * 2 / 3);
subLabel.setFont(labelFont);
labelPanel = new JPanel();
labelPanel.setLayout(new FlowLayout());
labelPanel.add(label);
labelPanel.add(subLabel);
this.add(labelPanel, BorderLayout.NORTH);
// This is the header layout
gamePanel = new JPanel();
gamePanel.setLayout(new GridLayout(0, 4));
hash = new JLabel("#");
labelFont = new Font(labelFont.getFontName(), Font.BOLD, PANEL_TEXT_SIZE);
hash.setFont(labelFont);
name = new JLabel("Name");
name.setFont(labelFont);
currentPlayer = new JLabel("Current Players");
currentPlayer.setFont(labelFont);
join = new JLabel("Join");
join.setFont(labelFont);
gamePanel.add(hash);
gamePanel.add(name);
gamePanel.add(currentPlayer);
gamePanel.add(join);
// This is the looped layout
if (games != null && games.size() > 0)
{
labelFont = labelFont.deriveFont(labelFont.getStyle(), PANEL_TEXT_SIZE);
for (GameDescription game : games)
{
JLabel tmp1 = new JLabel(String.valueOf(game.getId()));
tmp1.setFont(labelFont);
gamePanel.add(tmp1);
JLabel tmp2 = new JLabel(game.getTitle());
tmp2.setFont(labelFont);
gamePanel.add(tmp2);
List<PlayerDescription> playersList = game.getPlayerDescriptions();
String players = String.valueOf(playersList.size())+ "/4 : ";
//String players = String.valueOf(game.getPlayers().size()) + "/4 : ";
for (int j = 0; j < playersList.size(); j++) {
if (j < playersList.size() - 1) {
players = players + playersList.get(j).getName() + ", ";
} else {
players = players + playersList.get(j).getName();
}
}
JLabel tmp3 = new JLabel(players);
tmp3.setFont(labelFont);
gamePanel.add(tmp3);
JButton joinButton;
if (playersList.contains(localPlayer))
{
joinButton = new JButton("Re-Join");
}
else if (playersList.size() >= 4)
{
joinButton = new JButton("Full");
joinButton.setEnabled(false);
}
else
{
joinButton = new JButton("Join");
}
joinButton.setActionCommand("" + game.getId());
joinButton.addActionListener(actionListener);
gamePanel.add(joinButton);
}
}
//Add all the above
this.add(gamePanel, BorderLayout.CENTER);
tempJoinButton = new JButton("Temporary Join Button");
tempJoinButton.addActionListener(actionListener);
Font buttonFont = tempJoinButton.getFont();
buttonFont = buttonFont.deriveFont(buttonFont.getStyle(), BUTTON_TEXT_SIZE);
tempJoinButton.setFont(buttonFont);
createButton = new JButton("Create Game");
createButton.addActionListener(actionListener);
createButton.setFont(buttonFont);
buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(createButton);
buttonPanel.add(tempJoinButton);
this.add(buttonPanel, BorderLayout.SOUTH);
} |
47ed56fc-c529-4f60-bac2-85eb81d98abd | 7 | private void gameUpdate() {
if (!isPaused && !gameOver) {
//TODO Do something with game state
// You can for instance set certain flags and here you would then put: if(flag) => do something
/** PLACE A BLOCK **/
if(placeBlockFlag){
//Place the block
currentSelectedBlock.activate(new ArrayList<Node>(dropList));
for(Node n : dropList){
n.setFocussed(false);
if(n.isActive()){
if(this.currentPlayer!=player1){
player1.loseLife();
} else{
player2.loseLife();
}
}
n.activate(currentSelectedBlock, currentSelectedBlock.getColor());
}
//Adjust hand
this.currentPlayer.popBlock(nbOfCurrentSelectedBlockInHand);
this.nbOfCurrentSelectedBlockInHand = 0;
currentSelectedBlock = null;
gui.clearHandSelection();
setPlaceBlockFlag(false);
switchPhase();
}
gui.updatePlayerHealth();
gui.updatePlayerDecksize();
if(this.currentPlayer.isDead()){
System.out.println(currentPlayer+" is dead!");
}
}
} // end of gameUpdate() |
010ee173-e07a-4126-97e4-9379029ceeda | 6 | public void evolve() {
// Create a buffer for the new generation
Chromosome[] buffer = new Chromosome[popArr.length];
// Copy over a portion of the population unchanged, based on
// the elitism ratio.
int idx = Math.round(popArr.length * elitism);
System.arraycopy(popArr, 0, buffer, 0, idx);
// Iterate over the remainder of the population and evolve as
// appropriate.
while (idx < buffer.length) {
// Check to see if we should perform a crossover.
if (rand.nextFloat() <= crossover) {
// Select the parents and mate to get their children
Chromosome[] parents = selectParents();
Chromosome[] children = parents[0].mate(parents[1]);
// Check to see if the first child should be mutated.
if (rand.nextFloat() <= mutation) {
buffer[idx++] = children[0].mutate();
} else {
buffer[idx++] = children[0];
}
// Repeat for the second child, if there is room.
if (idx < buffer.length) {
if (rand.nextFloat() <= mutation) {
buffer[idx] = children[1].mutate();
} else {
buffer[idx] = children[1];
}
}
} else { // No crossover, so copy verbatium.
// Determine if mutation should occur.
if (rand.nextFloat() <= mutation) {
buffer[idx] = popArr[idx].mutate();
} else {
buffer[idx] = popArr[idx];
}
}
// Increase our counter
++idx;
}
// Sort the buffer based on fitness.
Arrays.sort(buffer);
// Reset the population
popArr = buffer;
} |
63346680-f707-4e0f-914b-45a0482944a5 | 5 | public void updateAt(Tile tile) {
int value = 0 ;
final Element owner = tile.owner() ;
if (owner instanceof Installation) {
value = ((Installation) owner).structure().ambienceVal() ;
}
if (owner instanceof Flora) {
value = ((Flora) owner).growStage() ;
}
for (Mobile m : tile.inside()) if (m instanceof Actor) {
final Actor a = (Actor) m ;
value -= 5 * a.health.stressPenalty() ;
final Item outfit = a.gear.outfitEquipped() ;
if (outfit != null) value += (outfit.quality - 1) / 2f ;
}
mapValues.set((byte) value, tile.x, tile.y) ;
} |
319269ba-4242-4774-a990-c48c7af2f24e | 1 | private void log(String string) {
System.out.print(string);
if (++m_count % 40 == 0) {
System.out.println("");
}
} |
b224e2e6-96d8-44ac-b3e4-e4fd6cbc5f9c | 5 | @Override
public void rodarJogo(){
if (JOptionPane.showConfirmDialog(null, "\nUsar midia física?\n","Iniciando...",JOptionPane.YES_NO_OPTION) == 0 ){
this.jogoRodando = JOptionPane.showInputDialog(null,"\nInforme qual o jogo a executar\n","Iniciando...",JOptionPane.INFORMATION_MESSAGE);
int aux = Integer.parseInt(JOptionPane.showInputDialog(null,"\nInforme a quantia de jogadores\n","Iniciando...",JOptionPane.INFORMATION_MESSAGE));
if(aux > 0 && aux <= maxControles){
qtControles = aux;
if (JOptionPane.showConfirmDialog(null, "\nUsar kinect?\n","Iniciando...",JOptionPane.YES_NO_OPTION) == 0 ){
if(kinect == null)
kinect = new Kinect();
usarKinect();
}
rodaMidiaFisica();
}
else
JOptionPane.showMessageDialog(null, "\nQuantia de jogadores invalida\n","Limite excedido",JOptionPane.ERROR_MESSAGE);
}
else
rodaMidiaVirtual();
} |
78d0dabd-8dc5-453c-8c91-b11eeb11c2f8 | 0 | public boolean isAccepted() {
return false;
} |
e077c46f-e070-45c8-9ce6-850786707443 | 2 | private String prepareGet(Response data) throws Exception {
if(data == null)
return "";
StringBuffer sb = new StringBuffer();
Map<String, String> params = data.toMap();
for(Entry<String, String> s : params.entrySet()) {
sb.append('&');
sb.append(URLEncoder.encode(s.getKey(), ENCODE) + "=" + URLEncoder.encode(s.getValue(), ENCODE));
}
return sb.toString();
} |
db0489b1-b840-47a6-a2c3-7020d5f0421a | 0 | public Instruction getInstruction(int currState) {
return fsm.get(currState);
} |
b1d703a0-ce94-400a-9e02-44fc8c89ce1f | 5 | public static void main(String[] args) {
// TODO Auto-generated method stub
long temp = 1;
boolean flag = true;
for(int i=1;i<=20; i++)
temp=temp*i;
long lcm =temp;
System.out.println(temp);
for(long j = 1 ; j <lcm; j++)
{
for(long k=1; k <= 20; k++)
{
if(j%k != 0)
{
flag = false;
break;
}
flag = true;
}
if(flag == true)
{System.out.println(j);
break;
}
}
} |
b7b475db-4475-455d-8aa7-2f5898d9dd05 | 7 | public void use(BattleFunction iface, PokeInstance user, PokeInstance target, Move move) {
if (this.target == Target.target) {
if (target.battleStatus.flags[8] && levels < 0)
return;
target.battleStatus.modify(stat, levels);
if (levels > 0) {
iface.print(target.getName() + "'s " + stat.name() + " has been raised!");
} else {
iface.print(target.getName() + "'s " + stat.name() + " has been lowered...");
}
} else {
if (user.battleStatus.flags[8] && levels < 0)
return;
user.battleStatus.modify(stat, levels);
if (levels > 0) {
iface.print(user.getName() + " raised it's " + stat.name());
} else {
iface.print(user.getName() + "'s lowered it's " + stat.name());
}
}
} |
1e7673b9-c06d-472d-8d93-cb4e85708f25 | 4 | private static String[] tempFSA(String[] input) {
char[] transitions = {' ', ',', '.', '?'};
int numberOfTransitions = transitions.length;
String[] output = new String[input.length*input.length*numberOfTransitions];
int counter = 0;
int internalCounters[] = new int[input.length];
Arrays.fill(internalCounters, (transitions.length - 1));
while (internalCounters[0]>=0) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < input.length; i++) {
sb.append(input[i]);
sb.append(transitions[internalCounters[i]]);
}
//System.err.println(internalCounters[internalCounters.length-1]);
internalCounters[internalCounters.length-1]--;
for(int i = 1; i < internalCounters.length; i++) {
if(internalCounters[i]<0) {
internalCounters[i] = numberOfTransitions-1;
internalCounters[i-1]--;
}
}
//System.err.println(sb.toString());
output[counter] = sb.toString();
counter++;
}
return output;
} |
0975e6f2-37f5-4e63-b8dc-ab312a3fd1f1 | 2 | public Cell findByCellValue(String value) {
for(Cell c : cells) {
if(value.equals(c.getCellValue())) {
return c;
}
}
return null;
} |
b798c85a-2ebd-4290-b036-71e056d0dd35 | 0 | public Music(Animation anim) {
super(anim);
} |
935ce953-cce8-416e-a9d8-b0c4b89d0e74 | 4 | boolean safe(int r, int c, int n, int[] occ) {
for (int i = 0; i <= r; ++i) {
if(occ[i] == c || Math.abs(occ[i]+i)==Math.abs(r+c) || occ[i]-i==c-r) {
return false;
}
}
return true;
} |
5dfe5118-40ee-425a-9aa2-70d271b1bd13 | 6 | @Override
public void run(Player interact, Entity on, InteractionType type) {
if(type != InteractionType.DAMAGE) return;
int range = 2;
if(interact.isSneaking()) range = 5;
for(Entity e : on.getNearbyEntities(range, range, range)){
if(e instanceof LivingEntity){
LivingEntity le = (LivingEntity) e;
if(!le.equals(interact) && !le.equals(on)) le.damage(2);
}
}
} |
4afecd32-19be-4cd6-bd83-4fa21810c10c | 1 | public void cleanup() {
final Iterator iter = clean.iterator();
while (iter.hasNext()) {
final Node node = (Node) iter.next();
node.cleanup();
}
} |
02319488-3203-4be4-a2f9-132ddcdf8c7b | 0 | public EventServlet() {
super();
// TODO Auto-generated constructor stub
} |
a8269293-0b08-41b9-a73f-7a2aee651dc0 | 2 | private boolean untar(File fileToUntar) throws FileNotFoundException, IOException {
boolean fileUntarred = false;
String untarLocation = fileToUntar.getAbsolutePath();
TarArchiveInputStream tarStream = new TarArchiveInputStream(new FileInputStream(fileToUntar));
BufferedReader bufferedTarReader = new BufferedReader(new InputStreamReader(tarStream));
ArchiveEntry entry;
while ((entry = tarStream.getNextEntry()) != null) {
char[] cbuf = new char[1024];
int count;
FileWriter out = new FileWriter(new File(String.format("%s/%s", untarLocation, entry.getName())));
while ((count = bufferedTarReader.read(cbuf, 0, 1024)) != -1) {
out.write(cbuf, 0, count);
}
out.flush();
out.close();
}
bufferedTarReader.close();
tarStream.close();
return fileUntarred;
} |
0e010c23-7f80-4d63-9733-735ae9180e95 | 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 DiscountCode)) {
return false;
}
DiscountCode other = (DiscountCode) object;
if ((this.discountCode == null && other.discountCode != null) || (this.discountCode != null && !this.discountCode.equals(other.discountCode))) {
return false;
}
return true;
} |
0fcbd93d-93e8-44a2-b14a-9ad539d3eef8 | 6 | public void mouseDragged(MouseEvent e ) {
if( fGrowBase != null ) {
Point loc = fComponent.getLocationOnScreen();
int width = Math.max(2, loc.x+e.getX() - fGrowBase.x);
int height= Math.max(2, loc.y+e.getY() - fGrowBase.y);
if( e.isShiftDown() && fImage!=null ) {
float imgWidth = fImage.getWidth(this);
float imgHeight = fImage.getHeight(this);
if( imgWidth>0 && imgHeight>0 ) {
float prop = imgHeight / imgWidth;
float pwidth = height / prop;
float pheight= width * prop;
if( pwidth > width )
width = (int) pwidth;
else
height = (int) pheight;
}
}
resize(width,height);
}
} |
d403c07b-8a2e-48bf-9b73-a31d50bffde8 | 3 | public String reverseWords(String s) {
String[] list = s.split(" ");
String result = "";
for(int i = list.length-1 ;i >= 0 ;i--){
if(!list[i].equals("") )
result = result+ list[i]+" ";
}
if(result.length() > 0)
return result.substring(0,result.length()-1);
else
return result;
} |
5fbadc56-804b-452c-b9d7-b1893cf020ae | 7 | public void initTransitionSystem(GuideUserHistory history) throws MaltChainedException {
this.actionContainers = history.getActionContainerArray();
if (actionContainers.length < 1) {
throw new ParsingException("Problem when initialize the history (sequence of actions). There are no action containers. ");
}
int nLabels = 0;
for (int i = 0; i < actionContainers.length; i++) {
if (actionContainers[i].getTableContainerName().startsWith("A.")) {
nLabels++;
}
}
int j = 0;
for (int i = 0; i < actionContainers.length; i++) {
if (actionContainers[i].getTableContainerName().equals("T.TRANS")) {
transActionContainer = actionContainers[i];
} else if (actionContainers[i].getTableContainerName().startsWith("A.")) {
if (arcLabelActionContainers == null) {
arcLabelActionContainers = new ActionContainer[nLabels];
}
arcLabelActionContainers[j++] = actionContainers[i];
}
}
initWithDefaultTransitions(history);
} |
71ccfae9-479c-4edb-bdf5-00645d4ee79c | 9 | public Parameter getLiblinearParameters() throws MaltChainedException {
Parameter param = new Parameter(SolverType.MCSVM_CS, 0.1, 0.1);
String type = liblinearOptions.get("s");
if (type.equals("0")) {
param.setSolverType(SolverType.L2R_LR);
} else if (type.equals("1")) {
param.setSolverType(SolverType.L2R_L2LOSS_SVC_DUAL);
} else if (type.equals("2")) {
param.setSolverType(SolverType.L2R_L2LOSS_SVC);
} else if (type.equals("3")) {
param.setSolverType(SolverType.L2R_L1LOSS_SVC_DUAL);
} else if (type.equals("4")) {
param.setSolverType(SolverType.MCSVM_CS);
} else if (type.equals("5")) {
param.setSolverType(SolverType.L1R_L2LOSS_SVC);
} else if (type.equals("6")) {
param.setSolverType(SolverType.L1R_LR);
} else {
throw new LiblinearException("The liblinear type (-s) is not an integer value between 0 and 4. ");
}
try {
param.setC(Double.valueOf(liblinearOptions.get("c")).doubleValue());
} catch (NumberFormatException e) {
throw new LiblinearException("The liblinear cost (-c) value is not numerical value. ", e);
}
try {
param.setEps(Double.valueOf(liblinearOptions.get("e")).doubleValue());
} catch (NumberFormatException e) {
throw new LiblinearException("The liblinear epsilon (-e) value is not numerical value. ", e);
}
return param;
} |
b039e435-7fe6-4fd6-a145-a614c23496ef | 5 | private void situationalInfluenceUpdate()
{
//array to hold each stakeholder's numerator value
double[] stakeholderNumerators = new double[Stakeholders.size()];
double stakeholderDenominator = 0;
//tally up each stakeholder's list of relationships
for (int i = 0; i < Stakeholders.size(); i++)
{
//temp Relationship to hold stakeholder's relationship
Relationship buddy;
//temp arrayList to hold stakeholder's relationships
ArrayList <Relationship> tempRelationships = new ArrayList<>();
for(Relationship partner: Stakeholders.get(i).getInfluences()){
buddy = new Relationship(partner);
tempRelationships.add(buddy);}
double stakeholderInfluenceNumerator = 0;
double magnitudeValue;
double classificationValue;
double attitudeValue;
//iterate through each stakeholder's relationships
for (int j = 0; j < tempRelationships.size(); j++)
{
magnitudeValue = influenceConverter(tempRelationships.get(j).getMagnitude());
classificationValue = classificationConverter(Stakeholders.get(j).getClassification());
attitudeValue = attitudeConverter(Stakeholders.get(j).getAttitude());
stakeholderInfluenceNumerator += (magnitudeValue*classificationValue*attitudeValue);
}
//store stakeholder's influence number in array
stakeholderNumerators[i] = stakeholderInfluenceNumerator;
stakeholderDenominator += stakeholderInfluenceNumerator;
}//end of get each stakeholder's influence numerator loop
//calculate each stakeholder's situational influence
for (int i = 0; i < Stakeholders.size(); i++)
{
if (stakeholderDenominator == 0)
{stakeholderDenominator = 1;}
else {}
double situationalInfluence = stakeholderNumerators[i]/stakeholderDenominator;
//save each stakeholder's individual situational influence
Stakeholders.get(i).setInfluence(situationalInfluence);
}
} |
529cf547-5f26-4a92-9772-4789e17fea04 | 1 | public void testFactory_FromCalendarFields() throws Exception {
GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6);
cal.set(Calendar.MILLISECOND, 7);
TimeOfDay expected = new TimeOfDay(4, 5, 6, 7);
assertEquals(expected, TimeOfDay.fromCalendarFields(cal));
try {
TimeOfDay.fromCalendarFields(null);
fail();
} catch (IllegalArgumentException ex) {}
} |
a45ad1c8-5eed-4679-91a9-e1daa38069bb | 5 | public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int f = 0;
d: do {
int s = scan.nextInt();
if (s == 0)
break d;
int[][] m = new int[s][s];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m.length; j++)
m[i][j] = scan.nextInt();
sb.append(((f++ != 0) ? "\n" : "") + v(m));
} while (scan.hasNext());
System.out.println(sb);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.