text stringlengths 14 410k | label int32 0 9 |
|---|---|
public ArrayList<Team> CreateTeams() {
for (int i = 0; i < NumOfTeams; i++) {
Team t = new Team();
teams.add(t);
}
return teams;
} | 1 |
@Override
public void update() {
// Consider player input and create more ribbons if requested
if( inputEvent.keyTyped( KeyEvent.VK_1 ) )
createRibbons( 1 );
else if( inputEvent.keyTyped( KeyEvent.VK_2 ) )
createRibbons( 10 );
else if( inputEvent.keyTyped( KeyEvent.VK_3 ) )
createRibbons( 100 );
// Move the viewport on each ribbon (move some ribbons faster than others)
int iOffsetCounter = 1;
for( GameObject gameObject : this.gameObjects.values() ) {
((ImageAssetRibbon)gameObject.graphicalRealisation[0])
.moveViewPortRight( (iOffsetCounter++)%5 + 1 );
}
} | 4 |
public AutomatonGraph(Automaton automaton) {
super();
State[] states = automaton.getStates();
Transition[] transitions = automaton.getTransitions();
for (int i = 0; i < states.length; i++)
addVertex(states[i], states[i].getPoint());
for (int i = 0; i < transitions.length; i++)
addEdge(transitions[i].getFromState(), transitions[i].getToState());
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != getClass()) return false;
Vector3 other = (Vector3) obj;
return x == other.x && y == other.y && z == other.z;
} | 5 |
private void BtGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtGravarActionPerformed
if (camposobrigatoriospreenchidos()) {
if (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja Gravar esta compra e de que todas as informações estão corretas?", "Deseja gravar?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
enviardados();
prodcompravenda.getCompravenda().incluir();
ClasseMvtoEstoque mvestoque = new ClasseMvtoEstoque();
final ClasseParcelas parcelas = new ClasseParcelas();
mvestoque.setCompravenda(prodcompravenda.getCompravenda());
mvestoque.setDtmvto(datas.retornadataehora());
mvestoque.setTpmvto("E");
if (TbCompra.getRowCount() > 0){
for (int i = 0; i < TbCompra.getRowCount(); i++) {
prodcompravenda.getForneproduto().getProduto().setCodigo(Integer.parseInt(TbCompra.getValueAt(i, 1).toString()));
TfQuantidade.setText(TbCompra.getValueAt(i, 3).toString());
prodcompravenda.setQuantidade(Float.parseFloat(TfQuantidade.getValue().toString()));
TfValorUnitario.setText(TbCompra.getValueAt(i, 4).toString());
prodcompravenda.setValorunit(Float.parseFloat(TfValorUnitario.getValue().toString()));
TfDesconto.setText(TbCompra.getValueAt(i, 5).toString());
prodcompravenda.setDesconto(Float.parseFloat(TfDesconto.getValue().toString()));
TfValorProduto.setText(TbCompra.getValueAt(i, 6).toString());
prodcompravenda.setValorprodut(Float.parseFloat(TfValorProduto.getValue().toString()));
prodcompravenda.setPromocao(TbCompra.getValueAt(i, 7).toString());
prodcompravenda.incluirprodutocompravenda();
mvestoque.getProduto().setCodigo(Integer.parseInt(TbCompra.getValueAt(i, 1).toString()));
if (!mvestoque.getProduto().eservico()){
TfQuantidade.setText(TbCompra.getValueAt(i, 3).toString());
mvestoque.setQtmvto(Float.parseFloat(TfQuantidade.getValue().toString()));
mvestoque.incluirmvto();
}
}
parcelas.getConta().setTotal(Float.parseFloat(TfValorTotalCompra.getValue().toString()));
} else if (TbCompraServ.getRowCount() > 0){
for (int i = 0; i < TbCompraServ.getRowCount(); i++) {
prodcompravenda.getForneproduto().getProduto().setCodigo(Integer.parseInt(TbCompraServ.getValueAt(i, 1).toString()));
TfQuantidadeServ.setText(TbCompraServ.getValueAt(i, 3).toString());
prodcompravenda.setQuantidade(Float.parseFloat(TfQuantidadeServ.getValue().toString()));
TfValorUnitarioServ.setText(TbCompraServ.getValueAt(i, 4).toString());
prodcompravenda.setValorunit(Float.parseFloat(TfValorUnitarioServ.getValue().toString()));
TfDescontoServ.setText(TbCompraServ.getValueAt(i, 5).toString());
prodcompravenda.setDesconto(Float.parseFloat(TfDescontoServ.getValue().toString()));
TfValorProdutoServ.setText(TbCompraServ.getValueAt(i, 6).toString());
prodcompravenda.setValorprodut(Float.parseFloat(TfValorProdutoServ.getValue().toString()));
prodcompravenda.setPromocao(TbCompraServ.getValueAt(i, 7).toString());
prodcompravenda.incluirprodutocompravenda();
}
parcelas.getConta().setTotal(Float.parseFloat(TfValorTotalCompraServ.getValue().toString()));
}
parcelas.getConta().setCompravenda(prodcompravenda.getCompravenda());
parcelas.getConta().setCondicao(prodcompravenda.getCompravenda().getCondicao());
parcelas.getConta().setOperacao(prodcompravenda.getCompravenda().getOperacao());
parcelas.getConta().setDescricao(prodcompravenda.getCompravenda().getDescricao());
parcelas.getConta().setDtconta(TfData.getText());
parcelas.getConta().setCodigopessoa(prodcompravenda.getCompravenda().getCodigopessoa());
parcelas.getConta().incluir();
parcelas.gerarparcelas();
final InterfaceAjusteDatasEPrecos tela = new InterfaceAjusteDatasEPrecos(getPrimeiratela(), true, parcelas);
tela.setVisible(true);
tela.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
HashMap filtro = new HashMap();
filtro.put("CD_COMPRA_VENDA", prodcompravenda.getCompravenda().getCodigo());
filtro.put("CD_OPERACAO", prodcompravenda.getCompravenda().getOperacao().getCodigo());
filtro.put("CD_CONTA", parcelas.getConta().getCodigo());
filtro.put("DS_NOTA", "EXTRATO DE COMPRA");
filtro.put("TP_PESSOA", "Fornecedor:");
ConexaoPostgre conexao = new ConexaoPostgre();
JDialog dialog = new JDialog(new javax.swing.JFrame(), "Visualização - Software Loja da Fátima", true);
dialog.setSize(1000, 700);
dialog.setLocationRelativeTo(null);
try {
JasperPrint print = JasperFillManager.fillReport("relatorios\\notaoperacaoestoquefinanceiro.jasper", filtro, conexao.conecta());
JasperViewer viewer = new JasperViewer(print, true);
dialog.getContentPane().add(viewer.getContentPane());
dialog.setVisible(true);
} catch (Exception ex) {
System.out.println(ex);
}
}
});
limpar.Limpar(jPanel1);
limpar.Limpar(jPanel3);
limpar.Limpar(jPanel4);
limpar.Limpar(TbCompra);
valida.validacamposCancelar(jPanel1, PnBotoes);
valida.validacamposCancelar(jPanel3, PnBotoes);
valida.validacamposCancelar(jPanel4, PnBotoes);
}
}
}//GEN-LAST:event_BtGravarActionPerformed | 8 |
public Document modifyDocumentFrom(InstanceCheckerEngine logic, Document document, InstanceCheckerParser problem) {
Element functionsElement = XMLManager.getElementByTagNameFrom(document.getDocumentElement(), InstanceTokens.FUNCTIONS, 0);
if (functionsElement != null)
document.getDocumentElement().removeChild(functionsElement);
Element predicatesElement = XMLManager.getElementByTagNameFrom(document.getDocumentElement(), InstanceTokens.PREDICATES, 0);
if (predicatesElement != null)
document.getDocumentElement().removeChild(predicatesElement);
Element constraintsElement = XMLManager.getElementByTagNameFrom(document.getDocumentElement(), InstanceTokens.CONSTRAINTS, 0);
NodeList nodeList = constraintsElement.getElementsByTagName(InstanceTokens.CONSTRAINT);
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String reference = element.getAttribute(InstanceTokens.REFERENCE);
if (problem.getFunctionsMap().containsKey(reference) || problem.getPredicatesMap().containsKey(reference)) {
Element parameters = XMLManager.getElementByTagNameFrom(element, InstanceTokens.PARAMETERS, 0);
element.removeChild(parameters);
String name = element.getAttribute(InstanceTokens.NAME);
element.setAttribute(InstanceTokens.REFERENCE, problem.getConstraintsToNewRelations().get(name));
}
}
Element relationsElement = XMLManager.getElementByTagNameFrom(document.getDocumentElement(), InstanceTokens.RELATIONS, 0);
if (relationsElement == null) {
relationsElement = document.createElement(InstanceTokens.RELATIONS);
document.getDocumentElement().insertBefore(relationsElement, constraintsElement);
}
relationsElement.setAttribute(InstanceTokens.NB_RELATIONS, problem.getRelationsMap().size() + problem.getNewRelations().size() + ""); // relations.size() + "");
// int spotLimit = (problem.getNewRelations().size() / 20);
int cpt = 0;
for (PRelation relation : problem.getNewRelations()) {
cpt++;
Element relationElement = document.createElement(InstanceTokens.RELATION);
relationElement.setAttribute(InstanceTokens.NAME, relation.getName());
relationElement.setAttribute(InstanceTokens.ARITY, relation.getArity() + "");
relationElement.setAttribute(InstanceTokens.NB_TUPLES, relation.getTuples().length + "");
relationElement.setAttribute(InstanceTokens.SEMANTICS, relation.getSemantics());
if (relation instanceof PSoftRelation)
relationElement.setAttribute(InstanceTokens.DEFAULT_COST, ((PSoftRelation)relation).getDefaultCost()+ "");
relationElement.setTextContent(relation.getStringListOfTuples());
relationsElement.appendChild(relationElement);
if (cpt % 10 == 0)
logic.spot();
}
return document;
} | 9 |
private void dfs(Digraph G, int v) {
count++;
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) dfs(G, w);
}
} | 2 |
public String getDescriptor(int r, int c) {
switch (currentTurn) {
case 1:
if (c < unitsP1.length )
return unitsP1[r][c].getDescriptor();
else
return terrainP1[r][c - unitsP1.length].getDescriptor();
case 2:
if (c < unitsP2.length )
return unitsP2[r][c].getDescriptor();
else
return terrainP2[r][c - unitsP2.length].getDescriptor();
case 3:
if (c < unitsP3.length )
return unitsP3[r][c].getDescriptor();
else
return terrainP3[r][c - unitsP3.length].getDescriptor();
default:
if (c < unitsP4.length )
return unitsP4[r][c].getDescriptor();
else
return terrainP4[r][c - unitsP4.length].getDescriptor();
}
} | 7 |
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
String parm = (commands.size() > 1) ? CMParms.combine(commands,1) : "";
if((mob.isAttributeSet(MOB.Attrib.AUTOASSIST) && (parm.length()==0))||(parm.equalsIgnoreCase("ON")))
{
mob.setAttribute(MOB.Attrib.AUTOASSIST,false);
mob.tell(L("Autoassist has been turned on."));
}
else
if((!mob.isAttributeSet(MOB.Attrib.AUTOASSIST) && (parm.length()==0))||(parm.equalsIgnoreCase("OFF")))
{
mob.setAttribute(MOB.Attrib.AUTOASSIST,true);
mob.tell(L("Autoassist has been turned off."));
}
else
if(parm.length() > 0)
{
mob.tell(L("Illegal @x1 argument: '@x2'. Try ON or OFF, or nothing to toggle.",getAccessWords()[0],parm));
}
return false;
} | 8 |
public void startgame() {
if (running)
return;
h = new HavenPanel(800, 600);
add(h);
h.init();
try {
p = new haven.error.ErrorHandler(new ErrorPanel(), new URL("http", getCodeBase().getHost(), 80, "/java/error"));
} catch (java.net.MalformedURLException e) {
p = new ThreadGroup("Haven client");
}
synchronized (applets) {
applets.put(p, this);
}
Thread main = new HackThread(p, new Runnable() {
public void run() {
Thread ui = new HackThread(h, "Haven UI thread");
ui.start();
try {
while (true) {
Bootstrap bill = new Bootstrap();
if ((getParameter("username") != null) && (getParameter("authcookie") != null))
bill.setinitcookie(getParameter("username"), Utils.hex2byte(getParameter("authcookie")));
bill.setaddr(getCodeBase().getHost());
Session sess = bill.run(h);
RemoteUI rui = new RemoteUI(sess);
rui.run(h.newui(sess));
}
} catch (InterruptedException e) {
} finally {
ui.interrupt();
}
}
}, "Haven main thread");
main.start();
running = true;
} | 6 |
public void setTrain(Train value) {
this._train = value;
} | 0 |
public void setAccount(String account) {
this.account = account;
} | 0 |
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) { degrees--; }
if (e.getKeyCode() == KeyEvent.VK_O) { degrees++; }
if (e.getKeyCode() == KeyEvent.VK_RIGHT) { x++; }
if (e.getKeyCode() == KeyEvent.VK_LEFT) { x--; }
if (e.getKeyCode() == KeyEvent.VK_DOWN) { y++; }
if (e.getKeyCode() == KeyEvent.VK_UP) { y--; }
//Some println stuff
System.out.println(String.format("x: %d, y: %d, degrees: %d", x, y, degrees));
repaint(); } | 6 |
public boolean retirar(double cantidad){
if(cantidad > saldo){
if(cuentaAhorro == null)
return false;
else if((cantidad-saldo) > cuentaAhorro.getSaldo() )
return false;
else{
cantidad-=saldo;
saldo=0;
cuentaAhorro.retirar(cantidad);
return true;
}
}
else{
saldo -= cantidad;
return true;
}
} | 3 |
public static String getFileNameByFilePathJudgeSuffix(String filePath,boolean flag){
String name = null;
if(null != filePath && filePath.length() > 0){
String temp[] = filePath.replaceAll("\\\\","/").split("/");
if (temp.length >= 1) {
name = temp[temp.length - 1];
}
}
if(null != name && name.length() > 0){
if(!flag){
//不包含后缀
if(name.indexOf(".") != -1){
name = name.substring(0, name.lastIndexOf("."));
}
}
}
return name;
} | 7 |
void keepAlive () {
if (!isConnected) return;
long time = System.currentTimeMillis();
if (tcp.needsKeepAlive(time)) sendTCP(FrameworkMessage.keepAlive);
if (udp != null && udpRegistered && udp.needsKeepAlive(time)) sendUDP(FrameworkMessage.keepAlive);
} | 5 |
public Behaviour jobFor(Actor actor) {
//if ((! structure.intact()) || (! personnel.onShift(actor))) return null ;
final Choice choice = new Choice(actor) ;
//
// See if any new datalinks need to be installed or manufactured-
final Delivery baseC = Deliveries.nextCollectionFor(
actor, this, new Service[] { CIRCUITRY }, 5, null, world
) ;
if (baseC != null) {
choice.add(baseC) ;
}
final Manufacture m = stocks.nextManufacture(
actor, CIRCUITRY_TO_DATALINKS
) ;
if (m != null) {
choice.add(m) ;
}
final Manufacture o = stocks.nextSpecialOrder(actor) ;
if (o != null) {
choice.add(o) ;
}
//
// Check to see if any datalinks require delivery- if so, key them to the
// client first.
Batch <Venue> clients = new Batch <Venue> () ;
world.presences.sampleFromKey(this, world, 5, clients, Holding.class) ;
final Delivery baseD = Deliveries.nextDeliveryFor(
actor, this, services(), clients, 1, world
) ;
I.sayAbout(this, "Next base delivery is: "+baseD) ;
if (baseD != null) {
final Item custom = Item.withReference(DATALINKS, baseD.destination) ;
if (! stocks.hasItem(custom)) {
final Action personalise = new Action(
actor, baseD.destination,
this, "actionKeyDatalink",
Action.BUILD, "Personalising Datalinks"
) ;
personalise.setMoveTarget(this) ;
personalise.setPriority(Action.ROUTINE) ;
choice.add(personalise) ;
}
else choice.add(new Delivery(custom, this, baseD.destination)) ;
}
//
// Check to see if any catalogues require indexing-
final Item indexed = nextToCatalogue() ;
if (indexed != null) {
final Action catalogues = new Action(
actor, this,
this, "actionCatalogue",
Action.REACH_DOWN, "Indexing catalogue for "+indexed.type
) ;
catalogues.setPriority(Action.CASUAL) ;
choice.add(catalogues) ;
}
if (choice.size() > 0) return choice.weightedPick() ;
//
// Otherwise, just hang around and help folks with their inquiries-
return new Supervision(actor, this) ;
} | 7 |
@Override
public void propertyChange(PropertyChangeEvent e) {
JTable table = (JTable)e.getSource();
if (table == null) {
return;
}
String propertyName = e.getPropertyName();
if (propertyName.equals("enabled")) {
boolean isEnabled = table.isEnabled();
setVisible(isEnabled);
if (isEnabled) {
setWidth(table);
resetViewPosition(table);
}
} else if (propertyName.equals("font")) {
setFont(table.getFont());
} else if (propertyName.equals("rowHeight")) {
setRowHeight(table.getRowHeight());
} else if (propertyName.equals("model")) {
model.setRowCount(table.getRowCount());
} else if (propertyName.equals("unlinkedRowStatus")) {
repaint();
} else if (propertyName.equals("ancestor")) {
// empty
} else {
// empty
}
validate();
} | 8 |
public void AddStopMenuElement() {
if (elementStop != null)
return;
elementStop = APXUtils.addResource("stop_" + scrUniq, scrName,
scrTooltip, scrHotkey, APXUtils.resScript4, APXUtils.scriptRootRem,
new MenuElemetUseListener(new String(filename)) {
@Override
public void use(int button) {
if (info instanceof String) {
JSScriptInfo script = script_list.get(info);
script.Stop();
}
}
});
} | 2 |
public TreeContainerRow overDisclosureControl(int x, int y) {
if (mShowDisclosureControls && !mColumns.isEmpty()) {
if (x < mColumns.get(0).getWidth() + getColumnDividerWidth()) {
TreeRow row = overRow(y);
if (row instanceof TreeContainerRow) {
int right = INDENT * row.getDepth();
if (x <= right && x >= right - INDENT) {
return (TreeContainerRow) row;
}
}
}
}
return null;
} | 6 |
@Test
public void testJoinGame() {
// valid join
try {
games.joinGame(new JoinGameRequest(0, "blue"), "TestUser", 999);
assertEquals("Failed to add player name to empty game in games list.", "TestUser", games.listGames().get(0).getPlayerDescriptions().get(0).getName());
} catch (InvalidGamesRequest e) {
fail("Failed to accept valid joinGame request.");
}
boolean invalid = false;
try {
invalid = !games.joinGame(new JoinGameRequest(0, "invalid"), "TestUser", 999);
} catch (InvalidGamesRequest e) {
invalid = true;
}
assertTrue("Failed to catch invalid color in join game request.", invalid);
invalid = false;
try {
invalid = !games.joinGame(new JoinGameRequest(0, "blue"), "Bobby", 0);
} catch (InvalidGamesRequest e) {
invalid = true;
}
System.out.println(invalid);
assertTrue("Failed to catch duplicate color (already in use by another player) in join game request.", invalid);
invalid = false;
try {
invalid = !games.joinGame(new JoinGameRequest(1, "brown"), "TestUser", 11);
} catch (InvalidGamesRequest e) {
invalid = true;
}
assertTrue("Failed to catch/deny user request to join full game.", invalid);
} | 4 |
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer s = new StringBuffer( nf.format(number) );
if( s.length() > width ) {
if( s.charAt(0) == ' ' && s.length() == width + 1 ) {
s.deleteCharAt(0);
}
else {
s.setLength( width );
for( int i = 0; i < width; i ++ )
s.setCharAt(i, '*');
}
}
else {
for (int i = 0; i < width - s.length(); i++) // padding
s.insert(0,' ');
}
if( !trailing && decimal > 0 ) { // delete trailing zeros
while( s.charAt( s.length()-1 ) == '0' )
s.deleteCharAt( s.length()-1 );
if( s.charAt( s.length()-1 ) == '.' )
s.deleteCharAt( s.length()-1 );
}
return toAppendTo.append( s );
} | 9 |
public void updateAll( float delta )
{
update( delta );
for ( GameObject child : children )
child.updateAll( delta );
} | 1 |
private Expression cons( List<Expression> args, String caller ) {
if ( args.size() != 2 ) {
System.err.println("cons expected exactly two argument and got " + args.size() );
return new Void();
}
Expression evaledArg = args.get(0).eval(defSubst, caller);
Expression list = args.get(1).eval(defSubst, caller);
if ( list.getType().compareTo("quotelist") != 0 ) {
System.err.println("cons expected a quotelist as the second argument and got a " + list.getType() );
return new Void();
}
QuoteList ourList = (QuoteList) list;
// the elements of the list
List<Expression> elements = ourList.getElements();
// if the list is empty -> error
// otherwise -> return all but the first element of the list
elements.add(0, evaledArg );
QuoteList newList = new QuoteList(elements);
return newList.eval(defSubst, caller);
} | 2 |
public EvolscriptView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
} | 7 |
@Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == boton_alta_departamento ){
Controlador.getInstance().accion(EventoNegocio.GUI_ALTA_DEPARTAMENTO,GUIPrincipal_Departamento.this);
}
else if( e.getSource() == boton_baja_departamento){
Controlador.getInstance().accion(EventoNegocio.GUI_BAJA_DEPARTAMENTO, GUIPrincipal_Departamento.this);
}
else if( e.getSource() == boton_nomina_departamentos){
Controlador.getInstance().accion(EventoNegocio.GUI_CALCULAR_NOMINA_DEPARTAMENTO, GUIPrincipal_Departamento.this);
}
else if( e.getSource() == boton_modificar_departamento){
Controlador.getInstance().accion(EventoNegocio.GUI_MODIFICAR_DEPARTAMENTO, GUIPrincipal_Departamento.this);
}
else if (e.getSource() == boton_mostrar_departamento) {
Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_DEPARTAMENTO, GUIPrincipal_Departamento.this);
}else if (e.getSource() == boton_mostrar_lista_departamentos) {
Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_LISTA_DEPARTAMENTOS, GUIPrincipal_Departamento.this);
}
} | 6 |
private static int pivot(int[] a, int low, int high) {
int i1 = low, i2 = high - 1, i3 = (low + high) / 2;
int a1 = a[i1], a2 = a[i2], a3 = a[i3];
int n = (a1 > a2) ? a1 : a2;
int m = (a2 > a3) ? a2 : a3;
if (m > n) {
return (a1 > a2) ? i1 : i2;
} else if (n > m) {
return (a2 > a3) ? i2 : i3;
} else if (n == m) {
return (a1 > a3) ? i1 : i3;
}
return -1;
} | 8 |
@ChattingAnnotation(feature="Attachment", type="method")
@Override
public void fileSent(String sender, String fileName, byte[] fileData) {
if (!sender.equals(this.getTitle())) {
tvTranscript.setText("Recived a file " + fileName + "\n");
try {
saveFile(filePath + fileName, fileData);
} catch (Exception e) {
e.printStackTrace();
}
}
} | 2 |
public boolean isEvenlyDivisible(int num) {
boolean isIt = true;
for (int i = 2; i <= 20 && isIt; i++) {
if (!(num % i == 0)) {
isIt = false;
}
}
return isIt;
} | 3 |
public void dispose() {
if (edgeListLeftNeighbor != null || edgeListRightNeighbor != null) {
// still in EdgeList
return;
}
if (nextInPriorityQueue != null) {
// still in PriorityQueue
return;
}
edge = null;
leftRight = null;
vertex = null;
_pool.push(this);
} | 3 |
private Square[][] createArrayBoard()
{
int height, width;
height = inputBoard.size();
width = 0;
for(int x = 0; x < height; x++)
{
if(width < inputBoard.get(x).size())
{
width = inputBoard.get(x).size();
}
}
Square[][] board = new Square[height][width];
for(int x = 0; x < height; x++)
{
for(int y = 0; y < width; y++)
{
if(y < inputBoard.get(x).size())
{
board[x][y] = inputBoard.get(x).get(y);
}
else
{
board[x][y] = new Square(0);
}
}
}
return board;
} | 5 |
private static String getAllowedCharacters() {
StringBuilder sb;
InputStreamReader isr = new InputStreamReader(ChatAllowedCharacters.class.getResourceAsStream("/font.txt"), Charset.forName("UTF-8"));
try (BufferedReader var1 = new BufferedReader(isr)) {
String tmp;
sb = new StringBuilder();
while ((tmp = var1.readLine()) != null) {
if (!tmp.startsWith("#")) {
sb.append(tmp);
}
}
} catch (Exception var3) {
return "";
}
return sb.toString();
} | 3 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
long n = Long.parseLong(line.trim()), ans[] = new long[2];
if (n == 0)
break;
int con = 0;
for (int i = 0; i <= 32; i++)
if ((n & (1L << i)) != 0)
ans[con++ % 2] |= (n & (1L << i)) != 0 ? (1L << i) : 0;
out.append(ans[0] + " " + ans[1] + "\n");
}
System.out.print(out);
} | 6 |
public static void main(final String[] args) {
boolean displayConsole = true;
if (args.length > 0) {
// it has arguments
if (args.length == 1 && args[0].equalsIgnoreCase(Main.help)) {
System.out.println("Starts the KOI server");
System.out.println("\nArguments:");
System.out.println(Main.noConsoleArg + " - does not create "
+ "a seperate console.");
}
int i;
for (i = 0; i < args.length; ++i) {
if (args[i].equalsIgnoreCase(Main.noConsoleArg)) {
displayConsole = false;
}
}
}
final Editor g = new Editor();
g.init();
if (displayConsole) {
final Console c = new Console(EventManager.getInstance());
PackageManager.getInstance().loadPackage(c);
if (!PackageManager.getInstance().enableOnLoad()) {
if (!PackageManager.getInstance().isEnabled(c.getName())) {
PackageManager.getInstance().enable(c.getName());
}
}
}
final TaskManager manager =
new TaskManager(PackageManager.getInstance());
manager.setVisible(true);
} | 8 |
public ListNode rotateRight(ListNode head, int n) {
if (head == null || head.next == null || n == 0) {
return head;
}
int length = 0;
int steps = 0;
ListNode first = head;
ListNode second = head;
while (first != null) {
first = first.next;
length ++;
}
first = head;
n = n % length;
if (n == 0) {
return head;
}
while (first.next != null) {
first = first.next;
if (steps >= n) {
second = second.next;
}
steps ++;
}
if (steps >= n) {
ListNode newHead = second.next;
second.next = null;
first.next = head;
head = newHead;
}
return head;
} | 8 |
public LinkedList<Field> getAttackBorder() {
LinkedList<Field> fields = this.field.getAttackBorder();
if (fields == null) {
fields = new LinkedList<Field>();
for (Offset offset : Ant.attackBorder) {
boolean found = false;
if (!offset.getField(this.field).hasWater()) {
for (Offset o : Ant.attackOffsets.get(offset)) {
if (!o.getField(this.field).hasWater()) {
found = true;
break;
} else if (!o.getInverse().getField(
offset.getField(this.field)).hasWater()) {
found = true;
break;
}
}
}
if (found) {
fields.add(offset.getField(this.field));
}
}
this.field.setAttackBorder(fields);
}
return fields;
} | 7 |
public boolean nextTo( Point p ){
if( equals(p) ){
return true;
}
if( _x == p._x ){
if( _y == p._y+1 || _y == p._y-1 ){
return true;
}
}
if( _y == p._y ){
if( _x == p._x+1 || _x == p._x-1 ){
return true;
}
}
return false;
} | 7 |
public static Action create(String action){
Action actionObject = null;
String nomeClasse = "br.com.implementacaoObserverWeb.action." + action + "Action";
Class classe = null;
Object object = null;
try{
classe = Class.forName(nomeClasse);
object = classe.newInstance();
}catch(Exception ex){
return null;
}
if(!(object instanceof Action))
return null;
actionObject = (Action) object;
return actionObject;
} | 2 |
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
//Position de la souris
int posX = Mouse.getX();
int posY = Mouse.getY();
//background
bg.draw();
//positions et mouvements des projectiles
for (int i = 0; i < listAnimationProjectiles.size(); i++) {
listAnimationProjectiles.get(i).draw((int) (controleur.positionProjectileX(i)), (int) (controleur.positionProjectileY(i)));
// listAnimationProjectiles.get(i).getCurrentFrame().setRotation((float) (controleur.orientationProjectil(controleur.listProjectiles().get(i))));
}
//positions et mouvements des structures
for (int i = 0; i < listImagesStructures.size(); i++) {
listImagesStructures.get(i).draw((int) (controleur.positionStructureX(i)), (int) (controleur.positionStructureY(i)));
}
//Stats sur force, angle et les positions du curseur
g.setColor(Color.black);
g.drawString("force: " + force, 300, 100);
g.drawString("angle: " + Math.toDegrees((Math.atan((double) posY / posX))), 300, 150);
g.drawString("" + Mouse.getX() + ", " + Mouse.getY(), 300, 200);
//boutons
buttonInventaire.draw(10, 600);
buttonPlay.draw(100, 600);
buttonExit.draw(1110, 5);
//canon
canon.draw(85 - 195, 500 + 7);
roue.draw(35, 506 + 7);
//barre de force
g.fillRect(100, 250, (int) force, 20);
//lorsque l'inventaire est ouvert (fin mouvement structure)
if (inventaire) {
//dessiner le menu de l'inventaire et le bouton exit
g.setColor(colorAlpha);
g.fillRoundRect(0, 80, 475, 505, 30);
inventaireExit.draw(435, 55);
cibleAnimation.draw(35, 105);
structure.draw(35, 165);
}
// FIN INVENTAIRE
} | 3 |
@Test
public void testCheckLabChoices(){
//Initialize a boolean saying there are no students who have no first choices and aren't flagged.
boolean startEmptyFirstChoices = true;
//For each student
for(Student s: students){
//If a student has no first choices and isn't flagged
if(s.getFirstChoiceLabs().isEmpty()){
if(s.getFlaggedForLabs() == false){
//Set boolean to false
startEmptyFirstChoices = false;
}
}
}
//Run data through a StudentChoiceOrder
StudentChoiceOrder sco = new StudentChoiceOrder(students);
//Initialize a boolean saying there are no students who have no first choices and aren't flagged.
boolean endEmptyFirstChoices = true;
//For each student
for (Student s : sco.getStudents()){
//If a student has no first choices
if(s.getFirstChoiceLabs().isEmpty()){
//Ignore if they have no choices and are flagged
if(s.getFlaggedForLabs()==true && s.getSecondChoiceLabs().isEmpty() && s.getThirdChoiceLabs().isEmpty()){}
//Otherwise
else {
//Set boolean to false
endEmptyFirstChoices = false;
}
}
}
//Show that the method started with students lacking first choices, and was modified so all students were
assertTrue(!startEmptyFirstChoices);
assertTrue(endEmptyFirstChoices);
} | 8 |
@Override
public void actionPerformed(ActionEvent e) {
if (held) {
if (this.pressed) {
heldStatus.put(this.name, true);
} else {
heldStatus.put(this.name, false);
}
} else {
if (this.pressed && !toggleStatus.get(this.name)) {
toggleStatus.put(this.name, true);
action();
} else if (!this.pressed) {
toggleStatus.put(this.name, false);
}
}
} | 5 |
private void pullStack(){
NetworkMessage m = messageQueue.poll();
if(m == null)
return;
try
{
Socket client = new Socket(m.getReceiver() , m.getPort() );
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
//out.writeUTF(m.getString());
switch (m.type){
case NetworkMessage.TYPE_FILE:
String address = m.content.replaceAll("@PATH:", "");
// address= "/Users/anttikulppi/Documents/Trabajo/Brainshots/rails data.txt";
// address= "/Users/anttikulppi/Pictures/d.jpg";
File f = new File(address );
NetworkMessage m2 = new NetworkMessage(NetworkMessage.TYPE_FILE, m.gameInstance, f.getName() );
System.out.println(m2.content);
System.out.println("FILE START SEND");
out.writeBytes(m2.getString()+"!#!");
client.close();
client = new Socket(m.getReceiver() , m.getPort() );
outToServer = client.getOutputStream();
out = new DataOutputStream(outToServer);
streamFile(f,out);
client.close();
System.out.println("filestream");
break;
default:
// System.out.println("enviando ##" + m.getString());
out.writeBytes(m.getString());
client.close();
break;
}
//client.close();
}catch(Exception e)
{
messageQueue.add(m);
}
} | 3 |
public CtrlVisiteurs getCtrl() {
return ctrlV;
} | 0 |
public ContentResponse send() throws InterruptedException, ExecutionException, TimeoutException, IOException {
String urlRequest = baseUri + resource;
Request httpRequest = httpClient
.newRequest(urlRequest)
.param("access_token", token);
for (String key : headers.keySet()) {
String value = headers.get(key);
httpRequest.header(key,value);
}
for (String key : params.keySet()){
String value = params.get(key);
httpRequest.param(key,value);
}
httpRequest.method(method);
if (payload != null)
httpRequest.content(payload);
if (token == null){
token = oAuth.getNewToken();
}
ContentResponse response = httpRequest.send();
if (response.getStatus() == 403){
token = oAuth.getNewToken();
response = httpRequest.send();
}
return response;
} | 5 |
private static void traverseTree(Tree tree) {
TreeItem[] treeItems = tree.getItems();
for (TreeItem treeItem : treeItems) {
traverseNode(treeItem);
}
} | 1 |
public Move move(boolean[] foodpresent, int[] neighbors, int foodleft, int energyleft) throws Exception {
Move m = null; // placeholder for return value
// this player selects randomly
int direction = rand.nextInt(6);
switch (direction) {
case 0: m = new Move(STAYPUT); break;
case 1: m = new Move(WEST); break;
case 2: m = new Move(EAST); break;
case 3: m = new Move(NORTH); break;
case 4: m = new Move(SOUTH); break;
case 5: direction = rand.nextInt(4);
// if this organism will reproduce:
// the second argument to the constructor is the direction to which the offspring should be born
// the third argument is the initial value for that organism's state variable (passed to its register function)
if (direction == 0) m = new Move(REPRODUCE, WEST, state);
else if (direction == 1) m = new Move(REPRODUCE, EAST, state);
else if (direction == 2) m = new Move(REPRODUCE, NORTH, state);
else m = new Move(REPRODUCE, SOUTH, state);
}
return m;
} | 9 |
public Proffession getProffession() {return proffession;} | 0 |
public String encodeValues() throws EncodeException {
StringBuilder res = new StringBuilder();
if (this.values != null && this.values.length > 0) {
for (Object value : this.values) {
if (value instanceof Integer) {
res.append("int:");
} else if (value instanceof Double) {
res.append("dbl:");
} else if (value instanceof Character) {
res.append("chr:");
} else if (value instanceof String) {
res.append("str:");
} else if (value == null) {
res.append("nul:");
} else {
throw new EncodeException("Unsupported variable type");
}
}
res.replace(res.length()-1, res.length(), "");
res.append("><");
for (Object value : this.values) {
res.append(value).append(':');
}
res.replace(res.length()-1, res.length(), "");
} else {
res.append("emp><");
}
return res.toString();
} | 9 |
@Override
public void run() {
do{
field.repaint();
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1/ticks));
} catch (InterruptedException e) {
e.printStackTrace();
}
}while(running);
} | 2 |
@Override
protected boolean judgeResult(CardGroup cardGroup) {
cardGroup.doSort(CardGroupSortType.DECREASE);
boolean result = true;
int score = cardGroup.getCard(0).getType();
for(int i = 0; i <cardGroup.size()-1 ; i += 2 , score --) {
if( score != cardGroup.getCard(i+1).getType() || ((i + 2)<cardGroup.size() && score != cardGroup.getCard(i+2).getType() + 1)){
result = false;
break;
}
}
return result;
} | 4 |
private void createInverter(String in, String out)
{
Inverter inverter = new Inverter();
// Connect the input
// Check if the in wire is an input
if (stringToInput.containsKey(in))
{
Wire inWire = new Wire();
stringToInput.get(in).connectOutput(inWire);
inverter.connectInput(inWire);
}
// Check if the in wire is an output
else if (stringToOutput.containsKey(in))
{
Wire inWire = new Wire();
stringToOutput.get(in).connectOutput(inWire);
inverter.connectInput(inWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(in))
inverter.connectInput(stringToWire.get(in));
else
MainFrame.showError("Error, the wire " + in
+ " isn't in the circuit");
// Connect the output
// Check if the in wire is an output
if (stringToOutput.containsKey(out))
{
Wire outWire = new Wire();
stringToOutput.get(out).connectInput(outWire);
inverter.connectOutput(outWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(out))
inverter.connectOutput(stringToWire.get(out));
else
MainFrame.showError("Error, the wire " + out
+ " isn't in the circuit");
gates.add(inverter);
} | 5 |
private void updateGcCapacity(GcCapacity gcCapacity) {
if(gcCap == null)
this.gcCap = gcCapacity;
else {
if(gcCap.getEC() > gcCapacity.getEC())
gcCap.setEC(gcCapacity.getEC());
if(gcCap.getNGC() > gcCapacity.getNGC())
gcCap.setNGC(gcCapacity.getNGC());
if(gcCap.getOGC() > gcCapacity.getOGC()) {
gcCap.setOGC(gcCapacity.getOGC());
gcCap.setOC(gcCapacity.getOGC());
}
if(gcCap.getPGC() > gcCapacity.getPGC()) {
gcCap.setPGC(gcCapacity.getPGC());
gcCap.setPC(gcCapacity.getPGC());
}
if(gcCap.getS0C() > gcCapacity.getS0C())
gcCap.setS0C(gcCapacity.getS0C());
if(gcCap.getS1C() > gcCapacity.getS1C())
gcCap.setS1C(gcCapacity.getS1C());
}
} | 7 |
private int getControlPosition(int controlType) throws Exception{
ArrayList<Integer> controls = new ArrayList<Integer>();
for(Surface surface: this.getSurfaces()){
for(Section section: surface.getSections()){
for(Control control: section.getControls()){
if (!controls.contains(control.getType())){
if (control.getType() == controlType) {
int position = controls.size();
logger.log(Level.FINE, "Control {0} found at {1}", new Object[]{controlType, position});
return position;
}
controls.add(control.getType());
}
}
}
}
return -1;
} | 5 |
public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_W))
{
position.add(new Vector2f(0,-MOTION_SPEED*delta));
body.setPosition(position.getX(),position.getY());
if (sprites.get("reverse") != null)
curImage = sprites.get("reverse");
}
if (input.isKeyDown(Input.KEY_A))
{
position.add(new Vector2f(-MOTION_SPEED*delta,0));
body.setPosition(position.getX(),position.getY());
if (sprites.get("side") != null)
curImage = sprites.get("side");
}
if (input.isKeyDown(Input.KEY_S))
{
position.add(new Vector2f(0,MOTION_SPEED*delta));
body.setPosition(position.getX(),position.getY());
if (sprites.get("forward") != null)
curImage = sprites.get("forward");
}
if (input.isKeyDown(Input.KEY_D))
{
position.add(new Vector2f(MOTION_SPEED*delta,0));
body.setPosition(position.getX(),position.getY());
if (sprites.get("side") != null)
curImage = sprites.get("side");
}
} | 8 |
public void replacePast() {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Entity past_string = null;
try {
past_string = datastore.get(KeyFactory.createKey("past_string",
"onlyOne"));
} catch (EntityNotFoundException e) {
}
String[] string_box = ((Text) past_string.getProperty("text"))
.getValue().split(",");
StringBuilder sb = new StringBuilder();
Pattern p = Pattern.compile(" ");
for (int i = 0; i * 4 + 4 < string_box.length; i++) {
if (p.matcher(string_box[i * 4 + 1]).find()
|| p.matcher(string_box[i * 4 + 2]).find())
continue;
sb.append("," + string_box[i * 4 + 1])
.append("," + string_box[i * 4 + 2])
.append("," + string_box[i * 4 + 3])
.append("," + string_box[i * 4 + 4]);
}
past_string.setProperty("text", new Text(new String(sb)));
if(false)datastore.put(past_string);
} | 5 |
public void collisionUpdate(int i, int j, int k, int l) {
Obstacle[][] obs = level.getObstacles();
boolean collideBad = true;
if (i+(height/Obstacle.getHeight())+ 1>=obs.length) { // Out of the drawing.
dead = true;
System.out.println("Below the box");
} else {
collisionSide(obs,i,j,k,l);
collideBad &= collisionFeet(obs,j,k);
collideBad &= collisionHead(obs,i,j,k);
if (collideBad)
System.out.println("BAD COLLISION");
}
} | 2 |
public Frame parse(ByteBuffer downloadBuffer) throws WebSocketException {
ByteBuffer buffer = null;
try {
if (State.DONE.equals(state)) {
transitionTo(State.HEADER);
buffer = downloadBuffer;
} else {
buffer = bufferManager.getBuffer(downloadBuffer);
}
if (State.HEADER.equals(state)) {
int position = buffer.position();
header = createFrameHeader(buffer);
if (header == null) {
buffer.position(position);
bufferManager.storeFragmentBuffer(buffer);
return null;
}
if (header.getContentsLength() - 1 > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"large data is not support yet");
}
transitionTo(State.FRAME);
}
if (State.FRAME.equals(state)) {
if (header.getContentsLength() > buffer.remaining()) {
bufferManager.storeFragmentBuffer(buffer);
return null;
}
byte[] bodyBuf = new byte[(int) header.getContentsLength()];
buffer.get(bodyBuf, 0, bodyBuf.length);
Frame frame = createFrame(header, bodyBuf);
transitionTo(State.DONE);
bufferManager.init();
header = null;
return frame;
}
return null;
} finally {
if (buffer != null && buffer != downloadBuffer) {
downloadBuffer.position(downloadBuffer.limit()
- buffer.remaining());
}
}
} | 8 |
public void setSolEstado(String solEstado) {
this.solEstado = solEstado;
} | 0 |
@Override
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if(obj == null)
{
return false;
}
if(!(obj instanceof TSLObject))
{
return false;
}
TSLObject other = (TSLObject) obj;
return objects_map.equals(other.objects_map) && strings_map.equals(other.strings_map);
} | 4 |
private void popWall(MansionArea room, boolean isRoom){
//each wall can contain only one item, and must contain one item
if (isRoom){
if (room.getNorth() == null){
room.addItem(wallItems.getItem(Face.NORTHERN));
}
if (room.getEast() == null){
room.addItem(wallItems.getItem(Face.EASTERN));
}
if (room.getSouth() == null){
room.addItem(wallItems.getItem(Face.SOUTHERN));
}
if (room.getWest() == null){
room.addItem(wallItems.getItem(Face.WESTERN));
}
} else {
//halls use a different item list
if (room.getNorth() == null){
room.addItem(hallWallItems.getItem(Face.NORTHERN));
}
if (room.getEast() == null){
room.addItem(hallWallItems.getItem(Face.EASTERN));
}
if (room.getSouth() == null){
room.addItem(hallWallItems.getItem(Face.SOUTHERN));
}
if (room.getWest() == null){
room.addItem(hallWallItems.getItem(Face.WESTERN));
}
}
} | 9 |
public static SampleSet generateData(final int bits, final Random rnd) {
//
final SampleSet result = new SampleSet();
//
final double[] input = new double[bits];
final double[] output = new double[2];
//
final int samples = 1 << bits;
//
for (int i = 0; i < samples; i++) {
//
// add 1 bit to bit-string.
//
for (int j = 0; j < bits; j++) {
if (input[j] == OFF) {
//
// 0**** -> 1****
//
input[j] = ON;
break;
} else {
//
// *1**** -> *0****
//
input[j] = OFF;
}
}
//
// generate parity sample
//
boolean parity = true;
//
for (int j = 0; j < bits; j++) {
if (input[j] == ON) {
parity = !parity;
}
}
//
if (parity) {
output[CLASS_EVEN] = ON;
output[CLASS_ODD] = OFF;
} else {
output[CLASS_EVEN] = OFF;
output[CLASS_ODD] = ON;
}
//
result.add(new Sample(input.clone(), output.clone()));
}
//
Collections.shuffle(result, rnd);
//
return result;
} | 6 |
public Map<Long, Link> getLinks(AreaBox box) {
String queryString;
ResultSet resultSet = null;
HashMap<Long, Link> links;
links = new HashMap<Long, Link>();
queryString = String.format("SELECT id, crossing_id_from, crossing_id_to, meters, lsiclass, tag, maxspeed, long_from, lat_from FROM link WHERE"
+ box.getSqlBetweenStatement("long_from", "lat_from"));
resultSet = this.query(queryString);
try {
while (resultSet.next()) {
long db_id = resultSet.getLong(1);
long db_crossingFrom = resultSet.getLong(2);
long db_crossingTo = resultSet.getLong(3);
int db_meters = resultSet.getInt(4);
int db_lsiClass = resultSet.getInt(5);
String db_tag = resultSet.getString(6);
int db_maxspeed = resultSet.getInt(7);
// keine Einbahnstrassen und nur Autostrassen hinzufuegen
if (!db_tag.equalsIgnoreCase("C") && (db_lsiClass / 100000 == 341)) {
links.put(db_id, new Link(db_crossingFrom, db_crossingTo, db_meters, db_lsiClass, db_maxspeed));
}
}
resultSet.close();
} catch (SQLException e) {
System.out.println("Error query DB: " + e.toString());
e.printStackTrace();
System.exit(1);
}
return links;
} | 4 |
public void onEnable() {
//Basic plugin setup
Server = getServer();
log = Server.getLogger();
setPdfFile(this.getDescription());
//load up our files if they don't exist
moveFiles();
setupPermissions();
//Load our flat file player DB
questPlayerStorage = new iProperty("plugins/uQuest/uQuest_Players.txt");
//Check if we need to convert old uQuest v1 quests
if(new File("plugins/uQuest/uQuest_Quests.txt").exists())
new QuestConverter();
//registerCommands
if(isUseDefaultUQuest()){
Cmd_uquest cmd_uquest = new Cmd_uquest(this);
getCommand("uquest").setExecutor(cmd_uquest);
getCommand("quest").setExecutor(cmd_uquest);
//Have had other plugins like "Questioner" that conflict with /q
try{
getCommand("q").setExecutor(cmd_uquest);
} catch(NullPointerException npe) {
useDefaultHelp = false;
}
}
setupEconomy();
//These commands exist even if they are not using the default uQuest
Cmd_reloadquests cmd_reloadquests = new Cmd_reloadquests(this);
getCommand("reloadquests").setExecutor(cmd_reloadquests);
Cmd_reloadquestconfig cmd_reloadquestconfig = new Cmd_reloadquestconfig(this);
getCommand("reloadquestconfig").setExecutor(cmd_reloadquestconfig);
// setup config
readConfig();
// load quests into array
theQuestsLoadAllIntoArray();
//Make sure we have quests loaded!
if(this.theQuests.isEmpty()){
System.err.println("\n\n\n" + pluginNameBracket() + " You have an empty quest list!\n Disabling plugin.\n\n\n");
Server.getPluginManager().disablePlugin(this);
return; //exit out of our enable method
}
//Get the DB fired up
if(isUseSQLite() == true){
this.setDB(new SqLiteKeyValStor<Quester>("questers", "plugins/uQuest/uQuestQuesters"));
System.out.println(pluginNameBracket() + " Loaded with SQLite!");
}
// start the player saving timer
if (firstLoad == true && isUseSQLite() == false) {
timerSavePlayers();
firstLoad = false;
System.out.println(pluginNameBracket() + " Loaded with Flatfile!");
}
// Register Bukkit Hooks
registerEvents();
System.out.println(pluginNameBracket() + " v" + getPdfFile().getVersion() + " enabled! With " + this.getQuestInteraction().getQuestTotal() + " quests loaded!");
// no longer necessary, Vault takes care of all this for us now. -morganm 3/3/11
// pluginSupport = new PluginSupport(this);
// //For iCon at least, it hooks in after the plugin enables. Solution: Timer!
// ScheduledThreadPoolExecutor onEnable_Timer = new ScheduledThreadPoolExecutor(1);
// onEnable_Timer.schedule(new Runnable() {
// public void run() {
// pluginSupport.link();
// pluginSupport.checkPluginSupport();
// }
// }, pluginTimerCheck, TimeUnit.SECONDS);
} | 7 |
public void create(Cliente cliente) throws PreexistingEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(cliente);
em.getTransaction().commit();
} catch (Exception ex) {
if (findCliente(cliente.getCpf()) != null) {
throw new PreexistingEntityException("Cliente " + cliente + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} | 3 |
public static DataSource inputDataFrom(final Object object) throws IOException {
if (object instanceof DataSource) return (DataSource)object;
if (object instanceof File) return IO._inputDataFrom_((File)object);
if (object instanceof RandomAccessFile) return IO._inputDataFrom_((RandomAccessFile)object);
if (object instanceof ByteArraySection) return IO._inputDataFrom_((ByteArraySection)object);
if (object instanceof ByteArray) return IO._inputDataFrom_((ByteArray)object);
if (object instanceof byte[]) return IO._inputDataFrom_((byte[])object);
if (object instanceof DataInput) return IO._inputDataFrom_((DataInput)object);
if (object instanceof InputStream) return IO._inputDataFrom_((InputStream)object);
if (object instanceof ByteBuffer) return IO._inputDataFrom_((ByteBuffer)object);
throw new IOException();
} | 9 |
private void createOutput(){
double maxLog2Score = 0;
double minLog2Score = 0;
//Determine maximum and minimum score
for(BedLine bl: bedLines){
if(bl.getLog2() > maxLog2Score){
maxLog2Score = bl.getLog2();
}
if(bl.getLog2() < minLog2Score){
minLog2Score = bl.getLog2();
}
}
//Set each lines color based on its proportion to the maximum/minimum score.
for(BedLine bl: bedLines){
if(bl.getLog2() > 0){
bl.setColor(0, (int)((bl.getLog2() / maxLog2Score) * 255), 0);
}else{
bl.setColor((int)((bl.getLog2() / minLog2Score) * 255), 0, 0);
}
}
//Writing to HDD related variables
StringBuffer sb;
BufferedWriter out;
try {
sb = new StringBuffer();
out = new BufferedWriter(new FileWriter(outputDir + inputFile.substring(inputFile.lastIndexOf('/')) + ".bed"));
//This information is necessary for colors to be displayed in the UCSC browser
sb.append("track itemRgb='On'" + "\n");
//Write each bed line to the string buffer
for(BedLine bl: bedLines){
sb.append(bl.toString() + "\n");
}
//Write the string buffer to the file.
out.write(sb.toString());
//Flush and close the stream to ensure all data was written to disk.
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//Catch
}//createOutput | 7 |
public synchronized void add(Range r) {
Set<Range> toDelete = new HashSet<Range>();
boolean span = false;
for(Range currentRange: this.ranges) {
if (r.getLow() <= currentRange.getHigh() + 1 && r.getLow() >= currentRange.getLow()) {
// if the current range will merge with the low-end of r, set r's low to currentRange's low and delete currentRange
r.setLow(currentRange.getLow());
toDelete.add(currentRange);
span = true;
} else if (r.getHigh() >= currentRange.getLow() - 1 && r.getHigh() <= currentRange.getHigh()) {
// if the current range will merge with the high-end of r, set r's high to currentRange's high and delete currentRange
r.setHigh(currentRange.getHigh());
toDelete.add(currentRange);
span = false;
} else if (span && currentRange.getHigh() < r.getHigh()) {
// if currentRange is spanned entirely by r
toDelete.add(currentRange);
}
}
// do not allow reading of this.ranges while we perform the adds and deletes
this.lock.writeLock().lock();
try {
this.ranges.removeAll(toDelete);
this.ranges.add(r);
} finally {
this.lock.writeLock().unlock();
}
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MethodParamBinding other = (MethodParamBinding) obj;
if (argumentCount != other.argumentCount)
return false;
if (message != other.message)
return false;
if (methodName == null) {
if (other.methodName != null)
return false;
} else if (!methodName.equals(other.methodName))
return false;
return true;
} | 8 |
public double getGeneration() {
return generation;
} | 0 |
@Override
public boolean click(int mx, int my, boolean click)
{
if (mouseIn(mx, my) && click)
{
if (!clicked)
{
formDown=!formDown;
clicked = true;
return true;
}
clicked = true;
return false;
}
if(formDown)
{
mouseOver(mx,my);
if(click==true&&overSel>=0)
{
setIndex(overSel);
formDown=false;
clicked=false;
return true;
}
}
else
overSel=-1;
if(click)
formDown=false;
clicked = false;
return false;
} | 7 |
public void delete(Juego juego){
Partida partida = selectPartida(juego);
List<Nave> naves = partida.getNaves();
List<Escudo> escudos = partida.getEscudos();
List<Invasor> invasores = partida.getInvasores();
try {
label.setText(format("Borrando juego ..."));
juegoDao.delete(juego);
label.setText(format("Borrando naves ..."));
for(Nave n: naves) naveDao.delete(n);
label.setText(format("Borrando escudos ..."));
for(Escudo e: escudos) escudoDao.delete(e);
label.setText(format("Borrando invasores ..."));
for(Invasor i: invasores) invasorDao.delete(i);
label.setText(format("Partida borrada con éxito."));
} catch (SQLException ex) {
Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
}
} | 4 |
private void createDB() {
Connection connection = null;
PreparedStatement statement = null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1/xmltojdbc", "root", "root");
statement = (PreparedStatement) connection.prepareStatement("INSERT INTO tariffs " + columnList +
" VALUES(?,?,?,?,?,?,?,?,?,?)");
for(int i = 0; i < data.size(); i++){
statement.setString(1, data.get(i).getName());
statement.setString(2, data.get(i).getOperatorName());
statement.setDouble(3, data.get(i).getPayroll());
statement.setDouble(4, data.get(i).getSmsPrice());
statement.setDouble(5, data.get(i).getCallPrice().getIntraCallPrice());
statement.setDouble(6, data.get(i).getCallPrice().getExternalCallPrice());
statement.setDouble(7, data.get(i).getCallPrice().getLandLineCallPrice());
statement.setBoolean(8, data.get(i).getParameter().isHasFavouriteNumber());
statement.setString(9, data.get(i).getParameter().getTypeTariff());
statement.setDouble(10, data.get(i).getParameter().getGetOperatorPrice());
statement.executeUpdate();
}
} catch (SQLException e) {
logger.error("SQL working error: " + e.getMessage());
} catch (ClassNotFoundException e) {
logger.error("Incorrect driver: " +e.getMessage());
}
finally {
try{
if(connection != null){ connection.close();}
if(statement != null) {statement.close();}
} catch (SQLException e) {
logger.error("SQL closing error: " + e.getMessage());
}
}
} | 6 |
@Override
public boolean equals(Object obj){
if (obj instanceof Circle){
Circle o = (Circle)obj;
if (pnt.x-rad/2<o.pnt.x && pnt.x+rad/2>o.pnt.x && pnt.y-rad/2<o.pnt.y && pnt.y+rad/2>o.pnt.y ||
pnt.x-rad/2>o.pnt.x && pnt.x+rad/2<o.pnt.x && pnt.y-rad/2>o.pnt.y && pnt.y+rad/2<o.pnt.y)
return true;
else
return false;
}else
return false;
} | 9 |
private void runStatement(Map<Point, Set<Integer>> geoTags, Map<GeoTag, PointTag> tagMap){
GeospatialData [] data = null;
// get multi-data from DB:
if (loader.loadingFeatures){
data = db.getMultiHorizons(geoTags, loader.srdsSource.srdsSrcID);
}
else{
////// TO DO >>>> db.getMultiTraces_v3
}
if (data == null){
System.err.println("Data array is null, nothing was returned from DB!!");
return;
}//if
// loop through data array
for (int i=0; i < data.length; i++){
// increment db visit count:
loader.incrementDbVisitCount();
// [28/5/2012] Note: if knowing data coordinates in advance, then all returned data units are non-null:
if (data[i] == null){
System.err.println("data [" + i + "] is null!!"); // shouldn't happen
loader.incrementEmptyUnitsCount();
continue;
}
// current associated tag:
PointTag tag = tagMap.get(data[i].geoTag);
// compute location of trace in texture (s,t):
int s = tag.x - this.xLRef;
int t = tag.y - this.yLRef;
// upload texture buffer & FESVo:
// ------------------------------
// if loading features:
if (loader.loadingFeatures){
if (loader.loadAtLowerResolution)
loader.uploadTextureBufferAtLowerResolution(s, t, lod, (Feature)data[i], tag.sourceID);
else
loader.uploadTextureBuffer(s, t, (Feature)data[i], tag.sourceID);
FESVo.putHorizon((Feature)data[i], tag, lod);
//[TEST]
// System.out.println(tag.sourceID + ", " + tag.x + ", " + tag.y + ", " + data[i].geoTag.x + ", " + data[i].geoTag.y);
}
// if loading a trace:
else{
if (loader.loadAtLowerResolution)
loader.uploadTextureBufferAtLowerResolution(s, t, lod, (Trace)data[i]);
else
loader.uploadTextureBuffer(s, t, (Trace)data[i]);
FESVo.putTrace((Trace)data[i], tag, lod);
}
}
}//runStatement | 7 |
private static ArrayList<Integer> getPredictor(int windowLen, int[] finalCluster, int VERBOSE) {
int logFlag = Constants.LOG_PREDICTOR;
// get the last W
int[] keySequence = new int[windowLen];
for (int i=finalCluster.length-windowLen; i<finalCluster.length; i++) {
keySequence[i-finalCluster.length+windowLen] = finalCluster[i];
}
Util.logPrintln(VERBOSE, logFlag, "keySeq: "+Util.arrayToStr(keySequence));
// search for predictor
// the result is the index in the training set
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i=0; i<finalCluster.length-windowLen; i++) {
// move forward W element from i if we can get the same sequence as keySequence
int[] newSeq = new int[windowLen];
for (int j=0; j<windowLen; j++ ){
newSeq[j] = finalCluster[i+j];
}
boolean equal = Util.isEqual(keySequence, newSeq);
Util.logPrintln(VERBOSE, logFlag, "newSeq: " + Util.arrayToStr(newSeq)+": "+equal);
if ( equal==true ) result.add(i+windowLen);
}
return result;
} | 4 |
private void compute_pcm_samples5(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[5 + dvp] * dp[0]) +
(vp[4 + dvp] * dp[1]) +
(vp[3 + dvp] * dp[2]) +
(vp[2 + dvp] * dp[3]) +
(vp[1 + dvp] * dp[4]) +
(vp[0 + dvp] * dp[5]) +
(vp[15 + dvp] * dp[6]) +
(vp[14 + dvp] * dp[7]) +
(vp[13 + dvp] * dp[8]) +
(vp[12 + dvp] * dp[9]) +
(vp[11 + dvp] * dp[10]) +
(vp[10 + dvp] * dp[11]) +
(vp[9 + dvp] * dp[12]) +
(vp[8 + dvp] * dp[13]) +
(vp[7 + dvp] * dp[14]) +
(vp[6 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} | 1 |
public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
} | 2 |
public static void main(String args []){
Board b = new Board();
Move m = new Move();
boolean player1 = true;
//A loop that runs until the board is full or someone has won.
//In each iteration we print the board, call insertMove and change whos turn it is.
while((!b.isFull(b.fields)) && (!b.hasWon(b.fields))){
b.PrintBoard(b.fields);
if(player1){
System.out.println("It's your turn Player 1!");
m.insertMove(1, b.fields);
}
else{
System.out.println("It's your turn Player 2!");
m.insertMove(2, b.fields);
}
if(player1){
player1 = false;
}
else{
player1 = true;
}
}
//Prints out the final board and reveals the result.
b.PrintBoard(b.fields);
if(b.isTie(b.fields)){
System.out.println("DRAW!");
}
else{
if(!player1){
System.out.println("VICTORY for Player 1");
}
else{
System.out.println("VICTORY for Player 2");
}
}
} | 6 |
public void popularCmbDepartamentoBuscar() {
ArrayList<String> Departamentos = new ArrayList<>();
DepartamentoBO departamentoBO = new DepartamentoBO();
if (userLogado.getTipo().equals("Diretor")) {
try {
Departamentos = departamentoBO.ComboBoxDepartamentos();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao popular o departamento",
"Departamento", JOptionPane.ERROR_MESSAGE);
}
} else {
try {
Departamentos = departamentoBO.CMBDepartamento(userLogado.getDepartamento().getCodigo());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao popular o departamento",
"Departamento", JOptionPane.ERROR_MESSAGE);
}
}
cmbBuscaFuncionario.removeAllItems();
cmbBuscaFuncionario.addItem("Selecione");
for (String item : Departamentos) {
cmbBuscaFuncionario.addItem(item);
}
} | 4 |
public Point[] fast (Point[] ptArr, int numPoints, int pointer){
Point origin = ptArr[0];
ptArr[0] = null;
int slope;
Hashtable<Integer, ArrayList<Point>> table = new Hashtable<Integer, ArrayList<Point>>();
for( int i = 1; i < numPoints; i++ ){
if(ptArr[i] == null) continue;
slope = (int) (100.0 * origin.slopeTo(ptArr[i]));
if ( table.containsKey(slope) ) {
table.get(slope).add(ptArr[i]);
}
else {
table.put(slope, new ArrayList<Point>());
table.get(slope).add(origin);
table.get(slope).add(ptArr[i]);
}
ptArr[i] = null;
}
Enumeration<ArrayList<Point>> enumeration = table.elements();
ArrayList<Point> alPoint;
pointer = 0;
numPoints = 0;
while( enumeration.hasMoreElements() ) {
alPoint = enumeration.nextElement();
if ( alPoint.size() >= 4 ){
for(int i = 0; i < alPoint.size(); i++) {
//origin.drawTo(alPoint.get(i));
StdOut.print(alPoint.get(i));
}
StdOut.print("\n");
}
else {
for(int i = 1; i < alPoint.size(); i++) {
ptArr[pointer++]= alPoint.get(i);
numPoints++;
}
}
}
return ptArr;
} | 7 |
public static int findMin(int[] num) {
if (null == num || 0 == num.length) return -1;
int low = 0, high = num.length - 1;
if (1 == num.length) return num[0];
if (num[low] < num[high]) return num[low];
while (low <= high) {
if (low + 1 == high)
return num[low] > num[high] ? num[high] : num[low];
int mid = (low + high) / 2;
if (num[mid] > num[low]) low = mid;
else high = mid;
}
return num[low];
} | 8 |
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
int confirmar = JOptionPane.showConfirmDialog(null, "Deseja Salvar?","Deseja Salvar?", JOptionPane.OK_CANCEL_OPTION);
if (JOptionPane.OK_OPTION == confirmar){
if(txtDescricao.getText().isEmpty() ){
JOptionPane.showMessageDialog(rootPane, "O campo Descrição deve ser preenchido");
}
if(txtNome.getText().isEmpty() ){
JOptionPane.showMessageDialog(rootPane, "O campo Nome deve ser preenchido");
}
if(txtQtd.getText().isEmpty() ){
JOptionPane.showMessageDialog(rootPane, "O campo Quantidade deve ser preenchido");
}
if(txtValor_Compra.getText().isEmpty() ){
JOptionPane.showMessageDialog(rootPane, "O campo Valor Compra deve ser preenchido");
}
if(txtValor_Venda.getText().isEmpty() ){
JOptionPane.showMessageDialog(rootPane, "O campo Valor Venda deve ser preenchido");
}
else {
Produto produto = new Produto();
try {
produto.setDescricao(txtDescricao.getText());
produto.setNome(txtNome.getText());
produto.setValor_unitario_compra(Double.parseDouble(txtValor_Compra.getText()));
produto.setValor_unitario_venda(Double.parseDouble(txtValor_Venda.getText()));
produto.setEstoque(Integer.parseInt(txtQtd.getText()));
} catch (Exception ex) {
Logger.getLogger(frmCadastroProduto.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ProdutoDAO dao = new ProdutoDAO();
if(dao.Salvar(produto)){
JOptionPane.showMessageDialog(this,"Dados gravados com sucesso");
}else{
JOptionPane.showMessageDialog(rootPane, "Erro ao gravar os dados");
}
} catch (Exception ex) {
Logger.getLogger(frmCadastroProduto.class.getName()).log(Level.SEVERE, null, ex);
}
limpaCampos();
}
}
}//GEN-LAST:event_btnSalvarActionPerformed | 9 |
private int handleR(String value,
DoubleMetaphoneResult result,
int index,
boolean slavoGermanic) {
if (index == value.length() - 1 && !slavoGermanic &&
contains(value, index - 2, 2, "IE") &&
!contains(value, index - 4, 2, "ME", "MA")) {
result.appendAlternate('R');
} else {
result.append('R');
}
return charAt(value, index + 1) == 'R' ? index + 2 : index + 1;
} | 5 |
public boolean sendData(Object data) {
boolean status = true;
TCPServer tcpServer;
for (int i = 0; i < tcpServers.size(); i++) {
tcpServer = tcpServers.get(i);
if (tcpServer != null) {
if (tcpServer.readyForUpdates) {
if (!tcpServer.sendData(data)) {
status = false;
}
}
}
}
return status;
} | 4 |
public boolean permGen(int[] array) {
// Find longest non-increasing suffix
int i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i])
i--;
// Now i is the head index of the suffix
// Are we at the last permutation already?
if (i <= 0)
return false;
// Let array[i - 1] be the pivot
// Find rightmost element that exceeds the pivot
int j = array.length - 1;
while (array[j] <= array[i - 1])
j--;
// Now the value array[j] will become the new pivot
// Assertion: j >= i
// Swap the pivot with j
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
// Reverse the suffix
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
// Successfully computed the next permutation
return true;
} | 5 |
public void checkGroup(GroupSettings settings, CheckReport report)
{
EntityConcentrationMap map = new EntityConcentrationMap(settings, this);
report.waitForGroup(settings);
for(World world : Bukkit.getWorlds())
{
if(allowWorldGlobal(world) && settings.allowWorld(world))
map.queueWorld(world);
}
map.build(new EntityChecker(settings, report));
} | 3 |
@Override
protected boolean finishTask() throws Throwable
{
URL url = ParseHelper.asURL(this.getAddress());
if (url == null)
{
this.response = 404;
return true;
}
URLConnection con = url.openConnection();
HttpURLConnection http = (con instanceof HttpURLConnection) ? (HttpURLConnection)con : null;
con.setConnectTimeout(this.connectTimeout);
con.setReadTimeout(this.readTimeout);
for (Pair<String> prop : this.props)
{
con.setRequestProperty(prop.one, prop.two);
}
if (http != null)
{
http.setInstanceFollowRedirects(this.followRedirect);
}
con.connect();
if (http != null)
{
this.response = http.getResponseCode();
}
if (con.getDoInput())
{
ByteStreams s = new ByteStreams(con.getInputStream());
this.result = s.readAll();
s.close();
}
return true;
} | 6 |
public ListadoPartidosPosibles(ArrayList<Jugador> jugadores, boolean idaV){
listado = new ArrayList<Partido>();
marcador = new HashMap<Partido, Boolean>();
Partido p, pAux;
total = 0;
idaVuelta = idaV;
boolean anadir = false;
for (Jugador j1: jugadores)
for (Jugador j2: jugadores)
if (!j1.equals(j2))
for (String eq1: j1.dameEquipos())
for (String eq2: j2.dameEquipos()){
p = new Partido(eq1, eq2);
pAux = new Partido(eq2, eq1);
anadir = (!yaExiste(p) && !yaExiste(pAux));
if (anadir) {
listado.add(p);
marcador.put(p, false);
total++;
}
}
} | 7 |
public void lossyFilterTriple(int lim) {
System.out.println("Determinating filters and applying lossy filter...");
long initTime = System.currentTimeMillis();
lossy = lim;
if (lineFilter == null) { filterDeterminate(); }
int slim = 1 << (lim - 1);
int mod = (1 << lim) + 1;
int exL = mod - 1;
int exH = 255 - exL;
int thisval = 0;
int err = 0;
int val, fv, filVal, r;
int c255 = 0;
for (int i2 = 0; i2 < biHeight; i2 ++) {
for (int i = 0; i < biWidth; i ++) {
for (int i3 = 0; i3 < 3; i3 ++) {
image.setPoint(i, i2, i3);
val = image.getIntCurVal();
fv = filter(i, i2, i3);
if (fv < 0) { fv += 256; }
filVal = val - fv;
r = filVal % mod;
if (filVal > 0) {
if (r <= slim) {
val -= r;
err += r;
}
else {
val += (mod - r);
err += (mod - r);
}
} else {
if (-r <= slim) {
val -= r;
err -= r;
}
else {
val -= (mod + r);
err += (mod + r);
}
}
if (val > 255) { val = 255; c255 += 1;}
image.setCurVal((byte)val);
}
}
}
System.out.println("Medium lossy filter introduced error is " + (float)err / (biWidth * biHeight * 3) + " per byte");
System.out.println("Filter determination and lossy filter applying time is " +
(System.currentTimeMillis() - initTime) + " ms. ");
} | 9 |
@Override
public void deserialize(Buffer buf) {
lifePoints = buf.readInt();
if (lifePoints < 0)
throw new RuntimeException("Forbidden value on lifePoints = " + lifePoints + ", it doesn't respect the following condition : lifePoints < 0");
maxLifePoints = buf.readInt();
if (maxLifePoints < 0)
throw new RuntimeException("Forbidden value on maxLifePoints = " + maxLifePoints + ", it doesn't respect the following condition : maxLifePoints < 0");
baseMaxLifePoints = buf.readInt();
if (baseMaxLifePoints < 0)
throw new RuntimeException("Forbidden value on baseMaxLifePoints = " + baseMaxLifePoints + ", it doesn't respect the following condition : baseMaxLifePoints < 0");
permanentDamagePercent = buf.readInt();
if (permanentDamagePercent < 0)
throw new RuntimeException("Forbidden value on permanentDamagePercent = " + permanentDamagePercent + ", it doesn't respect the following condition : permanentDamagePercent < 0");
shieldPoints = buf.readInt();
if (shieldPoints < 0)
throw new RuntimeException("Forbidden value on shieldPoints = " + shieldPoints + ", it doesn't respect the following condition : shieldPoints < 0");
actionPoints = buf.readShort();
maxActionPoints = buf.readShort();
movementPoints = buf.readShort();
maxMovementPoints = buf.readShort();
summoner = buf.readInt();
summoned = buf.readBoolean();
neutralElementResistPercent = buf.readShort();
earthElementResistPercent = buf.readShort();
waterElementResistPercent = buf.readShort();
airElementResistPercent = buf.readShort();
fireElementResistPercent = buf.readShort();
neutralElementReduction = buf.readShort();
earthElementReduction = buf.readShort();
waterElementReduction = buf.readShort();
airElementReduction = buf.readShort();
fireElementReduction = buf.readShort();
criticalDamageFixedResist = buf.readShort();
pushDamageFixedResist = buf.readShort();
dodgePALostProbability = buf.readShort();
if (dodgePALostProbability < 0)
throw new RuntimeException("Forbidden value on dodgePALostProbability = " + dodgePALostProbability + ", it doesn't respect the following condition : dodgePALostProbability < 0");
dodgePMLostProbability = buf.readShort();
if (dodgePMLostProbability < 0)
throw new RuntimeException("Forbidden value on dodgePMLostProbability = " + dodgePMLostProbability + ", it doesn't respect the following condition : dodgePMLostProbability < 0");
tackleBlock = buf.readShort();
tackleEvade = buf.readShort();
invisibilityState = buf.readByte();
} | 7 |
private int newHole(int hole, T element){
int left = (hole * 2) +1; //left child
int right = (hole * 2) +2; //right child
if(left > lastIndex)
//hole has no childern
return hole;
else
if(left == lastIndex)
//left child only
if(element.compareTo(elements.get(left))< 0)
//elem < left child
return left;
else
//element >= left child
return hole;
else
//hole has 2 children
if(elements.get(left).compareTo(elements.get(right)) < 0)
//left child < right child
if(elements.get(right).compareTo(element)<= 0)
//right child <= element
return hole;
else
//element < right child
return right;
else
//left child >= right child
if(elements.get(left).compareTo(element) <=0)
//left child <= element
return hole;
else
//element < left child
return left;
} | 6 |
@Override
public MapConnector<String, Integer> putAll(final Map<? extends String, ? extends Integer> map) throws Exception {
super.addSQLJob(new SQLJob<String, Integer>() {
@Override
public void executeJob(Connection con, Map<String, Integer> internalMap) throws SQLException {
String stm = getCreateTableTmp(getConnectorInfo().getTableName());
try (PreparedStatement prepStm = con.prepareStatement(stm)) {
prepStm.execute();
}
int n = 0;
StringBuilder values = new StringBuilder();
for (String s : getMap().keySet()) {
if (n == BLOCK_INSERT_COUNT || n == getMap().size() - 1) {
stm = "INSERT INTO " + getConnectorInfo().getTableName() + "tmp(key,value) VALUES " + values.toString() + ";";
try (PreparedStatement prepStm = con.prepareStatement(stm)) {
prepStm.execute();
}
values = new StringBuilder();
n = 0;
}
values = values.append("(").append("'").append(s).append("'").append(",").append(map.get(s)).append(")");
if (n + 1 != BLOCK_INSERT_COUNT && n + 1 != getMap().size() - 1) {
values = values.append(",");
}
n++;
}
stm = getMergeTables(getConnectorInfo().getTableName(), getConnectorInfo().getTableName() + "tmp");
try (PreparedStatement prepStm = con.prepareStatement(stm)) {
prepStm.execute();
}
stm = "DROP TABLE " + getConnectorInfo().getTableName() + "tmp";
try (PreparedStatement prepStm = con.prepareStatement(stm)) {
prepStm.execute();
}
}
});
return this;
} | 7 |
public static ArrayList<ArrayList<String>> createListFromSameLetterString(
String s, ArrayList<ArrayList<String>> allLists, int length) {
if (length == 0) {
return new ArrayList<ArrayList<String>>();
}
String letter = s.substring(0, 1);
allLists = createListFromSameLetterString(s, allLists, length - 1);
ArrayList<ArrayList<String>> newlists = new ArrayList<ArrayList<String>>();
int i = 0;
// copy list
// for(ArrayList<String> list: allLists){
// newlists.add((ArrayList<String>)list.clone());
// for(String element : list){
//
// }
// }
if (allLists.size() == 0) {
ArrayList<String> newList = new ArrayList<String>();
newList.add(letter);
allLists.add(newList);
return allLists;
}
i = 0;
// if orianl is bb link bb,b
while (i < allLists.size()) {
ArrayList<String> list = allLists.get(i);
ArrayList<String> newList = new ArrayList<String>();
for (String element : list)
newList.add(element);
newList.add(letter);
newlists.add(newList);
i++;
}
i = 0;
// if orianl is bb link bbb
while (i < allLists.size()) {
ArrayList<String> list = allLists.get(i);
ArrayList<String> newList = new ArrayList<String>();
for (int j = 0; j < list.size() - 1; j++) {
// String element = list.get(j);
newList.add(list.get(j));
}
if (list.size() > 0) {
newList.add(list.get(list.size() - 1) + letter);
}
newlists.add(newList);
i++;
}
return newlists;
} | 7 |
@Test
public void ifSpotNotFreePlaceNearBy()
{
Positioned p = new Positioned(64,64,1,1);
list.addEntity(p);
list.addEntity(new Positioned(64,64,1,1));
p.findNearestFreeSpot();
assertTrue( (p.X() == 66 && p.Y() == 64) ||
(p.X() == 64 && p.Y() == 66) ||
(p.X() == 62 && p.Y() == 64) ||
(p.X() == 64 && p.Y() == 62));
} | 7 |
@Override
public void mouseMoved(MouseEvent e) {
for(CButton btn : buttons){
if(btn.isEnabled() && isBetween(btn.getX(), e.getX(), btn.x1) && isBetween(btn.getY(), e.getY(), btn.y1)){
btn.showHover = true;
}else
btn.showHover = false;
}for(CTextBox txt : textboxes){
if(txt.isEnabled() && ((txt.hasFocus()) ||
(isBetween(txt.getX(), e.getX(), txt.x1) && isBetween(txt.getY(), e.getY(), txt.y1)))){
txt.showHover = true;
}else{
txt.showHover = false;
}
}
} | 9 |
private static void reverse(String player, int row, int col, int[][] revList, int countRev) {
for (int i=0; i<countRev; i++) {
switch (revList[i][2]) {
case 0: reverse0(revList, row, col, player, i); break;
case 1: reverse1(revList, row, col, player, i); break;
case 2: reverse2(revList, row, col, player, i); break;
case 3: reverse3(revList, row, col, player, i); break;
case 4: reverse4(revList, row, col, player, i); break;
case 5: reverse5(revList, row, col, player, i); break;
case 6: reverse6(revList, row, col, player, i); break;
case 7: reverse7(revList, row, col, player, i); break;
}
}
} | 9 |
public void testBean(Object instance) throws Exception {
List<Field> fields = getFields(instance);
StringBuilder message = new StringBuilder();
boolean alert = false;
message.append("Testing " + instance.getClass().getSimpleName() + "\n");
for (Field field : fields) {
field.setAccessible(true);
Method get = getGetter(field, instance);
Method set = getSetter(field, instance);
boolean getter = testGet(field, get, instance);
boolean setter = testSet(field, set, instance);
if (!(getter && setter)) {
// These fields seem to be added to all objects by Emma code coverage, so we're not
// interested in knowing about them.
if (!(field.getName().equals("serialVersionUID") || field.getName().equals("$VRc"))) {
alert = true;
message.append(" - testing field: " + field.getName() + "\n");
if (!getter) {
message.append(" - no getter\n");
}
if (!setter) {
message.append(" - no setter\n");
}
}
}
}
if (alert) {
System.out.println(message);
}
} | 8 |
public static String getIpInfo(String ip) {
if (ip.equals("本地")) {
ip = "127.0.0.1";
}
String info = "";
try {
URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
htpcon.setRequestMethod("GET");
htpcon.setDoOutput(true);
htpcon.setDoInput(true);
htpcon.setUseCaches(false);
InputStream in = htpcon.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
JSONObject obj = (JSONObject) JSON.parse(temp.toString());
if (obj.getIntValue("code") == 0) {
JSONObject data = obj.getJSONObject("data");
info += data.getString("country") + " ";
info += data.getString("region") + " ";
info += data.getString("city") + " ";
info += data.getString("isp");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return info;
} | 6 |
@Override
public void setDbDriverNname(String dbdrivername) {
this.dbdrivername = dbdrivername;
} | 0 |
private byte[] encodeBase64 (File file, boolean isChunked)
throws IOException {
byte[] buf = null;
if (!file.isFile())
throw new IOException(file.getAbsolutePath() + ": is not a file.");
buf = new byte[(int) file.length()];
FileInputStream in = new FileInputStream(file);
int bytesRead = 0;
do {
bytesRead = in.read(buf, bytesRead, buf.length - bytesRead);
} while (bytesRead > 0);
return Base64.encodeBase64(buf, isChunked);
} | 2 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.