method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
76d4c18d-06cd-4d72-b35e-dd933aed75f4 | 7 | public boolean shellCollideCheck(Shell shell)
{
if (deadTime != 0) return false;
float xD = shell.x - x;
float yD = shell.y - y;
if (xD > -16 && xD < 16)
{
if (yD > -height && yD < shell.height)
{
world.sound.play(Art.samples[Art.SAMPLE_MARIO_KICK], this, 1, 1, 1);
xa = shell.facing * 2;
ya = -5;
flyDeath = true;
if (spriteTemplate != null) spriteTemplate.isDead = true;
deadTime = 100;
winged = false;
hPic = -hPic;
yPicO = -yPicO + 16;
if(world.recorder != null)
world.recorder.shellKillRecord(this);
return true;
}
}
return false;
} |
3acbc4e7-8e63-4bec-9bfa-9a09ff94ac16 | 5 | public ArrayList<Object> findObject(String command, String keywords)
throws RemoteException {
if(command.equals("userFind")){
return new UserController().find(keywords);
}
if(command.equals("accountFind")){
return new FinanceController().find(keywords) ;
}if(command.equals("getCustomer")){
ArrayList<Object> list=new ArrayList<Object>();
list.add(new CustomerController().getCustomerPOById(keywords));
return list;
}if(command.equals("findCustomer")){
return new CustomerController().findCustomer(keywords);
}
if (command.equals("findGoods")) {
return goodsController.searchGoods(keywords);
}
else{
return null;
}
} |
6f03961e-690f-4544-b0d9-79ed9a9dfc72 | 5 | public static void scanWorlds()
{
for(World a:Bukkit.getWorlds())
{
if(!AddressBook.containsWorld(a.getName()))
{
AddressBook.writeAddress(a.getName(), new ChevronWorld(a.getName(),a.getName(),"NONE",1,(a.getName().equals("world_nether")? true:false),false,false,false));
File f = new File(data + "/worlds.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(f);
config.set("worlds."+a.getName()+".GateMaterial", "NONE");
config.set("worlds."+a.getName()+".Multiplier", 1);
config.set("worlds."+a.getName()+".isNether", (a.getName().equals("world_nether")? true:false));
config.set("worlds."+a.getName()+".autoGateCreating", false);
config.set("worlds."+a.getName()+".canDial", false);
config.set("worlds."+a.getName()+".handleNormal", false);
config.set("worlds."+a.getName()+".DisplayName", "NONE");
try {
config.save(f);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
e0fcbb41-cf27-4770-9c74-1b8cbb627409 | 3 | public Ink_Calculator(List<RecParametr> params) {
if(params != null)
for(RecParametr rp : params)
{
InkMass im = new InkMass(rp);
if(im.GetColor() != record_ink.Unknown)
inks.add(im);
}
} |
8bf8d7e3-e954-4b9f-9d40-64e404c43589 | 3 | public Object invokeMethod(Reference ref, boolean isVirtual, Object cls,
Object[] params) throws InterpreterException,
InvocationTargetException {
if (isWhite(ref))
return super.invokeMethod(ref, isVirtual, cls, params);
MethodIdentifier mi = (MethodIdentifier) Main.getClassBundle()
.getIdentifier(ref);
if (mi != null) {
BytecodeInfo code = mi.info.getBytecode();
if (code != null)
return interpreter.interpretMethod(code, cls, params);
}
throw new InterpreterException("Invoking library method " + ref + ".");
} |
00a811fd-0724-4b78-bc89-5e1a5a431de6 | 3 | public int rocRLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 10;
else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod;
} |
e92eedda-f19c-40ff-b553-e368013ba2c0 | 7 | public void setInstances(Instances inst) {
m_Instances = inst;
String [] attribNames = new String [m_Instances.numAttributes()];
for (int i = 0; i < attribNames.length; i++) {
String type = "";
switch (m_Instances.attribute(i).type()) {
case Attribute.NOMINAL:
type = "(Nom) ";
break;
case Attribute.NUMERIC:
type = "(Num) ";
break;
case Attribute.STRING:
type = "(Str) ";
break;
case Attribute.DATE:
type = "(Dat) ";
break;
case Attribute.RELATIONAL:
type = "(Rel) ";
break;
default:
type = "(???) ";
}
String attnm = m_Instances.attribute(i).name();
attribNames[i] = type + attnm;
}
m_StartBut.setEnabled(m_RunThread == null);
m_StopBut.setEnabled(m_RunThread != null);
m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames));
if (inst.classIndex() == -1)
m_ClassCombo.setSelectedIndex(attribNames.length - 1);
else
m_ClassCombo.setSelectedIndex(inst.classIndex());
m_ClassCombo.setEnabled(true);
} |
29f211bb-f0d8-4947-ad74-cf20313e641e | 6 | @Override
public ProvaEscrita alterar(IEntidade entidade) throws SQLException {
if (entidade instanceof ProvaEscrita) {
Connection connection = ConnectionFactory.getConnection();
ProvaEscrita provaEscrita = (ProvaEscrita) entidade;
String sql2 = "delete from candidato_aptos_prova_escrita where id_prova_escrita=?";
PreparedStatement stmt2 = connection.prepareStatement(sql2);
stmt2.setInt(1, provaEscrita.getIdProvaEscrita());
stmt2.executeUpdate();
if (provaEscrita.getCandidatosAptosProva().isEmpty() == false) {
ArrayList<Candidato> listaAptos = provaEscrita.getCandidatosAptosProva();
Iterator<Candidato> iterator = listaAptos.iterator();
/*remove todos os candidadtos aptos*/
while (iterator.hasNext()) {
Candidato object = iterator.next();
String sql3 = "insert into candidato_aptos_prova_escrita (id_candidato, id_prova_escrita) values(?,?)";
PreparedStatement stmt3 = connection.prepareStatement(sql3, Statement.RETURN_GENERATED_KEYS);
stmt3.setInt(1, object.getIdCandidato());
stmt3.setInt(2, provaEscrita.getIdProvaEscrita());
stmt3.executeUpdate();
}
}
String sql4 = "delete from candidato_aptos_leitura_prova_escrita where id_prova_escrita=?";
PreparedStatement stmt4 = connection.prepareStatement(sql4);
stmt4.setInt(1, provaEscrita.getIdProvaEscrita());
stmt4.executeUpdate();
if (provaEscrita.getCandidatosAptosLeitura().isEmpty() == false) {
ArrayList<Candidato> listaAptos = provaEscrita.getCandidatosAptosLeitura();
Iterator<Candidato> iterator = listaAptos.iterator();
/*remove todos os candidadtos aptos*/
while (iterator.hasNext()) {
Candidato object = iterator.next();
String sql5 = "insert into candidato_aptos_leitura_prova_escrita (id_candidato, id_prova_escrita) values(?,?)";
PreparedStatement stmt5 = connection.prepareStatement(sql5, Statement.RETURN_GENERATED_KEYS);
stmt5.setInt(1, object.getIdCandidato());
stmt5.setInt(2, provaEscrita.getIdProvaEscrita());
stmt5.executeUpdate();
}
}
String sql = " UPDATE prova_escrita SET "
+ " id_concurso = ?,"
+ " id_ponto_sorteado_prova_escrita = ?,"
+ " hora_ponto_sorteado = ? ,"
+ " hora_inicio_prova = ?,"
+ " hora_fim_prova = ?,"
+ " local_realizacao = ?,"
+ " hora_inicio_leitura = ?,"
+ " hora_fim_leitura = ?,"
+ " local_leitura = ?,"
+ " hora_inicio_julgamento = ?,"
+ " local_julgamento = ?,"
+ " hora_inicio_resultado = ?,"
+ " local_resultado = ?"
+ " WHERE id_prova_escrita = ? ";
PreparedStatement stmt = connection.prepareStatement(sql);
this.setInt(stmt, 1, provaEscrita.getConcurso().getIdConcurso());
this.setInt(stmt, 2, provaEscrita.getPontoSorteado().getIdPontoProvaEscrita());
this.setTime(stmt, 3, provaEscrita.getHoraPontoSorteado());
this.setTime(stmt, 4, provaEscrita.getHoraInicioProva());
this.setTime(stmt, 5, provaEscrita.getHoraFimProva());
stmt.setString(6, provaEscrita.getLocalRealizacao());
this.setTime(stmt, 7, provaEscrita.getHoraInicioLeitura());
this.setTime(stmt, 8, provaEscrita.getHoraFimLeitura());
stmt.setString(9, provaEscrita.getLocalLeitura());
this.setTime(stmt, 10, provaEscrita.getHoraInicioJulgamento());
stmt.setString(11, provaEscrita.getLocalJulgamento());
this.setTime(stmt, 12, provaEscrita.getHoraInicioResultado());
stmt.setString(13, provaEscrita.getLocalResultado());
stmt.setInt(14, provaEscrita.getIdProvaEscrita());
System.out.println(stmt.toString());
if (stmt.executeUpdate() == 1) {
return provaEscrita;
}
}
return null;
} |
e0b9d703-a184-4751-8a69-cd0f453e3b8c | 2 | public boolean opEquals(Operator o) {
if (o instanceof ConstOperator) {
Object otherValue = ((ConstOperator) o).value;
return value == null ? otherValue == null : value
.equals(otherValue);
}
return false;
} |
e6555030-d481-4b32-b60f-4672056a0832 | 0 | public String getHtmlCode() {
return htmlCode;
} |
a85d9922-bfc4-497a-bded-36302cdf5dfd | 0 | public int run()
{
qSortBase(aInt, 0, aInt.length-1);
return 0;
} |
ee0863df-99ce-4bd7-9857-46931aeac1b0 | 9 | public static void finalizeOneClass(Stella_Class renamed_Class) {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, renamed_Class.homeModule());
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (((Symbol)(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_CLASS_EXTENSION_NAME, null))) != null) {
KeyValueList.setDynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_STORED_ACTIVEp, Stella.TRUE_WRAPPER, null);
}
Stella_Class.addDirectSupersBackLinks(renamed_Class);
Stella_Class.inheritSuperclasses(renamed_Class);
if ((((BooleanWrapper)(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_STORED_ACTIVEp, null))) != null) &&
BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_STORED_ACTIVEp, null))))) {
Stella_Class.activateClass(renamed_Class);
}
Stella_Class.addPrimaryType(renamed_Class);
{ Surrogate alias = null;
Cons iter000 = renamed_Class.classSynonyms().theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
alias = ((Surrogate)(iter000.value));
if ((((Stella_Class)(alias.surrogateValue)) != null) &&
((!(((Stella_Class)(alias.surrogateValue)) == renamed_Class)) &&
(!Stella.stringEqlP(Stella_Class.className(((Stella_Class)(alias.surrogateValue))), Stella_Class.className(renamed_Class))))) {
{
Stella.STANDARD_WARNING.nativeStream.println("Warning: Alias `" + Symbol.internSymbolInModule(alias.symbolName, ((Module)(alias.homeContext)), true) + "' can't point to `" + Stella_Class.classSymbol(renamed_Class) + "' because it already points to ");
Stella.STANDARD_WARNING.nativeStream.println("the class `" + Stella_Class.classSymbol(((Stella_Class)(alias.surrogateValue))) + "'.");
}
;
}
else {
alias.surrogateValue = renamed_Class;
}
}
}
if ((((Symbol)(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_CLASS_EXTENSION_NAME, null))) != null) &&
(((ClassExtension)(KeyValueList.dynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_CLASS_EXTENSION, null))) == null)) {
KeyValueList.setDynamicSlotValue(renamed_Class.dynamicSlots, Stella.SYM_STELLA_CLASS_EXTENSION, ClassExtension.newClassExtension(), null);
}
HookList.runHooks(Stella.$FINALIZE_RELATION_HOOKS$, renamed_Class);
renamed_Class.classFinalizedP = true;
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
20789f70-025b-4594-9a80-d1b32af1ae54 | 8 | public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) {
Object base = prefix.eval(bindings, context);
if (base == null) {
throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", prefix));
}
Object property = getProperty(bindings, context);
if (property == null && strict) {
throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base));
}
String name = bindings.convert(property, String.class);
Method method = findMethod(name, base.getClass(), returnType, paramTypes);
try {
return method.invoke(base, paramValues);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.property.method.access", name, base.getClass()));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.property.method.invocation", name, base.getClass()), e);
} catch (InvocationTargetException e) {
throw new ELException(LocalMessages.get("error.property.method.invocation", name, base.getClass()), e.getCause());
}
} |
aa7d8d08-3e47-4cc0-951d-bc2a7723089a | 5 | public Card chooseSeven() {
CardArray sevenCards = new CardArray();
for (Card i : cards)
if (i.num() == 7)
sevenCards.add(i);
if (sevenCards.isEmpty())
return null;
Card.Suit mSuit = Agonia.findDominantSuit(sevenCards);
for (Card i : sevenCards)
if (i.suit() == mSuit) {
cards.remove(i);
System.out.println("\nCPU played: " +
i.shortdesc());
return i;
}
return null;
} |
4a174217-f751-443f-8570-7632379e7bf1 | 3 | private List<String> getNumCombinations(String phoneNum) {
List<String> numCombinations = new ArrayList<String>();
// Get Position Combinations for Inserting, each combination may form a new set of words
List<String> insertPointList = getInsertPositions(phoneNum.length() - 1);
Iterator<String> itorator = insertPointList.iterator();
while (itorator.hasNext()) {
String insertPointStr = itorator.next();
//char[] insertPoints = insertPointStr.toCharArray();
String[] insertPoints = insertPointStr.split(DELIMITER_POS);
StringBuilder sb = new StringBuilder();
String substr = "";
int lastposition = 0;
for (int i = 0; i < insertPoints.length; i++) {
int position = Integer.parseInt(insertPoints[i]);
substr = phoneNum.substring(lastposition, position);
if (!"".equals(substr)) {
sb.append(substr + DELIMITER);
}
lastposition = position;
}
// Add last part
sb.append(phoneNum.substring(lastposition));
numCombinations.add(sb.toString());
}
return numCombinations;
} |
ecf4e435-da3c-4a20-a624-b8736402d222 | 1 | public List<T> getNextValues() {
List<T> values = new ArrayList<T>();
for (int i = 0; i < count(); i++) {
values.add(getNextValue(i));
}
return values;
} |
814d541c-e166-439e-8915-ed4b92e584f4 | 2 | public void handleAbilityButtonClick(Ability ability) {
panel.getMatchInfoPanel().setSurrenderPending(false);
if (inProgress && selectedTile != null) { //Ignore ability button clicks when the match is over.
setRange(new Range(this, selectedTile, ability));
}
} |
a772cfb9-c8d2-4fe2-9e7b-8e34f56c6877 | 8 | final void method3669(Canvas canvas, int i, int i_90_) {
do {
try {
anInt8025++;
Object object = null;
if (canvas == null || canvas == ((NativeToolkit) this).aCanvas7925)
object = anObject8020;
else if (aHashtable8014.containsKey(canvas))
object = aHashtable8014.get(canvas);
if (object == null)
throw new RuntimeException();
method3844(12727, canvas, object);
if (canvas != aCanvas7910)
break;
method3917(false);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("wga.HF("
+ (canvas != null ? "{...}"
: "null")
+ ',' + i + ',' + i_90_
+ ')'));
}
break;
} while (false);
} |
4eddcd42-bd12-486e-b969-8a0d0e2ea2d6 | 7 | public void transferImage()
throws IOException, DBException
{
VersionDTO version = getVersion();
if (null == version)
throw new IllegalStateException("Cannot transfer an image: target version is not set");
if (version.isImageAvailable())
return;
InputStream image = null;
Logger log = log();
log.finer("Transferring image to " + version + " ...");
try
{
image = buildImage();
db.findDAO(VersionDAO.class).saveImage(version, image);
}
catch (Exception ex)
{
log.log(Level.SEVERE, "Error transferring " + version, ex);
if (ex instanceof IOException)
throw (IOException)ex;
if (ex instanceof DBException)
throw (DBException)ex;
if (ex instanceof RuntimeException)
throw (RuntimeException)ex;
else
throw new RuntimeException(ex);
}
finally
{
// Allow exception in close() to supersede initial exception
// as it will store status of asynchronous restore process
if (null != image)
image.close();
}
} |
9f5fcdaf-e483-423f-969d-d847422c7430 | 3 | private static int rank_recursive(int[] N, int key, int hi, int lo) {
if (lo > hi) {
return KEY_NOT_FOUND; //base case
}
int mid = findMidpoint(hi, lo); // find the midpoint
if (key < N[mid]) { // the key is in the lower half so lower the upper bound
hi = --mid;
rank_recursive(N, key, hi, lo);
} else if (key > N[mid]) { // the key is in the upper half so raise the lower bound
lo = ++mid;
rank_recursive(N, key, hi, lo);
} else {
return mid;
}
return KEY_NOT_FOUND;
} |
d1c7d6e9-fa2e-4743-8013-412bec654435 | 9 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String nextPage = "showResult.jsp";
String message = "action nulo o invalido";
try {
HttpSession session = request.getSession();
switch (action) {
case "inicializarEmpresa":
session.setAttribute("empresa", new Empresa("empresa1", new ArrayList<Liquidable>()));
nextPage = "showResult.jsp";
message = "empresa inicializada";
break;
case "inicioAgregarEmpleadoAnual":
nextPage = "agregarEmpleadoAnual.jsp";
break;
case "agregarEmpleadoAnual":
EmpleadoAnual empleadoAnual = new EmpleadoAnual(request.getParameter("nombre"), request.getParameter("dni"), request.getParameter("direccion"),
Double.parseDouble(request.getParameter("salarioAnual")));
Empresa empresa = (Empresa) session.getAttribute("empresa");
empresa.getLiquidables().add(empleadoAnual);
nextPage = "showResult.jsp";
message = "empleado anual dado de alta";
break;
case "inicioAgregarEmpleadoHora":
nextPage = "agregarEmpleadoHora.jsp";
break;
case "agregarEmpleadoHora":
EmpleadoHora empleadoHora = new EmpleadoHora(request.getParameter("nombre"), request.getParameter("dni"), request.getParameter("direccion"),
Double.parseDouble(request.getParameter("valorHora")), Double.parseDouble(request.getParameter("cantidadHoras")));
empresa = (Empresa) session.getAttribute("empresa");
empresa.getLiquidables().add(empleadoHora);
nextPage = "showResult.jsp";
message = "empleado hora dado de alta";
break;
case "obtenerLiquidacion":
empresa = (Empresa) session.getAttribute("empresa");
nextPage = "showResult.jsp";
message = String.valueOf(empresa.calcularTotalPagosMensuales());
break;
case "mostrarSession":
nextPage = "mostrarSession.jsp";
break;
case "invalidarSession":
nextPage = "showResult.jsp";
message = "sesion invalidada";
break;
}
} catch (Throwable t) {
t.printStackTrace();
message = t.getMessage();
}
request.setAttribute("message", message);
request.getRequestDispatcher(nextPage).forward(request, response);
} |
6861b000-a506-4cfa-8a73-99023f08483f | 4 | public void run(){
try {
synchronized(this){
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fileName=null;
while((fileName=br.readLine())!=null){
break;
}
System.out.println(fileName);
File receivedFile=new File(fileName);
InputStream is=socket.getInputStream();
FileOutputStream fos=new FileOutputStream(receivedFile,true);
BufferedOutputStream bos=new BufferedOutputStream(fos);
byte[] mybytearray=new byte[1000000];
byte [] tempbuffer=new byte[Long.BYTES];
is.read(tempbuffer,0,tempbuffer.length);
long fileSize=bytesToLong(tempbuffer);
System.out.println(fileSize);
//READ
int bytesRead=0;
int totalbytes=0;
while(totalbytes<fileSize)
{
bytesRead = is.read(mybytearray,0,mybytearray.length);
//System.out.println(receivedFile.getName()+" "+bytesRead);
totalbytes+=bytesRead;
//System.out.println("Total bytesRead "+totalbytes);
if(bytesRead>0)bos.write(mybytearray,0, bytesRead);
bos.flush();
}
System.out.println(receivedFile.getName()+" Done!");
is.close();
fos.close();
bos.close();
socket.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
} |
460f85fa-895f-4da7-a848-2a4ba84ddcee | 9 | public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0, N = parseInt(in.readLine().trim()); i < N; i++) {
in.readLine();
StringTokenizer st = new StringTokenizer(in.readLine().trim());
arr = new int[parseInt(st.nextToken())][parseInt(st.nextToken())];
camino = new boolean[arr.length][arr[0].length];
for (int j = 0; j < arr.length; j++) {
st = new StringTokenizer(in.readLine().trim());
int I = parseInt(st.nextToken());
while(st.hasMoreTokens())
camino[I - 1][parseInt(st.nextToken()) - 1]=true;
}
for (int j = 0; j < arr.length; j++) Arrays.fill(arr[j], MAX_VALUE - 1);
arr[0][0] = 0;
if(!camino[0][1]){
cambio = new boolean[arr.length][arr[0].length];
cambio[0][0]=true;
hallarCamino(0, 1);
}
else if(!camino[1][0]){
cambio = new boolean[arr.length][arr[0].length];
cambio[0][0]=true;
hallarCamino(1, 0);
}
if(arr[arr.length-1][arr[0].length - 1]==MAX_VALUE||arr[arr.length-1][arr[0].length - 1]==MAX_VALUE-1)System.out.println(0);
else System.out.println(caminos(arr.length-1, arr[0].length - 1));
if(i<N-1)System.out.println();
}
} |
22812baf-dc45-4266-82b5-bf3078faeb14 | 2 | private OutputChannels(int channels)
{
outputChannels = channels;
if (channels<0 || channels>3)
throw new IllegalArgumentException("channels");
} |
98627d25-029b-4e8b-b5cd-5c53dd7411e0 | 1 | public static void printTable(double itemArray[][], int itemNumber[], double unitValue[], DecimalFormat df){
System.out.println("This is the current Item Set: ");
System.out.println("Item " + itemNumber[0] + ": $"+itemArray[0][0]+" | "+itemArray[1][0]+" lbs");
System.out.println("Item " + itemNumber[1] + ": $"+itemArray[0][1]+" | "+itemArray[1][1]+" lbs");
System.out.println("Item " + itemNumber[2] + ": $"+itemArray[0][2]+" | "+itemArray[1][2]+" lbs");
System.out.println("Item " + itemNumber[3] + ": $"+itemArray[0][3]+" | "+itemArray[1][3]+" lbs\n");
for(int i=0; i<4; i++)
System.out.println("Item "+itemNumber[i]+" unit value: "+df.format(unitValue[i])+" $/lb");
} |
5809ca25-bb1f-4cb9-8d3b-f813f21576e1 | 0 | public int getRandom() {
return this.random;
} |
2b5f63a6-47e2-4a67-bbba-8e6a1e133e8e | 3 | private static Collection<Circle> filterFinalScoreCheck(ShortImageBuffer edgeImage, Collection<Circle> input)
{
Collection<Circle> output = new ArrayList<>(input.size());
for (Circle original : input)
{
List<Circle> permutations = new ArrayList<>(input.size());
for(int i=0;i<3*3*3;i++)
{
int dr = (i%3)-1;
int dx = ((i/9)%3)-1;
int dy = ((i/3)%3)-1;
permutations.add(original.shift(dx, dy).grow(dr).score(edgeImage));
}
Circle best = Collections.max(permutations);
if (best.score >= FINAL_SCORE_THRESHOLD)
{
output.add(best);
}
}
return output;
} |
f92f7c1b-7295-4711-b79e-452f9ec9226b | 2 | public State stateAtPoint(Point point) {
State[] states = getAutomaton().getStates();
// Work backwards, since we want to select the "top" state,
// and states are drawn forwards so later is on top.
for (int i = states.length - 1; i >= 0; i--)
if (point.distance(states[i].getPoint()) <= StateDrawer.STATE_RADIUS)
return states[i];
// Not found. Drat!
return null;
} |
3a57be38-5793-42b3-bead-5e3676d4c089 | 8 | @Override
public String howMuch(String item, String client, String market) {
logger.info("Calculating expected time to delivery. " +
"item " + item + ", client " + client + ", market " + market);
// business rule: delivery date depends of the market last letter
// business rule: delivery date depends of the client first letter
char key = market.toUpperCase().charAt(market.length()-1);
if ((key >= 'A') && (key <= 'D'))
return "0.3";
else if ((key >= 'E') && (key <= 'P'))
return "0.2";
else if ((key >= 'Q') && (key <= 'Z'))
return "0.1";
else if ((key >= '0') && (key <= '9'))
return "0.5";
else
return "1.0";
} |
6d4d1a59-1e67-4c47-baff-9f3eeba9bc27 | 9 | public static void main(String[] args) {
Scanner in = null; // for input
PrintStream out = null; // for output
BasicMapADT<String, Entry> concord = new BSTBasicMap<String, Entry>();
// the concordance
File inFile = null; //store input file
File outFile = null; //store output file
// Set up where to send input and output
switch (args.length) {
case 1:
try {
inFile = new File(args[0]);
in = new Scanner(inFile);
} catch (FileNotFoundException ex) {
System.out.println("file not found");
System.exit(0);
}
out = System.out;
break;
case 2:
try {
inFile = new File(args[0]);
in = new Scanner(inFile);
outFile = new File(args[1]);
out = new PrintStream(outFile);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
System.exit(0);
}
break;
default:
System.err.println("Invalid command-line arguments");
System.exit(0);
}
// Process the input file line by line
// Note: the code below just prints out the words contained in each
// line. You will need to replace that code with code to generate
// the concordance.
int lineNum = 1; //keeps track of current line number
while (in.hasNext()) {
String line = in.nextLine();
List<String> words = parseLine(line);
////////////////////////////////////////
// replace the code below with your code
for (String word : words) {
Entry myEntry = new Entry(word);
try {
concord.put(word.toLowerCase(), myEntry);
myEntry.getLines().add(lineNum);
} catch (DuplicateException ex) {
concord.get(word.toLowerCase()).getLines().add(lineNum);
}
}
lineNum++;
////////////////////////////////////////
} // end while
// Print out the concordance
Iterator<Entry> iter = concord.values().iterator();
while (iter.hasNext())
out.println(iter.next().toString());
// Print out the statistics
int keys = concord.size();
int pathLength = concord.totalPathLength();
out.print("# keys: " + keys + " total path length: " + pathLength);
double avg = pathLength;
out.println(" avg path length: " + ((keys == 0)? 0 :avg/keys));
out.close();
} |
e3d4ec51-1bd7-4fa4-8a14-7a499a3c31c2 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CadastraOpcional.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastraOpcional.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastraOpcional.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastraOpcional.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CadastraOpcional().setVisible(true);
}
});
} |
7049864a-b181-472a-921c-1316e86adfb7 | 9 | public void giveHint(String target, String hint)
throws HanabiException
{
if (hintsLeft <= 0) {
throw new HanabiException("No hints left; discard or play a card instead");
}
int seatNumber = Integer.parseInt(target);
if (seatNumber < 0 || seatNumber >= seats.size()) {
throw new HanabiException("Invalid target for hint");
}
Seat targetSeat = seats.get(seatNumber);
Hint h = new Hint();
h.from = activeSeat;
h.to = seatNumber;
h.whenGiven = turn;
if (h.from == h.to) {
throw new HanabiException("Invalid target for hint");
}
if (hint.matches("^(\\d+)$")) {
int rank = Integer.parseInt(hint);
h.type = HintType.RANK;
h.hintData = rank;
}
else {
h.type = HintType.SUIT;
h.hintData = -1;
for (int i = 0; i < SUIT_NAMES.length; i++) {
if (hint.equals(SUIT_NAMES[i])) {
h.hintData = i;
break;
}
}
if (h.hintData == -1) {
throw new HanabiException("Invalid hint '"+hint+"'");
}
}
hints.add(h);
hintsLeft--;
HintEvent evt = new HintEvent();
evt.actor = activeSeat;
evt.actorSeat = getActiveSeat();
evt.target = h.to;
evt.hintType = h.type;
evt.hint = h.getHintString();
evt.applies = new boolean[targetSeat.hand.size()];
for (int i = 0; i < targetSeat.hand.size(); i++) {
evt.applies[i] = h.affirms(targetSeat.hand.get(i));
}
events.push(evt);
nextTurn();
} |
820ae766-bc4c-477a-9e6f-905ec73b5dc1 | 7 | public void affiche(Graphics g) {
if (type == TYPE.HEAL) {
g.setColor(Color.green);
String text = "+" + Integer.toString(value);
int width = g.getFont().getWidth(text);
int height = g.getFont().getHeight(text);
if (perso != null)
g.drawString(text, perso.getX() + (perso.getImg().getWidth() - width) / 2, perso.getY() - height - 2 * varY);
else
g.drawString(text, mob.getX() + (mob.getImg().getWidth() - width) / 2, mob.getY() - height - 2 * varY);
g.setColor(Color.white);
}
else if (type == TYPE.DAMAGE) {
g.setColor(Color.red);
String text = "-" + Integer.toString(value);
int width = g.getFont().getWidth(text);
int height = g.getFont().getHeight(text);
if (perso != null)
g.drawString(text, perso.getX() + (perso.getImg().getWidth() - width) / 2, perso.getY() - height - 2 * varY);
else
g.drawString(text, mob.getX() + (mob.getImg().getWidth() - width) / 2, mob.getY() - height - 2 * varY);
g.setColor(Color.white);
}
else if (type == TYPE.TRUEDAMAGE) {
g.setColor(Color.yellow);
String text = "-" + Integer.toString(value);
int width = g.getFont().getWidth(text);
int height = g.getFont().getHeight(text);
if (perso != null)
g.drawString(text, perso.getX() + (perso.getImg().getWidth() - width) / 2, perso.getY() - height - 2 * varY);
else
g.drawString(text, mob.getX() + (mob.getImg().getWidth() - width) / 2, mob.getY() - height - 2 * varY);
g.setColor(Color.white);
}
if (System.currentTimeMillis() - lastTick > 30) {
lastTick = System.currentTimeMillis();
varY++;
}
} |
b73805bc-b0ee-4b63-b313-f6268068f989 | 4 | private String getFormatString(TextureFormat _format) {
switch(_format){
case PNG: {
return "PNG";
}
case JPG: {
return "JPG";
}
case GIF: {
return "GIF";
}
case TGA: {
return "TGA";
}
default: {
//TODO: Error, texture type not supported. Return error texture.
return"PNG";
}
}
} |
b386178f-9485-4b86-b131-9d337fafdf77 | 3 | public static synchronized ArrayList<Stock> addStock(String tickername,
ArrayList<Stock> stocks) {
stocks = DataReader.getStocks();
double price = 0;
tickername = tickername.toUpperCase();
try {
price = PriceUpdater.price(tickername);
} catch (Exception e) {
System.out.println("The tickername you entered is invalid");
return stocks;
}
if (price > 0 && !stockExists(tickername, stocks)) {
Stock newStock = new Stock(tickername, 1000, price);
stocks.add(newStock);
}
writeStockValues(stocks);
return stocks;
} |
a6dca3b1-e29b-4f03-a56c-5c43fa7f933d | 1 | public IVideo createVideo(String path) {
if(getExtension(path).equals("wmv")) {
return new VideoWMV(path);
}
else {
return null;
}
} |
8da0617d-67e6-4e2e-aeda-7dfbccfed86a | 5 | public Font(String s){
location = new File(s);
if(!location.exists()){ Util.ERRORCODE2();}
else {
File[] listOfFiles = location.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
try {
String files = listOfFiles[i].getName();
if (files.length() > 4 && files.substring(files.length() - 4).equals(".png")){
BufferedImage image;
String name = files.substring(0, files.length() - 4);
File loc = new File(location + "\\" + CorrectText(name,false) + ".png");
image = ImageIO.read(loc);
characters.add(new T(image, name));
//System.out.println("Added Text!; " + name ); //You can uncomment this if you want. It just tells you that the file is added.
}
} catch (IOException e) {
e.printStackTrace();
}
} System.out.println("Loaded Fonts!");
}} |
44b04c10-6e7c-4b90-9ca9-b1cac11d86e4 | 2 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String usuario = tf_usuario.getText();
String pass = tf_pass.getText();
Usuario u = new Usuario();
u.setRut(Integer.parseInt(usuario));
u.setPassword(Integer.parseInt(pass));
ArrayList<String> usuarios = u.traerUsuario(u);
int perfil = Integer.parseInt(usuarios.get(2));
switch(perfil){
case 1:
Conserje co = new Conserje();
co.setVisible(true);
co.lblNombre.setText(usuarios.get(0));
Inicio.this.dispose();
break;
case 4:
administracion admin = new administracion();
admin.setVisible(true);
Inicio.this.dispose();
break;
}
}//GEN-LAST:event_jButton1ActionPerformed |
69db803b-aadf-46e1-a7ba-3c7cb3d9c3dd | 4 | protected void read(File file) throws IOException{
String tempFile = "";
if(file.isDirectory()){
if(file.list().length==0){
}else{
String files[] = file.list();
for (String temp : files) {
File fileDelete = new File(file, temp);
read(fileDelete);
}
}
}else{
FileInputStream fistream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fistream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
tempFile = file.toString();
String [] res = tempFile.replaceAll(getDBloc(), "").split("/");
strLine = res[1]+"|"+res[2]+"|"+res[3]+"|"+strLine;
Result = Result + strLine+"\n";
}
in.close();
}
} |
1de8f64a-aab3-4e1b-adf4-57300780f952 | 1 | public boolean tieneSiguiente(){
boolean resp = false;
if(siguiente != null)
resp = true;
return resp;
} |
a6eaafa3-3a72-43ad-a421-a7406ebd0c30 | 7 | public void unmutePlayer(Client c, String name){
if (!isOwner(c)) {
c.sendMessage("You do not have the power to do that!");
return;
}
if (clans[c.clanId] != null) {
for (int j = 0; j < clans[c.clanId].mutedMembers.length; j++) {
for(int i = 0; j < Config.MAX_PLAYERS; i++) {
if (Server.playerHandler.players[i].playerName.equalsIgnoreCase(name)) {
Client c2 = (Client)Server.playerHandler.players[i];
if (!isInClan(c2)) {
c.sendMessage(c2.playerName+" is not in your clan!");
return;
}
if (clans[c.clanId].mutedMembers[j] == i) {
clans[c.clanId].mutedMembers[j] = -1;
c2.sendMessage("You have been unmuted in: " + clans[c.clanId].name);
}
} else {
c.sendMessage("This person is not online!");
}
}
}
}
} |
4a41f209-53bc-490c-9709-9ebbd9d3a110 | 2 | private void userTypeJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_userTypeJComboBoxItemStateChanged
// TODO add your handling code here:
String selected_user_type = String.valueOf(userTypeJComboBox.getSelectedItem());
/**
*If the the user type selected is a new then load the new user form else
* load the existing user JPanel
*/
userJPanelNew.removeAll();
userJPanelNew.setLayout(new BorderLayout());
if(selected_user_type.equals("Create New")) {
userJPanelNew.add(newCustomerJPanel);
}
else if(selected_user_type.equals("Exisiting Customer")) {
existingCustomerJPanel.refreshTable();
userJPanelNew.add(existingCustomerJPanel);
}
userJPanelNew.invalidate();
userJPanelNew.validate();
userJPanelNew.repaint();
}//GEN-LAST:event_userTypeJComboBoxItemStateChanged |
80b589af-202d-4345-984a-4a3693b6d32a | 3 | public boolean interact(Level level, int x, int y, Player player, Item item, int attackDir) {
if (item instanceof ToolItem) {
ToolItem tool = (ToolItem) item;
if (tool.type == ToolType.shovel) {
if (player.payStamina(4 - tool.level)) {
level.add(new ItemEntity(new ResourceItem(Resource.flower), x * 16 + random.nextInt(10) + 3, y * 16 + random.nextInt(10) + 3));
level.add(new ItemEntity(new ResourceItem(Resource.flower), x * 16 + random.nextInt(10) + 3, y * 16 + random.nextInt(10) + 3));
level.setTile(x, y, Tile.grass, 0);
return true;
}
}
}
return false;
} |
a3266a28-ce06-41ae-b1da-8b4d391c74a1 | 7 | @Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((buildingI!=null)&&(!aborted))
{
if(messedUp)
{
if(activity == CraftingActivity.LEARNING)
commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",buildingI.name()));
else
commonEmote(mob,L("<S-NAME> mess(es) up making @x1.",buildingI.name()));
buildingI.destroy();
}
else
if(activity==CraftingActivity.LEARNING)
{
deconstructRecipeInto( buildingI, recipeHolder );
buildingI.destroy();
}
else
{
dropAWinner(mob,buildingI);
CMLib.achievements().possiblyBumpAchievement(mob, AchievementLibrary.Event.CRAFTING, 1, this);
}
}
buildingI=null;
}
}
super.unInvoke();
} |
24154e4b-8718-424a-9740-413558eb0958 | 1 | @Override
public synchronized void destroy() throws Exception {
if (isActive()) doStop();
closeConnections();
doDestroy();
} |
c9ae8793-2d11-45e5-8344-bd07eacbc2a1 | 8 | public static void main (String args[])
{
boolean homefound = false;
String localgame = "";
int na = 0;
int move = 0;
while (args.length > na)
{
if (args.length - na >= 2 && args[na].startsWith("-h"))
{
Global.home(args[na + 1]);
na += 2;
homefound = true;
}
else if (args[na].startsWith("-d"))
{
Dump.open("dump.dat");
na++;
}
else
{
localgame = args[na];
na++;
if (args.length > na)
{
try
{
move = Integer.parseInt(args[na]);
na++;
}
catch (Exception e)
{}
}
break;
}
}
Global.setApplet(false);
if ( !homefound) Global.home(System.getProperty("user.home"));
Global.readparameter(".go.cfg");
Global.createfonts();
Global.frame(new Frame());
JagoSound.play("high", "", true);
if ( !localgame.equals(""))
openlocal(localgame, move);
else GF = new LocalGoFrame(new Frame(), Global
.resourceString("Local_Viewer"));
Global.setcomponent(GF);
} |
5596050b-9660-4248-b72c-4d86289f76e7 | 4 | private int selectInvertColors(invertColorsAvailable chanelInvert, Color color){
int colorReturn=0;
switch (chanelInvert){
case RGB:
colorReturn=super.colorRGBtoSRGB(new Color(255-color.getRed(),
255-color.getGreen(), 255-color.getBlue(),color.getAlpha()));
break;
case red:
colorReturn=super.colorRGBtoSRGB(new Color(255-color.getRed(),
color.getGreen(),color.getBlue(),color.getAlpha()));
break;
case green:
colorReturn=super.colorRGBtoSRGB(new Color(color.getRed(),
255-color.getGreen(),color.getBlue(),color.getAlpha()));
break;
case blue:
colorReturn=super.colorRGBtoSRGB(new Color(color.getRed(),
color.getGreen(), 255-color.getBlue(),color.getAlpha()));
break;
}
return colorReturn;
} |
45a78738-d6b0-4956-819b-506e279e0670 | 5 | @Override
public boolean wipeTable(String table) {
Connection connection = open();
Statement statement = null;
String query = null;
try {
if (!this.checkTable(table)) {
this.writeError("Error at Wipe Table: table, " + table + ", does not exist", true);
return false;
}
statement = connection.createStatement();
query = "DELETE FROM " + table + ";";
statement.executeQuery(query);
return true;
} catch (SQLException ex) {
if (!(ex.getMessage().toLowerCase().contains("locking") ||
ex.getMessage().toLowerCase().contains("locked")) &&
!ex.toString().contains("not return ResultSet"))
this.writeError("Error at SQL Wipe Table Query: " + ex, false);
return false;
}
} |
93c6697c-7b96-427b-9e5f-545bd8714c44 | 9 | private void gameKeyReleased(int key){
switch(key){
case KeyEvent.VK_W:
//UP
break;
case KeyEvent.VK_S:
//DOWN
break;
case KeyEvent.VK_A:
//LEFT
mainModel.wilbert.stopMoveLeft();
break;
case KeyEvent.VK_D:
//RIGHT
break;
case KeyEvent.VK_SPACE:
//JUMP
mainModel.wilbert.getBody().applyLinearImpulse(new Vec2(0.0f,-0.05f), mainModel.wilbert.getBody().getPosition());
System.out.println("jump");
break;
case KeyEvent.VK_H:
//ACTION 1
break;
case KeyEvent.VK_J:
//ACTION 2
break;
case KeyEvent.VK_K:
//ACTION 3
break;
case KeyEvent.VK_L:
//ACTION 4
break;
}
} |
5950f39a-fc6b-4a58-82d0-6653d9738900 | 0 | public int size() { return N; } |
4eee2f3d-83f9-44d3-90b9-f9eb506d2257 | 6 | private RequestDispatcher goSetting(HttpServletRequest request, HttpServletResponse response) throws ServletException{
if(request.getParameter("oldpwd")!=null&&request.getParameter("newpwd")!=null&&request.getParameter("newpwd2")!=null){
try {
if(DB.passwordCorretta(((Utente)request.getSession().getAttribute("user")).getUsername(), request.getParameter("oldpwd"))){
if(request.getParameter("newpwd").equals(request.getParameter("newpwd2"))){
DB.editUser(((Utente)request.getSession().getAttribute("user")).getUsername(), request.getParameter("newpwd"));
request.setAttribute("result", "ok");
}
else{
request.setAttribute("result", "badnew");
}
}
else{
request.setAttribute("result", "badpwd");
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
return getServletContext().getRequestDispatcher("/setting.jsp");
} |
1637603c-3c9d-477e-b796-926a525c993f | 8 | public int converterParaInteiro(String romano) {
int numeroConvertido = 0;
int tamanhoString = romano.length();
int iteracao = 0;
while(true){
if(romano.charAt(iteracao) == 'M')
numeroConvertido += 1000;
if(romano.charAt(iteracao) == 'D')
numeroConvertido += 500;
if(romano.charAt(iteracao) == 'C')
numeroConvertido += 100;
if(romano.charAt(iteracao) == 'L')
numeroConvertido += 50;
if(romano.charAt(iteracao) == 'X')
numeroConvertido += 10;
if(romano.charAt(iteracao) == 'I')
numeroConvertido += 1;
iteracao++;
if(iteracao == tamanhoString)
break;
}
System.out.println(numeroConvertido);
return numeroConvertido;
} |
94fec532-2538-4c9c-870b-840f2ed7cd71 | 0 | public Node getNode() {
return this.node;
} |
964dac7c-e55a-4265-9382-a01fe5a3987c | 2 | @Override
public int insertOne(String strTabla) throws Exception {
ResultSet oResultSet;
java.sql.PreparedStatement oPreparedStatement;
int id = 0;
try {
String strSQL = "INSERT INTO " + strTabla + " (id) VALUES (null) ";
oPreparedStatement = oConexionMySQL.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS);
int returnLastInsertId = oPreparedStatement.executeUpdate();
if (returnLastInsertId != -1) {
oResultSet = oPreparedStatement.getGeneratedKeys();
oResultSet.next();
id = oResultSet.getInt(1);
}
return id;
} catch (SQLException e) {
throw new Exception("mysql.insertOne: Error al insertar el registro: " + e.getMessage());
}
} |
cbcb7457-76dc-42ea-bf44-e92b859c7b1e | 6 | void savefile()
{
// FrontEnd.statuswindow.append("Saving File...\n");
FrontEnd.appendToPane(FrontEnd.statuswindow,"Saving File...\n",Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
int id = FrontEnd.EditorPane.getSelectedIndex();
if (FrontEnd.EditorPane.getToolTipTextAt(id) == null)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new MyCustomFilter());
int returnVal = fileChooser.showSaveDialog(new javax.swing.JFrame());
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
FrontEnd.filepath = fileChooser.getSelectedFile().getPath() + ".s";
File n = new File(FrontEnd.filepath);
BufferedWriter out = new BufferedWriter(new FileWriter(FrontEnd.filepath));
out.write(FrontEnd.activepane.getText());
String fname = fileChooser.getSelectedFile().getName();
JOptionPane.showMessageDialog(null, "Saved " + ((fileChooser.getSelectedFile() != null) ? fname : "nothing"));
FrontEnd.EditorPane.setTitleAt(id, fname);
FrontEnd.EditorPane.setToolTipTextAt(id, FrontEnd.filepath);
out.close();
backend.Register.resetRegisters();
clean_branchtable();
clean_memtable();
} catch (Exception e)
{
//FrontEnd.statuswindow.append("Error occured while saving file...\n");
FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured While Saving File\n",Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
// FrontEnd.statuswindow.append(e.getStackTrace().toString());
FrontEnd.appendToPane(FrontEnd.statuswindow,e.getStackTrace().toString(),Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
JOptionPane.showMessageDialog(null, "Saving File cancelled.");
frontend.FrontEnd.exceptionraised++;
}
} else
{
// FrontEnd.statuswindow.append("Saving cancelled by user.\n");
FrontEnd.appendToPane(FrontEnd.statuswindow,"Saving Cancelled By User\n",Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
}
} else
{
BufferedWriter out = null;
try
{
FrontEnd.filepath = FrontEnd.EditorPane.getToolTipTextAt(id);
out = new BufferedWriter(new FileWriter(FrontEnd.filepath));
out.write(FrontEnd.activepane.getText());
} catch (IOException ex)
{
// FrontEnd.statuswindow.append("Error occured while saving file...\n");
FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured While Saving File\n",Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
// FrontEnd.statuswindow.append(ex.getStackTrace().toString());
FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getStackTrace().toString(),Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
} finally
{
try
{
out.close();
} catch (IOException ex)
{
//FrontEnd.statuswindow.append("Error occured while saving file...\n");
FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured While Saving File/n",Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
//FrontEnd.statuswindow.append(ex.getStackTrace().toString());
FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getMessage(),Color.BLACK);
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
//frontend.FrontEnd.exceptionraised++;
}
}
}
} |
4dda8f3f-ed54-48bd-b271-2893a82196c4 | 3 | private static void winCondition() {
// If the alien and the predator are on the same node
if (ship.getAlienNode().equals(ship.getPredatorNode())) {
// prints to the status bar
uigui.changeWinStatus(" The Alien Wins");
// Display message indicating the Alien's victory
JOptionPane.showMessageDialog(uigui.getGUI(), "THE ALIEN WINS!!!!! AHHHHHH", "", JOptionPane.INFORMATION_MESSAGE);
// Close the program
System.exit(0);
}
// If the predator is at the control room and he has walled
// himself off
// from the alieen
if (ship.getPredatorNode().equals(controlNode) && ship.getPath(ship.getPredatorNode(), ship.getAlienNode()) == null) {
// prints to the status bar
uigui.changeWinStatus(" The Predator Wins");
// Display message indicating the Predator's victory
JOptionPane.showMessageDialog(uigui.getGUI(), "THE PREDATOR IS A WINNER", "", JOptionPane.INFORMATION_MESSAGE);
// Close the program
System.exit(0);
}
} |
242f2fca-b42f-435f-a01f-a00e484be880 | 3 | void printFrequency(String filename){
HashMap m=new HashMap();
char c[]=new FileReadHelper().readFile(filename);
for(int count=0;count<c.length;count++){
if( m.containsKey(String.valueOf(c[count]))){
Integer value = (Integer) m.get(String.valueOf(c[count]));
value=value+1;
m.put(String.valueOf(c[count]), new Integer (value));
}else{
m.put(String.valueOf(c[count]), new Integer (1));
}
}
Iterator iter=m.entrySet().iterator();
while(iter.hasNext()){
Map.Entry pair = (Map.Entry)iter.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
} |
cb11528e-8701-47ca-896d-fd6d0a8cf8d2 | 8 | private boolean check() {
if (N == 0) {
if (first != null) return false;
}
else if (N == 1) {
if (first == null) return false;
if (first.next != null) return false;
}
else {
if (first.next == null) return false;
}
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
return true;
} |
b91578b0-de34-4882-9d04-740d6cda7ca4 | 0 | public int tapes() {
return tapes;
} |
db97cc1a-58de-4f09-af94-5d6ddc952cef | 2 | public static boolean isTypeCollection(Class<?> type) {
return (type != null && isAssignable(type, Collection.class));
} |
24495384-b987-406f-8e3f-1c6508cc66c9 | 8 | static int f(int p, boolean[] v, int c){
if(p==vis.length)return prim(v)+c;
boolean[] cp=new boolean[v.length];
int min=MAX_VALUE;
for(int i=0;i<v.length;i++)
for(int j=0;j<v.length;j++)
if(v[i]&&vis[p][j])min=Math.min(min,mAdy[i][j]);
for(int i=0;i<v.length;i++)cp[i]=v[i]||vis[p][i];
return Math.min(f(p+1,v,c),f(p+1,cp,c+costo[p]+(min==MAX_VALUE?0:min)));
} |
29e9611f-5ba8-4e4e-bc5e-3c9d7543b1bc | 3 | @Override
public boolean isMine(String command) {
if (super.isMine(command)) {
if ((command.indexOf("[") == -1) || (command.indexOf("]") == -1)) {
error = hint;
return false;
}
jsonStr = command.substring(command.indexOf("["), command.lastIndexOf("]") + 1);
return true;
}
return false;
} |
5e305f4f-3525-4369-98e9-a3c033917b3b | 6 | public static List<String> getFileNames(String prefix, String suffix, String language,
String country, String variant) {
List<String> result = new ArrayList<String>(4);
if (!language.equals("")) {
language = "_" + language;
}
if (!country.equals("")) {
country = "_" + country;
}
if (!variant.equals("")) {
variant = "_" + variant;
}
result.add(prefix + suffix);
String filename = prefix + language + suffix;
if (!result.contains(filename)) result.add(filename);
filename = prefix + language + country + suffix;
if (!result.contains(filename)) result.add(filename);
filename = prefix + language + country + variant + suffix;
if (!result.contains(filename)) result.add(filename);
return result;
} |
8731c10e-208f-4cc8-9a48-d64f50c1eff3 | 0 | public FileIOException(Exception e, String name)
{
super(e, name);
} |
e6fd5edd-d091-47d5-9dd6-2a511ff41a25 | 9 | public void run() {
if (!mClient.connect()) {
return;
}
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running) {
StringBuilder sb = new StringBuilder();
sb.append(sUserActions[0]);
for(int i=1; i<sUserActions.length; i++) {
sb.append(", ");
sb.append(sUserActions[i]);
}
System.out.printf("Please enter action [%s]: ",sb.toString());
String input = scan.nextLine();
switch (input) {
case USER_ACTION_EXIT:
running = false;
break;
case USER_ACTION_ADDCAB:
addCabRequest(scan);
break;
case USER_ACTION_ADDPASSENGER:
addPassengerRequest(scan);
break;
case USER_ACTION_LIST_DRIVING:
sendListRequest(MessageFactory.ACTION_LIST_DRIVING);
break;
case USER_ACTION_LIST_WAITING_CABS:
sendListRequest(MessageFactory.ACTION_LIST_WAITING_CABS);
break;
case USER_ACTION_LIST_PASSENGERS:
sendListRequest(MessageFactory.ACTION_LIST_WAITING_PASSENGERS);
break;
default:
System.out.println("Wrong input. Try again.");
break;
}
}
Request msg = new Request(MessageFactory.ACTION_EXIT);
mClient.sendRequest(msg.toJSON());
mClient.close();
} |
8ff299bd-5b6d-404f-a63a-bfe62b4ac4a4 | 3 | public boolean checkIfHasSameName(String uuid, String metaname){
if(plugin.getAnimalData().getString("Farmer."+ uuid + ".Animals") == null){
return true;
}
Set<String> auuids = plugin.getAnimalData().getConfigurationSection("Farmer."+ uuid + ".Animals").getKeys(false);
for(String auuid : auuids){
String can = plugin.getAnimalData().getString("Farmer."+ uuid + ".Animals." + auuid + ".Name");
if(can.equalsIgnoreCase(metaname)){
return false;
}
}
return true;
} |
acad720b-226a-43cb-af2e-e70058bfc2e0 | 5 | public void discoverChildren() {
GsSong[] songs=null;
if(album!=null)
songs=album.getSongs();
if(artist!=null)
songs=artist.getSongs();
if(playlist!=null) {
File f=new File(playlist.saveFile());
if(useFile)
songs=readFile(f);
else {
songs=playlist.getSongs();
savePlaylist(songs,f);
}
}
if(songs!=null)
aDisc(songs);
} |
667bb839-2c8c-4478-b2bd-c63cb4fe1512 | 6 | @SuppressWarnings("unchecked")
private List<List<Gate>> getLayersOfGates(List<Gate> gates) {
List<List<Gate>> layersOfGates = new ArrayList<List<Gate>>();
initMaps(gates);
int totalNumberOfInputs = circuitParser.getNumberOfInputs();
/*
* Loop to run through each list in our MultiMap, first runs through all
* gates with left input 0, 1, 2, ..., #inputs.
* For each of these "input" dependant gates, we visit them recursively
* and set a timestamp on each of these.
*/
for (int i = 0; i < totalNumberOfInputs; i++) {
Collection<Gate> leftList = leftMap.getCollection(i);
if(leftList == null){
continue;
}
for (Gate g: leftList) {
visitGate(g, 0, layersOfGates);
}
}
/*
* Now that we've visited all gates which depends on a left input, we
* do the same for the right input and recursively visit them again.
* When we visit a gate which has already been visited we set a
* time stamp again to be the max of the current time and the time stamp
* of the gate. This value determines which layer the gate is to be
* placed in.
*/
for (int i = 0; i < totalNumberOfInputs; i++) {
Collection<Gate> rightList = rightMap.getCollection(i);
if (rightList == null) {
continue;
}
for (Gate g: rightList) {
layersOfGates = visitGate(g, 0, layersOfGates);
}
}
return layersOfGates;
} |
a7fe53dd-b8e8-4e01-9f43-950a96ca565f | 7 | @Override
public void actionPerformed(ActionEvent event)
{
if (!event.getSource().equals(back))
{
try
{
Item item = (Item) inventory.getSelectedValue();
int indexNumber = inventory.getSelectedIndex();
int itemNumber = item.getIDNumber();
if (event.getSource().equals(use))
{
if (usableItems.contains(itemNumber) && thePlayer.canUseThisPart(item))
{
message.setText(thePlayer.use(item));
if (thepanel!=null)
{
thepanel.playerStatusChanged();
}
bank.setText("Money: $" + thePlayer.getMoney() + " Fuel: "
+ thePlayer.getFuelLevel());
inventoryList.removeElement(item);
inventory.setSelectedIndex(indexNumber);
} else
{
message.setText("You can't use this item");
}
} else if (event.getSource().equals(drop))
{
thePlayer.drop(item);
inventoryList.removeElement(item);
inventory.setSelectedIndex(indexNumber);
}
repaint();
} catch (Exception e)
{
}
} else
{
dispose();
}
} |
653995f7-d982-4c23-a215-b8f55ac552da | 4 | private Mark makeMark0(HashMap table, int pos,
boolean isBlockBegin, boolean isTarget) {
Integer p = new Integer(pos);
Mark m = (Mark)table.get(p);
if (m == null) {
m = new Mark(pos);
table.put(p, m);
}
if (isBlockBegin) {
if (m.block == null)
m.block = makeBlock(pos);
if (isTarget)
m.block.incoming++;
}
return m;
} |
fe8f8c9b-5c88-4c60-a075-9c7242721294 | 8 | public Connection createConnection() {
if (use_MySQL) {
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://" +
plugin.getConfig().getString("dbPath"),
plugin.getConfig().getString("dbUser"),
plugin.getConfig().getString("dbPassword"));
cn.setAutoCommit(false);
return cn;
} catch (SQLException e) {
plugin.getLoggerUtility().log("could not be enabled: Exception occured while trying to connect to DB", LoggerUtility.Level.ERROR);
SQLErrorHandler(e);
if (cn != null) {
System.out.println("Old Connection still activated");
try {
cn.close();
plugin.getLoggerUtility().log("Old connection that was still activated has been successfully closed", LoggerUtility.Level.ERROR);
} catch (SQLException e2) {
plugin.getLoggerUtility().log("Failed to close old connection that was still activated", LoggerUtility.Level.ERROR);
SQLErrorHandler(e2);
}
}
return null;
} catch (ClassNotFoundException e) {
plugin.getLoggerUtility().log(e.getMessage(), LoggerUtility.Level.ERROR);
return null;
}
} else {
try {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException cs) {
plugin.getLoggerUtility().log(cs.getMessage(), LoggerUtility.Level.ERROR);
}
File root = new File(plugin.getDataFolder() + File.separator + "Databases");
if(!root.exists()){
root.mkdir();
}
cn = DriverManager.getConnection("jdbc:sqlite:"
+ plugin.getDataFolder()
+ File.separator + "Databases" + File.separator
+ "Signs.sqlite");
cn.setAutoCommit(false);
return cn;
} catch (SQLException e) {
SQLErrorHandler(e);
}
}
return null;
} |
15f410c8-3743-4983-8f74-eb996a793933 | 6 | private void loadPositions(Path baseDir) throws IOException {
Path provinceDefinitionsPath = getFilePath(MapFile.POSITIONS, baseDir);
Pattern pattern = Pattern.compile("(\\d+)=");
Map<Integer, Province> provincesById = getProvincesById();
try(BufferedReader reader = Files.newBufferedReader(provinceDefinitionsPath, MapUtilities.ISO_CHARSET)) {
String line = "";
while(line != null) {
// Lines starting with # are comments, ignore them
if(line.isEmpty() || line.startsWith("#")) {
line = reader.readLine();
continue;
}
Matcher matcher = pattern.matcher(line.trim());
if(matcher.matches()){
int provinceId = Integer.parseInt(matcher.group(1));
reader.readLine(); // Open bracket
reader.readLine(); // position=
reader.readLine(); // Open bracket
String[] tokens = reader.readLine().trim().split(" ");
double cityX = Double.parseDouble(tokens[0]);
double cityY = height - Double.parseDouble(tokens[1]);
double unitX = Double.parseDouble(tokens[2]);
double unitY = height - Double.parseDouble(tokens[3]);
double textX = Double.parseDouble(tokens[2]);
double textY = height - Double.parseDouble(tokens[3]);
double tradeX = Double.parseDouble(tokens[2]);
double tradeY = height - Double.parseDouble(tokens[3]);
double portX = Double.parseDouble(tokens[2]);
double portY = height - Double.parseDouble(tokens[3]);
double combatX = Double.parseDouble(tokens[2]);
double combatY = height - Double.parseDouble(tokens[3]);
Province province = provincesById.get(provinceId);
province.addPosition(PositionType.CITY, new Point2D.Double(cityX, cityY));
province.addPosition(PositionType.UNIT, new Point2D.Double(unitX, unitY));
province.addPosition(PositionType.TEXT, new Point2D.Double(textX, textY));
province.addPosition(PositionType.TRADE, new Point2D.Double(tradeX, tradeY));
province.addPosition(PositionType.PORT, new Point2D.Double(portX, portY));
province.addPosition(PositionType.COMBAT, new Point2D.Double(combatX, combatY));
// Skip to next section
while(line != null && !line.startsWith("#"))
line = reader.readLine();
}
}
}
} |
2bff2011-cf8b-46b8-a267-2cd16f230d1a | 0 | @Override
public void mouseReleased(MouseEvent e) {
isMouseDown = false;
} |
380aff04-8574-47ee-964e-736667f34847 | 1 | public OfflinePlayer getStoreOwner(Chest chest){
if(chest==null)
return null;
return stores.get(chest).getOwner();
} |
56c04c05-6dfc-4154-ad79-1159aabeea8c | 3 | public synchronized void init() throws IOException {
int nPieces = new Double(Math.ceil((double)this.totalLength /
this.pieceLength)).intValue();
this.pieces = new Piece[nPieces];
this.completedPieces = new BitSet(nPieces);
this.piecesHashes.clear();
logger.debug("Analyzing local data for " + this.getName() + "...");
for (int idx=0; idx<this.pieces.length; idx++) {
byte[] hash = new byte[Torrent.PIECE_HASH_SIZE];
this.piecesHashes.get(hash);
// The last piece may be shorter than the torrent's global piece
// length.
// tzn: yes might be, but if it isn't this will be 0, leading to no validation
/*int len = (idx < this.pieces.length - 1) ?
this.pieceLength :
this.totalLength % this.pieceLength;*/
int len = (idx < this.pieces.length - 1) ?
this.pieceLength :
this.totalLength - ((this.pieces.length-1)*this.pieceLength);
int off = idx * this.pieceLength;
logger.trace("Creating Piece#" + idx + "/" + this.pieces.length + " off: " + off + " len: " + len + "/" + this.totalLength + " bytes " + len*idx + ")");
this.pieces[idx] = new Piece(this.bucket, idx, off, len, hash);
this.pieces[idx].validate();
if (this.pieces[idx].isValid()) {
this.completedPieces.set(idx);
this.left -= len;
}
}
logger.debug(this.getName() + ": " +
(this.totalLength - this.left) + "/" +
this.totalLength + " bytes [" +
this.completedPieces.cardinality() + "/" +
this.pieces.length + "].");
} |
ac30a578-1f9b-4a2a-b861-1f6bf2409e2b | 1 | @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
throw new ServletException("Controller: Error: ClassNotFoundException " + ex.getMessage());
}
} |
ebf40095-5217-47e3-9373-ee5d16eddd72 | 4 | public static int longestValidParentheses(String s) {
int maxLen = 0, last = -1;
Stack<Integer> lefts = new Stack<Integer>();
for (int i=0; i<s.length(); ++i) {
if (s.charAt(i)=='(') {
lefts.push(i);
} else {
if (lefts.isEmpty()) {
// no matching left
last = i;
} else {
// find a matching pair
lefts.pop();
if (lefts.isEmpty()) {//有一个完整的valid的group。计算该group的长度
maxLen = Math.max(maxLen, i-last);
} else {
//栈内还有‘(',一个最外层完整的group还没有匹配完成,
//但是通过查询下一个即将匹配还未匹配的"("的index来更新maxLen。
maxLen = Math.max(maxLen, i-lefts.peek());
}
}
}
}
return maxLen;
} |
fc70f966-5097-4c14-b1c3-28372515825c | 5 | private File search(File current, FileFilter filter) {
if (current.isDirectory()) {
File[] expected = current.listFiles(filter);
if (expected != null) {
if (expected.length > 0) {
// found
return expected[0];
} else {
for (File f : iterateOver(current)) {
File found = search(f, filter);
if (found != null) {
return found;
}
}
}
}
}
return null; // nothing found
} |
30285b60-5bb6-4a65-94d0-bd4318bdf2cb | 7 | private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
int rounds, i, j;
int cdata[] = (int[])bf_crypt_ciphertext.clone();
int clen = cdata.length;
byte ret[];
if (log_rounds < 4 || log_rounds > 31)
throw new IllegalArgumentException ("Bad number of rounds");
rounds = 1 << log_rounds;
if (salt.length != BCRYPT_SALT_LEN)
throw new IllegalArgumentException ("Bad salt length");
init_key();
ekskey(salt, password);
for (i = 0; i < rounds; i++) {
key(password);
key(salt);
}
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++)
encipher(cdata, j << 1);
}
ret = new byte[clen * 4];
for (i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte)((cdata[i] >> 24) & 0xff);
ret[j++] = (byte)((cdata[i] >> 16) & 0xff);
ret[j++] = (byte)((cdata[i] >> 8) & 0xff);
ret[j++] = (byte)(cdata[i] & 0xff);
}
return ret;
} |
7aa6f5e5-9751-4aeb-80d1-00c673daca83 | 7 | /* */ public void handleDirection(int targetX, int targetY)
/* */ {
/* 75 */ double hitX = this.hitCheck.getX2();
/* 76 */ double hitY = this.hitCheck.getY2();
/* */
/* 78 */ if (this.y < hitY) {
/* 79 */ if (this.x > hitX) {
/* 80 */ if (Math.abs(this.x - hitX) > Math.abs(this.y -
/* 81 */ hitY))
/* 82 */ this.image = Core.enemyRifleManDirections.getTileImage(3);
/* */ else {
/* 84 */ this.image = Core.enemyRifleManDirections.getTileImage(2);
/* */ }
/* */ }
/* 87 */ else if (Math.abs(this.x - hitX) > Math.abs(this.y -
/* 88 */ hitY))
/* 89 */ this.image = Core.enemyRifleManDirections.getTileImage(1);
/* */ else {
/* 91 */ this.image = Core.enemyRifleManDirections.getTileImage(2);
/* */ }
/* */
/* */ }
/* 95 */ else if (this.x > hitX) {
/* 96 */ if (Math.abs(this.x - hitX) > Math.abs(this.y -
/* 97 */ hitY))
/* 98 */ this.image = Core.enemyRifleManDirections.getTileImage(3);
/* */ else {
/* 100 */ this.image = Core.enemyRifleManDirections.getTileImage(0);
/* */ }
/* */ }
/* 103 */ else if (Math.abs(this.x - hitX) > Math.abs(this.y -
/* 104 */ hitY))
/* 105 */ this.image = Core.enemyRifleManDirections.getTileImage(1);
/* */ else
/* 107 */ this.image = Core.enemyRifleManDirections.getTileImage(0);
/* */ } |
e49ef040-3f41-4542-a8cb-21713cfdb4ef | 1 | private static long makelong(byte[] x) {
long y = 0L;
for(int i = 0; i < x.length; i++) {
y += ((long)x[i]) << (8*i);
}
return y;
} |
8e4c9680-48e5-4105-83e1-9cd280cf80e2 | 6 | public boolean deleteNode(E data) {
BinaryTreeNode<E> node = findNode(data);
if (node == null) {
return false;
}
if (node.left == null && node.right == null) {
// Deleting the leaf node
replaceNodeWithChild(node, null);
} else if (node.left == null || node.right == null) {
// Deleting node with one child
if (node.left != null) {
replaceNodeWithChild(node, node.left);
} else {
replaceNodeWithChild(node, node.right);
}
} else {
// Deleting node with two children. Get either in-order successor or in-order predecessor (anything is
// fine). For now working with predecessor, better would be to check the height of the left and right
// subtree and call predecessor or successor accordingly
BinaryTreeNode<E> predecessor = BinarySearchTreeAlgorithms.inOrderPredecessor(node);
E temp = predecessor.data;
deleteNode(predecessor.data);
node.data = temp;
}
return true;
} |
6e977c68-5f03-4d8d-8cc6-6f2a3b371f77 | 5 | int dinicDfs(int[] ptr, int[] dist, int dest, int u, int f) {
if (u == dest)
return f;
for (; ptr[u] < ady[u].size(); ++ptr[u]) {
Edge e = ady[u].get(ptr[u]);
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
int df = dinicDfs(ptr, dist, dest, e.t,
Math.min(f, e.cap - e.f));
if (df > 0) {
e.f += df;
ady[e.t].get(e.rev).f -= df;
return df;
}
}
}
return 0;
} |
9513830d-a5a2-4049-b2a3-993baaed05ee | 5 | private void dfs(EdgeWeightedDigraph G, int v) {
onStack[v] = true;
marked[v] = true;
for (DirectedEdge e : G.adj(v)) {
int w = e.to();
// short circuit if directed cycle found
if (cycle != null) return;
//found new vertex, so recur
else if (!marked[w]) {
edgeTo[w] = e;
dfs(G, w);
}
// trace back directed cycle
else if (onStack[w]) {
cycle = new Stack<DirectedEdge>();
while (e.from() != w) {
cycle.push(e);
e = edgeTo[e.from()];
}
cycle.push(e);
}
}
onStack[v] = false;
} |
3d15af06-4b5d-4b96-aff3-4366f31e145a | 2 | public void loadFromFile() throws Exception{
String filename = "Girl.bin";
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
Object temp = ois.readObject();
if(temp.getClass().getName().equals("Girl")){
ghead = (Girl) temp;
}
}catch(EOFException e){
System.out.println("File loaded");
}
} |
07b2ff04-fb84-467d-bea6-50ef0274612c | 0 | public void setRound(int round)
{
this.round = round;
notifyListeners();
} |
901ac75e-896d-43f2-b26f-09662eddf053 | 0 | public void mouseReleased(MouseEvent e)
{
} |
d962e036-a0d8-4337-8d4e-bcf85ceb483d | 3 | public boolean contains(E target) {
DoubleLinkedListElement tmp = head;
for (int i = 0; i < size(); i++) {
if(tmp!=null && tmp.data.equals(target)) return true;
tmp = tmp.nextElement;
}
return false;
} |
292727bf-a8db-4d38-80f6-fe7332db261f | 8 | public Object scalar() //to fetch single value
{
ResultSet rs=null;
Object s=null;
try {
rs=ps.executeQuery();
if(rs.next())
{
s=rs.getObject(1);
}
}catch(Exception ex){
System.err.println(ex);
}finally{
try{
if(rs!=null)
rs.close();
}catch(Exception ex) {
System.err.println(ex);
}
try{
if(ps.getConnection()!=null)
ps.getConnection().close();
}catch(Exception ex) {
System.err.println(ex);
}
try{
if(ps!=null)
ps.close();
}catch(Exception ex){
System.err.println(ex);
}
}
return s;
} |
bf5ef96e-256a-481e-a16e-7b55a7c8b380 | 2 | public boolean addAll(Collection<? extends Car> c) {
if((c.size() + list.size()) > maximum){
return false;
}
list.addAll(c);
return true;
} |
b9f91b7e-f55a-493f-af9a-dc4318efa0ce | 0 | public CheckResultMessage checkSum4(int i,int j){
return checkReport1.checkSum4(i,j);
} |
cc746c71-3b0d-42a0-87a1-c452bde3e4d8 | 7 | public boolean equals(Object _other)
{
if (_other == null) {
return false;
}
if (_other == this) {
return true;
}
if (!(_other instanceof BillDetailsPk)) {
return false;
}
final BillDetailsPk _cast = (BillDetailsPk) _other;
if (billId != _cast.billId) {
return false;
}
if (userId != _cast.userId) {
return false;
}
if (billIdNull != _cast.billIdNull) {
return false;
}
if (userIdNull != _cast.userIdNull) {
return false;
}
return true;
} |
11cb4283-137b-4105-8028-d2090e280438 | 6 | public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a Boolean.");
} |
40da18a7-b2d4-454e-ba21-3c75613fd80f | 7 | private void AddTextElementToRulesList(TranscriptionRulesElement textElement)
{
//At first we need to validate whether the rule element has the minimum required data.
if (textElement!=null && textElement._text.length()>0)
{
if (_rules==null)
{
//If this is the first rule in the list:
_rules = textElement;
}
else
{//If there is at lest one rule in the list.
TranscriptionRulesElement iterator = _rules;
boolean attached = false;
//We iterate through rules.
do
{
if (iterator._text.charAt(0)==textElement._text.charAt(0))
{
//If we have found a rule with the same first character, we have to iterate through the second dimension (same character rules).
if (iterator._next!=null)
{//When we have found the last rule in the list, we attach the new rule at the end.
iterator = iterator._next;
}
else
{
iterator._next = textElement;
attached = true;
}
}
else if (iterator._nextCharElement!=null)
{
//The current rule is with a different first character, so we have to iterate through the first dimension (different first character rules).
iterator = iterator._nextCharElement;
}
else
{
//If there are no rules with the same first character as in the new rule, we attach the new rule at the end of the first dimension rules.
iterator._nextCharElement = textElement;
attached = true;
}
}
while (!attached);
}
}
} |
c3436336-6cfa-4be4-9706-f9b5a0cf11a5 | 9 | @Override
public void paintComponent(Graphics g) {
// lancement de la musique de fond
SoundEffect.MUSIC.playLoop();
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
int nbLosers = 0;
int winner = 0;
for(int i = 0; i < players.length; ++i) {
g.translate(this.getWidth() / players.length * i, 0);
players[i].getGameScreen().draw(g, this.getWidth() / players.length, this.getHeight(), players[i].getIndice(), players[i].isOver(), this);
g.translate(-this.getWidth() / players.length * i, 0);
if(players[i].isOver()) {
++nbLosers;
} else {
winner = i + 1;
}
}
if(nbLosers == players.length - 1 && players.length > 1) {
// arret de la musique de fond
SoundEffect.MUSIC.stop();
if(!players[winner - 1].isWin()) SoundEffect.WIN.play();
//affichage des résultats
g.setColor(Color.black);
g.fillRect(0, this.getHeight() / 3, this.getWidth(), this.getHeight() / 3);
g.setColor(Color.red);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 20));
g.drawString("Le joueur " + winner + " gagne !", this.getWidth() / 6, this.getHeight() / 2);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 40));
g.drawString("Appuyez sur Entrée", this.getWidth() / 3, this.getHeight() * 3 / 5);
players[winner - 1].setWin(true);
} else if(nbLosers == players.length && players.length > 1) {
// arret de la musique de fond
SoundEffect.MUSIC.stop();
//affichage des résultats
g.setColor(Color.black);
g.fillRect(0, this.getHeight() / 3, this.getWidth(), this.getHeight() / 3);
g.setColor(Color.red);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 20));
g.drawString("Egalité !", this.getWidth() * 2 / 5, this.getHeight() / 2);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 40));
g.drawString("Appuyez sur Entrée", this.getWidth() / 3, this.getHeight() * 3 / 5);
} else if(nbLosers == 1 && players.length == 1) {
// arret de la musique de fond
SoundEffect.MUSIC.stop();
// bruitage
SoundEffect.LOOSE.play();
//affichage des résultats
g.setColor(Color.black);
g.fillRect(0, this.getHeight() / 3, this.getWidth(), this.getHeight() / 3);
g.setColor(Color.red);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 20));
g.drawString("Score : " + players[0].getGameScreen().getScore(), this.getWidth() / 4, this.getHeight() / 2);
g.setFont(minecraftia.deriveFont(Font.PLAIN, this.getWidth() / 40));
g.drawString("Appuyez sur Entrée", this.getWidth() / 3, this.getHeight() * 3 / 5);
}
} |
da7b4bfa-6dd6-4001-8da3-59fbacd82ce3 | 6 | public void quickSort(Integer[] values, int start, int length) {
// Check for empty or null array
if (values == null || values.length == 0) {
return;
}
if (length == 0 || (start - length) == 0) {
return;
}
int p = pivot.ChoosePivot(values, start, length - 1);
int i = partition(values, p, length);
if (start <= i - 1) {
quickSort(values, start, i);
}
if (i + 1 <= length) {
quickSort(values, i + 1, length);
}
} |
6597acab-c636-40d8-be9a-c234dd1a2919 | 8 | public boolean rotate(Polyomino poly){
//Allows for wall kicks
for (int i=0; i<=poly.getLength()/2; i=(i<=0)?(-i+1):(-i)){
boolean canRotate=true;
for (Point loc:poly.getRotateAndTranslateLocs(i,0)){
if (loc.y<0 || loc.x<0 || loc.x>=fWidth ||
contents[loc.y][loc.x] != null){
canRotate=false;
}
}
if (canRotate){
poly.translate(i, 0);
poly.rotate();
return true;
}
}
return false;
} |
678dc3f5-373a-40d9-8b68-3138fb1860d2 | 0 | public SignedInfoType getSignedInfo() {
return signedInfo;
} |
f931bcfb-7a05-4ebe-948b-f5fd4873dd51 | 1 | private void SaveTimestampDiffsToFile(HashMap<Integer, String> hashMap) {
try (
OutputStream file = new FileOutputStream("timestamps.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);) {
output.writeObject(hashMap);
} catch (IOException ex) {
logger.error("Cannot serialize object: " + ex.getMessage());
}
} |
a8f09fb7-9785-4185-880a-dd2b53641bf6 | 2 | public static void process(String s, int durationInMillis) {
if(!process)
return;
try {
Thread.sleep(durationInMillis);
} catch (InterruptedException e) {
// ignore
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.