method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
dfd5c244-dcc4-4fbb-9cac-0cda6a902fd3 | 2 | public double[] subarray_as_degrees_phase_of_Phasor(int start, int end){
if(end>=this.length)throw new IllegalArgumentException("end, " + end + ", is greater than the highest index, " + (this.length-1));
Phasor[] pp = this.getArray_as_Phasor();
double[] phased = new double[end-start+1];
for(int i=start; i<=end; i++)phased[i-start] = pp[i].getPhaseInDegrees();
return phased;
} |
3241b587-45f7-4129-8cb2-6c07211c5dda | 3 | public static List<ArrayList<Double>> getCenters(String inputpath){
List<ArrayList<Double>> result = new ArrayList<ArrayList<Double>>();
Configuration conf = new Configuration();
try {
FileSystem hdfs = FileSystem.get(conf);
Path in = new Path(inputpath);
FSDataInputStream fsIn = hdfs.open(in);
LineReader lineIn = new LineReader(fsIn, conf);
Text line = new Text();
while (lineIn.readLine(line) > 0){
String record = line.toString();
/*
因为Hadoop输出键值对时会在键跟值之间添加制表符,
所以用空格代替之。
*/
String[] fields = record.replace("\t", " ").split(" ");
List<Double> tmplist = new ArrayList<Double>();
for (int i = 0; i < fields.length; ++i){
tmplist.add(Double.parseDouble(fields[i]));
}
result.add((ArrayList<Double>) tmplist);
}
fsIn.close();
} catch (IOException e){
e.printStackTrace();
}
return result;
} |
f73f6598-4c7f-456d-a783-21b0c0d4e177 | 8 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AutomatoImpl automato = (AutomatoImpl) o;
if (!alfabeto.equals(automato.alfabeto)) return false;
if (!estadoInicial.equals(automato.estadoInicial)) return false;
if (!estados.equals(automato.estados)) return false;
if (!estadosFinais.equals(automato.estadosFinais)) return false;
if (!funcoesTransicao.equals(automato.funcoesTransicao)) return false;
return true;
} |
5c20ab19-3d03-4d4f-9829-35f2314b108e | 0 | public OutlinerSubMenuItem() {} |
d37084c0-50dc-45d4-b633-b2f84c5e2582 | 3 | public TestCompareCds(String genomeVersion, String configFile) {
config = new Config(genomeVersion, configFile);
cdsByTrId = new HashMap<String, String>();
try {
if (!quiet) System.out.print("Loading predictor " + config.getGenome().getVersion() + " ");
config.loadSnpEffectPredictor();
if (!quiet) System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} |
d8ede7f6-abd0-48be-a48d-989152607e5d | 3 | public int AddCell(String Text, String ID, int colspan, int rowspan) {
//Controllo se è stato creato l'oggetto tabella
if (this._PdfPTable != null) {
//Controllo se l'ID sia presente nella lista
for (int i = 0; i < this._MyCellList.size(); i++) {
if (this._MyCellList.get(i).GetID().equals(ID)) {
//Creo la frase che verrà contenuta nella cella
Phrase TmpPhrase = new Phrase(new Chunk(Text, FontFactory.getFont(this._MyCellList.get(i).GetBaseFont(), this._MyCellList.get(i).GetFontSize(), this._MyCellList.get(i).GetStyle(), this._MyCellList.get(i).GetTextColor())));
//Creo la cella
PdfPCell TmpPdfPCell = new PdfPCell(TmpPhrase);
//Imposto quante colonne deve contenere la cella
TmpPdfPCell.setColspan(colspan);
//Imposto quante righe deve contenere la cella
TmpPdfPCell.setRowspan(rowspan);
TmpPdfPCell.setHorizontalAlignment(this._MyCellList.get(i).GetHorizontalAlignment());
TmpPdfPCell.setVerticalAlignment(this._MyCellList.get(i).GetVerticalAlignment());
TmpPdfPCell.setBorderWidth(this._MyCellList.get(i).GetBorderWidth());
TmpPdfPCell.setBorderColor(this._MyCellList.get(i).GetBorderColor());
TmpPdfPCell.setBackgroundColor(this._MyCellList.get(i).GetBackGroundColor());
//Aggiungo la cella alla tabella
this._PdfPTable.addCell(TmpPdfPCell);
return 1;
}
}
//Se l'ID non è presente
return -1;
}
//Se non è stato creato l'ogetto tabella
else{
return -2;
}
} |
20d22088-792a-4d37-9d9b-81edd408aa2b | 9 | public static String findFile(File root, String name)
throws PatternSyntaxException {
Pattern p = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
Deque<Filer> next = new ArrayDeque<Filer>();
for (File f : root.listFiles()) {
if (p.matcher(f.getName()).matches())
return f.getName() + (f.isDirectory() ? "/" : "");
if (f.isDirectory())
next.addLast(new Filer(f, f.getName() + "/"));
}
while (!next.isEmpty()) {
Filer fr = next.removeFirst();
for (File f : fr.f.listFiles()) {
if (p.matcher(f.getName()).matches())
return fr.n + f.getName() + (f.isDirectory() ? "/" : "");
if (f.isDirectory())
next.addLast(new Filer(f, fr.n + f.getName() + "/"));
}
}
return null;
} |
a3195120-dc52-4b64-a9f4-371553ea2508 | 5 | public static Color[] createMultiGradient(Color[] colors, int numSteps) {
// we assume a linear gradient, with equal spacing between colors
// The final gradient will be made up of n 'sections', where n =
// colors.length - 1
int numSections = colors.length - 1;
int gradientIndex = 0; // points to the next open spot in the final
// gradient
Color[] gradient = new Color[numSteps];
Color[] temp;
if (numSections <= 0) {
throw new IllegalArgumentException(
"You must pass in at least 2 colors in the array!");
}
for (int section = 0; section < numSections; section++) {
// we divide the gradient into (n - 1) sections, and do a regular
// gradient for each
temp = createGradient(colors[section], colors[section + 1],
numSteps / numSections);
for (int i = 0; i < temp.length; i++) {
// copy the sub-gradient into the overall gradient
gradient[gradientIndex++] = temp[i];
}
}
if (gradientIndex < numSteps) {
// The rounding didn't work out in our favor, and there is at least
// one unfilled slot in the gradient[] array.
// We can just copy the final color there
for (/* nothing to initialize */; gradientIndex < numSteps; gradientIndex++) {
gradient[gradientIndex] = colors[colors.length - 1];
}
}
return gradient;
} |
b45238fa-bd73-468b-b280-07decd0b6a15 | 6 | private void buildOutlineElement(Node node, String lineEnding, StringBuffer buf, int max_style_depth) {
indent(node, buf);
// Calculate CSS Class
String cssClass = "";
if (node.isLeaf()) {
if (node.isComment()) {
cssClass = CSS_LEAF_COMMENT;
} else {
cssClass = CSS_LEAF;
}
} else {
if (node.isComment()) {
cssClass = CSS_BRANCH_COMMENT;
} else {
cssClass = CSS_BRANCH;
}
}
if (node.getDepth() <= max_style_depth) {
cssClass = cssClass + node.getDepth();
}
buf.append("<div class=\"").append(cssClass).append("\">").append(XMLTools.escapeHTML(node.getValue())).append(lineEnding);
if (!node.isLeaf()) {
for (int i = 0; i < node.numOfChildren(); i++) {
buildOutlineElement(node.getChild(i), lineEnding, buf, max_style_depth);
}
}
indent(node, buf);
buf.append("</div>").append(lineEnding);
} |
f55f99c2-7192-4152-b976-62152251e9f9 | 1 | public void setStatustextZoomedFontsize(int fontsize) {
if (fontsize <= 0) {
this.statustextZoomedFontSize = UIFontInits.STATUSZOOMED.getSize();
} else {
this.statustextZoomedFontSize = fontsize;
}
somethingChanged();
} |
ca63be84-6f8e-4f55-b7d6-bc8f728afb4e | 0 | public InvalidMove() {
} |
09e944c5-1648-4469-b5e3-68a5fa596456 | 5 | public static double getMinObservation(ArrayList<Observation>[] list, Vector2d reference){
if(list == null) return 0;
double result = Double.MAX_VALUE;
for(int i=0; i<list.length; i++){
for(int j=0; j<list[i].size(); j++){
double distance = list[i].get(j).position.dist(reference);
if(distance < result){
result = distance;
}
}
}
if(result == Double.MAX_VALUE){
return 0;
}
return result;
} |
3926cab0-b1a9-4dd5-b1fa-6eabe294d0eb | 7 | public void calculateRelativeFrequenciesPerRole() {
featureValueFrequency.put("all", new MultiSet<String>());
featureValueFrequency.get("all").add("all", totalCount);
for (String featureType : FeatureTypes.getUsedFeatures()) {
if (featureType.contains(Const.roleTypeIdentifier)) {
int roleIndex = 0;
String role = "";
int i = 0;
for (String featureTypePart : featureType.split(Const.splitChar)) {
if (featureTypePart.equals(Const.roleTypeIdentifier)) {
roleIndex = i;
role = featureTypePart;
}
i++;
}
for (Entry<String, Integer> countsPerRolePerFeatureValue : featureValueFrequency.get(featureType).getMap().entrySet()) {
String featureValue = countsPerRolePerFeatureValue.getKey();
String[] featureValueParts = featureValue.split(Const.splitChar);
if (!featureValueRelativeRoleFrequency.containsKey(featureType)) {
featureValueRelativeRoleFrequency.put(featureType, new HashMap<String, Double>());
}
if (featureValueParts.length == 1) {
featureValueRelativeRoleFrequency.get(featureType).put(featureValue, Math.log(countsPerRolePerFeatureValue.getValue()) - Math.log(totalCount));
} else
featureValueRelativeRoleFrequency.get(featureType).put(featureValue, Math.log(countsPerRolePerFeatureValue.getValue()) - Math.log(featureValueFrequency.get(role).get(featureValueParts[roleIndex])));
}
} else {
// wirklich noetig??
/*for (Entry<String, Integer> countsPerRolePerFeatureValue : featureValueFrequency.get(featureType).getMap().entrySet()) {
String featureValue = countsPerRolePerFeatureValue.getKey();
if (!featureValueRelativeRoleFrequency.containsKey(featureType)) {
Map<String, Double> valueProbabilities = new HashMap<String, Double>();
featureValueRelativeRoleFrequency.put(featureType, valueProbabilities);
}
featureValueRelativeRoleFrequency.get(featureType).put(featureValue, Math.log(countsPerRolePerFeatureValue.getValue()) - Math.log(totalCount));
} */
}
}
//System.out.println();
} |
755e26f4-0956-4eaa-b849-392f8af4bd92 | 0 | public void onStart(IContext context) throws JFException {
engine = context.getEngine();
indicators = context.getIndicators();
console = context.getConsole();
} |
38e9be15-f11c-4d65-a0f0-f659ac1d4853 | 7 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Board))
return false;
Board other = (Board) obj;
if (N != other.N)
return false;
if (hamming != other.hamming)
return false;
if (manhattan != other.manhattan)
return false;
if (!Arrays.deepEquals(tiles, other.tiles))
return false;
return true;
} |
42ff4057-e51c-4318-9998-9202f51569e9 | 8 | private void consolodateInts()
{
for(int i=0;i<intArray.length-1;i++)
{
if(((intArray[i]&NEXT_FLAG)==0)
&&(intArray[i]+1==(intArray[i+1]&INT_BITS)))
{
if((intArray[i+1]&NEXT_FLAG)>0)
{
if((i>0)&&((intArray[i-1]&NEXT_FLAG)>0))
{
shrinkIntArray(i,2);
return;
}
shrinkIntArray(i,1);
intArray[i]=((intArray[i]&INT_BITS)-1)|NEXT_FLAG;
return;
}
if((i>0)&&((intArray[i-1]&NEXT_FLAG)>0))
{
shrinkIntArray(i+1,1);
intArray[i]++;
return;
}
intArray[i]=intArray[i]|NEXT_FLAG;
return;
}
}
} |
d1286179-aa29-473c-8a45-631c98d27772 | 0 | public void onMessage(IMessage message) throws JFException {
} |
96be97a7-f97d-405f-9932-51a78c08730e | 7 | @Override
public List<Orientador> Buscar(Orientador obj) {
String sql = "select a from Orientador a";
String filtros = "";
if(obj != null){
if(obj.getId() != null){
filtros += "a.id = " + obj.getId();
}
//ver se a busca por nome é em USUARIODAO
//FAZER A BUSCA POR MATRICULA SIAPE
if(obj.getNome() != null){
if(filtros.length() > 0)
filtros += " and ";
filtros += "a.nome like '%" + obj.getNome() + "%'";
}
if(obj.getAreaConhecimento() != null){
if(filtros.length() > 0)
filtros += " and ";
filtros += "a.areaconhecimento like '%" + obj.getAreaConhecimento() + "%'";
}
}
if(filtros.length() > 0){
sql += " where " + filtros;
}
Query consulta = manager.createQuery(sql);
return consulta.getResultList();
} |
cf3dc682-68c3-4206-947c-365885b86d75 | 2 | public void decrement(int by) {
// if given value is negative, we have to increment
if (by < 0) {
decrement(Math.abs(by));
return;
}
// cut off full overflows
by %= (range + 1);
// check if we would still overflow
int space_down = value - min;
if (by > space_down) {
// we check how big overflow is and remove that from max
by -= space_down + 1;
value = max - by;
} else {
// no overflowing, this is easy
value -= by;
}
} |
f50b8dd0-e76c-4773-86cd-c71aa6a0351f | 2 | @Override
public Set<FoodObject> lookUpFoodByCollection(Collection<String> names) {
Set<FoodObject> result = new HashSet<FoodObject>();
for (String name : names) {
if (cachedFoodObjectMap.containsKey(name)) {
result.add(cachedFoodObjectMap.get(name));
//TODO: fall back to db
}
}
return result;
} |
c96ef029-a26f-40a1-be8a-bc5235481ae4 | 4 | public static void extractEntry(ZipFile zipFile, ZipEntry entry, String destDir) throws IOException {
File file = new File(destDir + "/" + entry.getName().replace("\\", "/"));
if (entry.isDirectory()) file.mkdirs();
else {
file.getParentFile().mkdirs();
InputStream is = null;
OutputStream os = null;
try {
is = zipFile.getInputStream(entry);
os = new FileOutputStream(file);
for (int len; (len = is.read(BUFFER)) != -1;) {
os.write(BUFFER, 0, len);
}
} finally {
if (os != null) os.close();
if (is != null) is.close();
}
}
} |
f5904cc7-128f-4a0b-8a47-f9833acbb2e7 | 2 | private Boolean isAPropertiesFile(final String filePath) {
String[] splitted = filePath.split("\\.");
if ((splitted.length > 1) && (splitted[1]).compareTo(PROPERTIES_FILE_EXTENSION) == 0) {
return true;
}
return false;
} |
d1928e40-638c-4f8d-a7a5-b051f7057c09 | 4 | public void speciate(List<Organism> organisms) {
/* All other genomes are placed into species as follows:
* A random member of each existing species is chosen as its permanent representative.
* Genomes are tested one at a time; if a genome’s distance to the representative of any
* existing species is less than t, a compatibility threshold, it is placed into this species.*/
String path = "/Users/anastasiiakabeshova/Documents/these_softPartie/sorties/delta_" + getGenerationNumber()
+ "_" + EcritureTXTfichier.nextEnabeledIDfile() + ".txt";
EcritureTXTfichier toFile = new EcritureTXTfichier(path);
toFile.writeToFile(path);
for (int i = 0; i < organisms.size(); i++) {
boolean added = false;
for (int j = 0; j < getSpecies().size(); j++) {
double delta = organisms.get(i).countDistanceDelta(getSpecies().get(j).getRepresentOrganism());
//write delta to file
toFile.appendToFile(true, delta);
if (delta < AppProperties.compatThreshold()) {
getSpecies().get(j).addOrganism(organisms.get(i));
j = getSpecies().size();
// go out from second for
added = true;
}
}
/**
* Otherwise, if it is not compatible with any existing species, a
* new species is created and given a new number.
*/
if (added == false) {
getSpecies().add(new Species(organisms.get(i)));
}
toFile.appendToFile(true, "\n");
}
} |
f18581eb-34e3-400f-8cf9-75b0bf823b89 | 8 | protected void execute() {
velocity = oi.getRawAnalogStickALY();
turn = oi.getRawAnalogStickARX();
if (Math.abs(velocity) < .05) {
velocity = 0;
}
if (Math.abs(turn) < .05) {
turn = 0;
}
if (vPrev - velocity > rampThreshold) {
velocity = vPrev - rampThreshold;
} else if (velocity - vPrev > rampThreshold) {
velocity = vPrev + rampThreshold;
}
if (turnPrev - turn > rampThreshold) {
turn = turnPrev - rampThreshold;
} else if (turn - turnPrev > rampThreshold) {
turn = turnPrev + rampThreshold;
}
vPrev = (float) velocity;
turnPrev = (float) turn;
if (velocity >= 0) {
driveLeft = -(velocity - turn);
driveRight = velocity + turn;
}
if (velocity < 0) {
driveLeft = -(velocity + turn);
driveRight = velocity - turn;
}
drivetrainSub.tankDrive(driveLeft, driveRight);
} |
f62a2567-5377-4ef4-9299-f0703f4b1bc3 | 8 | private Color getColorWithIndex(int index) {
Color color = null;
switch (index) {
case 0:
color = Color.ORANGE.darker();
break;
case 1:
color = Color.CYAN.darker();
break;
case 2:
color = Color.GREEN.darker();
break;
case 3:
color = Color.YELLOW.darker();
break;
case 5:
color = Color.BLUE.darker();
break;
case 6:
color = Color.RED.darker();
break;
case 7:
color = Color.WHITE;
break;
case 9:
color = Color.BLACK;
break;
default:
color = Color.BLACK;
}
return color;
} |
d7387983-7c9a-4e91-9955-88dc8908721b | 0 | public ArrayList<String> getQuestAnswer() {
return questAnswer;
} |
6050f8aa-dc55-4faa-bf50-ebac4f0747a4 | 9 | protected void loadFields(com.sforce.ws.parser.XmlInputStream __in,
com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException {
super.loadFields(__in, __typeMapper);
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) {
setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedById__typeInfo)) {
setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) {
setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Field__typeInfo)) {
setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) {
setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, NewValue__typeInfo)) {
setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, OldValue__typeInfo)) {
setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Parent__typeInfo)) {
setParent((com.sforce.soap.enterprise.sobject.Event__c)__typeMapper.readObject(__in, Parent__typeInfo, com.sforce.soap.enterprise.sobject.Event__c.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, ParentId__typeInfo)) {
setParentId(__typeMapper.readString(__in, ParentId__typeInfo, java.lang.String.class));
}
} |
7151aa75-74bc-445b-babd-9f2a3057ce11 | 1 | public final void need(int count) throws VerifyException {
if (stackHeight < count)
throw new VerifyException("stack underflow");
} |
7f713934-4c03-46b3-b9de-9bb698b13922 | 8 | public static void sendPlayerToLastBack( BSPlayer player, boolean death, boolean teleport ) {
if ( player.hasDeathBackLocation() || player.hasTeleportBackLocation() ) {
player.sendMessage( Messages.SENT_BACK );
} else {
player.sendMessage( Messages.NO_BACK_TP );
}
if ( death && teleport ) {
if ( player.hasDeathBackLocation() || player.hasTeleportBackLocation() ) {
teleportPlayerToLocation( player, player.getLastBackLocation() );
}
} else if ( death ) {
teleportPlayerToLocation( player, player.getDeathBackLocation() );
} else if ( teleport ) {
teleportPlayerToLocation( player, player.getTeleportBackLocation() );
}
} |
522c450c-de8a-4733-9fa0-8e4a738e857a | 1 | @Override
public void scoreGame(boolean won, int score) {
if (won)
System.out.println("You won the game!\n");
else System.out.println("You lost the game.\n");
} |
185baf8e-0f0e-425f-8309-4968c4c4c3b2 | 4 | public int read()
{
try
{
FileInputStream inStream = new FileInputStream("options.txt");
DataInputStream in = new DataInputStream(inStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
url = br.readLine();
url = url.replaceFirst("url: ", "");
//dbcon.setUrl(url);
login = br.readLine();
login = login.replaceFirst("login: ","");
// dbcon.setLogin(login);
pass = br.readLine();
pass = pass.replaceFirst("pass: ", "");
//dbcon.setPass(pass);
status = 1;
br.close();
}//try
catch(Exception e)
{
if(e.getMessage().contains("options.txt ("))
{
LOGGER.info("Brak pliku opcji! Czy chcesz go utworzyc? tak/nie");
Scanner skan = new Scanner(System.in);
String wybor = skan.nextLine();
if(wybor.equals("tak"))
{
newOptionsFile();
read();
}
}//if
else {
LOGGER.log(Level.SEVERE,e.getMessage(),e);
status = 2;
if(proba<2)
{
proba++;
newOptionsFile();
read();
}
}
}//catch
return status;
}//read |
5fc683e1-52c0-4813-ada4-c5033a2c6e61 | 4 | private void handleResize() {
paintCanvas.update();
Rectangle visibleRect = paintCanvas.getClientArea();
visibleWidth = visibleRect.width;
visibleHeight = visibleRect.height;
ScrollBar horizontal = paintCanvas.getHorizontalBar();
if (horizontal != null) {
displayFDC.xOffset = Math.min(horizontal.getSelection(), imageWidth - visibleWidth);
if (imageWidth <= visibleWidth) {
horizontal.setEnabled(false);
horizontal.setSelection(0);
} else {
horizontal.setEnabled(true);
horizontal.setValues(displayFDC.xOffset, 0, imageWidth, visibleWidth,
8, visibleWidth);
}
}
ScrollBar vertical = paintCanvas.getVerticalBar();
if (vertical != null) {
displayFDC.yOffset = Math.min(vertical.getSelection(), imageHeight - visibleHeight);
if (imageHeight <= visibleHeight) {
vertical.setEnabled(false);
vertical.setSelection(0);
} else {
vertical.setEnabled(true);
vertical.setValues(displayFDC.yOffset, 0, imageHeight, visibleHeight,
8, visibleHeight);
}
}
} |
8760be5a-ed14-41be-be5d-771e91320997 | 6 | public int removeDuplicates(int[] A) {
int count = 1;
int countAll = 0;
int pre = Integer.MIN_VALUE;
int removed = 0;
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < A.length; i++) {
int a = A[i];
if (a == pre) {
count++;
} else {
count = 1;
}
pre = a;
if (count <= 2) {
countAll++;
} else {
set.add(i);
removed++;
}
}
int index = 0;
int[] B = new int[A.length - removed];
for (int i = 0; i < A.length; i++) {
if (!set.contains(i)) {
B[index++] = A[i];
}
}
for (int i = 0; i < B.length; i++) {
A[i] = B[i];
}
return countAll;
} |
099abc93-789b-4db0-8e74-4c4a47062de9 | 3 | public void replace(String statement) throws CannotCompileException {
thisClass.getClassFile(); // to call checkModify().
ConstPool constPool = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
Javac jc = new Javac(thisClass);
ClassPool cp = thisClass.getClassPool();
CodeAttribute ca = iterator.get();
try {
CtClass[] params
= new CtClass[] { cp.get(javaLangObject) };
CtClass retType = getType();
int paramVar = ca.getMaxLocals();
jc.recordParams(javaLangObject, params, true, paramVar,
withinStatic());
int retVar = jc.recordReturnType(retType, true);
jc.recordProceed(new ProceedForCast(index, retType));
/* Is $_ included in the source code?
*/
checkResultValue(retType, statement);
Bytecode bytecode = jc.getBytecode();
storeStack(params, true, paramVar, bytecode);
jc.recordLocalVariables(ca, pos);
bytecode.addConstZero(retType);
bytecode.addStore(retVar, retType); // initialize $_
jc.compileStmnt(statement);
bytecode.addLoad(retVar, retType);
replace0(pos, bytecode, 3);
}
catch (CompileError e) { throw new CannotCompileException(e); }
catch (NotFoundException e) { throw new CannotCompileException(e); }
catch (BadBytecode e) {
throw new CannotCompileException("broken method");
}
} |
21b87bd7-a01f-45d9-94c2-8c735ede5e82 | 6 | public static Level forName(final String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null for level");
}
if (name.toUpperCase().equals("NONE")) {
return NONE;
} else if (name.toUpperCase().equals("NOVICE")) {
return NOVICE;
} else if (name.toUpperCase().equals("INTERMEDIATE")) {
return INTERMEDIATE;
} else if (name.toUpperCase().equals("ADVANCED")) {
return ADVANCED;
} else if (name.toUpperCase().equals("EXPERT")) {
return EXPERT;
}
throw new IllegalArgumentException("Name \"" + name + "\" does not correspond to any Level");
} |
5c269b11-e8f9-4994-bf64-9ce0d98fa3f0 | 4 | public void moveOneStep(){
int sizeBase = AppliWindow.getInstance().getTilesSize();
boolean agentArrived = ((this.position.x > baseDestination.getPosition().x) && (this.position.x < baseDestination.getPosition().x + sizeBase)) &&
((this.position.y > baseDestination.getPosition().y) && (this.position.y < baseDestination.getPosition().y + sizeBase));
if(!agentArrived) {
float x = this.position.x + this.vectorDirector.x * this.speed;
float y = this.position.y += this.vectorDirector.y * this.speed;
this.setPosition(x, y);
}
else{
AttackBase attackCommand = new AttackBase(baseDestination, this);
Engine.getInstance().getCommands().add(attackCommand);
return;
}
} |
7ea7b4bf-7f51-4f17-b0d9-7a817646d048 | 6 | public static boolean tryAvoidingEnemyTanks(Unit unit) {
// Our own tanks should engage enemy tanks.
if (unit.getType().isTank()) {
return false;
}
Collection<Unit> allKnownEnemyTanks = getEnemyTanksThatAreDangerouslyClose(unit);
for (Unit enemyTank : allKnownEnemyTanks) {
double distance = enemyTank.distanceTo(unit);
if (distance < ALWAYS_MOVE_TO_ENEMY_TANK_IF_CLOSER_THAN) {
if (distance < ALWAYS_ATTACK_ENEMY_TANK_IF_CLOSER_THAN) {
UnitActions.attackTo(unit, enemyTank);
} else {
UnitActions.moveTo(unit, enemyTank);
}
}
}
if (allKnownEnemyTanks.size() <= MAXIMUM_TANKS_TO_ENGAGE_WITH_NORMAL_UNITS) {
return false;
}
for (Unit enemyTank : allKnownEnemyTanks) {
UnitActions.moveAwayFrom(unit, enemyTank);
unit.setAiOrder("Avoid siege tank");
return true;
}
return false;
} |
77d6208a-f5e0-45d8-a0a6-2db1f361f016 | 3 | void setTouched(int tt) {
map[tt] |= VISIT;
if ((map[tt] & NEB) == 0) { // no bomb around, auto flip
for (int i = 0; i < 8; i++) {
if ((map[tt + directions[i]] & VISIT) == 0) { // 已翻開就不用再做了
setTouched(tt + directions[i]);
}
}
}
} |
3a64fd90-505c-42aa-8e4e-6c415ecf1863 | 9 | public boolean isAssignableTo(Type type) {
if (eq(type.getCtClass(), Type.OBJECT.getCtClass()))
return true;
if (eq(type.getCtClass(), Type.CLONEABLE.getCtClass()))
return true;
if (eq(type.getCtClass(), Type.SERIALIZABLE.getCtClass()))
return true;
if (! type.isArray())
return false;
Type typeRoot = getRootComponent(type);
int typeDims = type.getDimensions();
if (typeDims > dims)
return false;
if (typeDims < dims) {
if (eq(typeRoot.getCtClass(), Type.OBJECT.getCtClass()))
return true;
if (eq(typeRoot.getCtClass(), Type.CLONEABLE.getCtClass()))
return true;
if (eq(typeRoot.getCtClass(), Type.SERIALIZABLE.getCtClass()))
return true;
return false;
}
return component.isAssignableTo(typeRoot);
} |
4640d03a-c9df-40f0-8c6f-14a67ee3258f | 2 | public DefaultLinkNormalizer(final String beginUrl) {
if ((beginUrl == null) || (beginUrl.trim().length() == 0)) {
throw new IllegalArgumentException("beginUrl cannot be null or empty");
}
this.beginUrl = beginUrl;
} |
48b28c38-ebb3-442e-aa93-ea57ec9337cf | 4 | private static BufferedImage initRotatedImage(BufferedImage givenImage,
int rotationCenterX, int rotationCenterY, double rotatingAngle) {
double maxR = -99999;
// double minR = 99999;
final int maxX = givenImage.getWidth() - 1;
final int maxY = givenImage.getHeight() - 1;
final int minX = 0;
final int minY = 0;
double temp = getR(minX, rotationCenterX, minY, rotationCenterY);
if (temp > maxR) {
maxR = temp;
}
temp = getR(minX, rotationCenterX, maxY, rotationCenterY);
if (temp > maxR) {
maxR = temp;
}
temp = getR(maxX, rotationCenterX, maxY, rotationCenterY);
if (temp > maxR) {
maxR = temp;
}
temp = getR(maxX, rotationCenterX, minY, rotationCenterY);
if (temp > maxR) {
maxR = temp;
}
final int L = (int) Math.round(3 * maxR + 1);
return new BufferedImage(L, L, givenImage.getType());
} |
031adc75-f165-449e-b4ef-8c07274000bf | 5 | public int addUser() {
String username = textField.getText();
char[] newpw = PWField.getPassword();
char[] repeat = PWField2.getPassword();
String repeatString = new String(repeat);
String newpwString = new String(newpw);
if (repeatString.equals(newpwString)) {
try {
answer = Switch.switchMethod("addUser", username, newpwString);
} catch (Exception e1) {
e1.printStackTrace();
}
switch (answer) {
case "0":
return 0;
case "1":
return 1;
case "2":
return 2;
}
}
return 3;
} |
25ce72a4-3758-4c38-8155-13fa20c0de75 | 8 | private void keyActionPerformed(final KeyEvent e) {
if (e.isControlDown()) {
if (e.getKeyCode() == KeyEvent.VK_N) {
this.actionPerformed(new ActionEvent(e.getSource(), -1, "New"));
} else if (e.getKeyCode() == KeyEvent.VK_O) {
this.actionPerformed(new ActionEvent(e.getSource(), -1, "Open"));
} else if (e.getKeyCode() == KeyEvent.VK_S) {
this.actionPerformed(new ActionEvent(e.getSource(), -1,
"Save "));
} else if (e.getKeyCode() == KeyEvent.VK_P) {
this.actionPerformed(new ActionEvent(e.getSource(), -1, "Print"));
} else if (e.getKeyCode() == KeyEvent.VK_Z) {
this.actionPerformed(new ActionEvent(e.getSource(), -1, "Undo"));
} else if (e.getKeyCode() == KeyEvent.VK_F) {
this.actionPerformed(new ActionEvent(e.getSource(), -1, "Find"));
} else if (e.getKeyCode() == KeyEvent.VK_H) {
this.actionPerformed(new ActionEvent(e.getSource(), -1,
"Replace"));
}
}
} |
7ff17bce-b958-4d24-b4e8-959bafb45a18 | 2 | public int compareTo(NGram other){
if(weight > other.getWeight()) return -1;
else if(weight < other.getWeight()) return 1;
else return 0;
} |
ba849e9c-e38c-4546-885a-49b9f60e0fde | 4 | public synchronized ArrayList<String> mobilesToBeDeleted() {
ArrayList<String> mobilesToBeDeleted = new ArrayList<String>();
ResultSet result = null;
String sqlUpdateTable;
double curtime = System.currentTimeMillis()/1000;
try {
connection = (Connection) DriverManager.getConnection(connectionUrl);
statement = connection.createStatement();
sqlUpdateTable = "SELECT * FROM mobiles;";
result = statement.executeQuery(sqlUpdateTable);
while (result.next()) {
if (curtime - result.getDouble("time") > time/1000) {
mobilesToBeDeleted.add(result.getString("imei"));
}
}
} catch (SQLException ex) {
ex.getErrorCode();
} finally {
try { statement.close();
connection.close();
} catch (SQLException ex) { ex.printStackTrace(); }
}
return mobilesToBeDeleted;
} |
b6f65c73-05d6-4287-abc4-281495b2391d | 7 | void buildPolyhedra() {
boolean useBondAlgorithm = radius == 0 || bondedOnly;
for (int i = atomCount; --i >= 0;)
if (centers.get(i)) {
Polyhedron p = (
haveBitSetVertices ? constructBitSetPolyhedron(i)
: useBondAlgorithm ? constructBondsPolyhedron(i)
: constructRadiusPolyhedron(i));
if (p != null)
savePolyhedron(p);
if (haveBitSetVertices)
return;
}
} |
41543ebf-519d-4c55-820f-c1a56ba6ec2a | 8 | private void GenreSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenreSearchButtonActionPerformed
try {
userSocket = new Socket("127.0.0.1", 6666);
out = new PrintWriter(userSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(userSocket.getInputStream()));
String search = GenreTextField.getText();
String movReturn;
boolean argument;
argument = Pattern.compile("[a-zA-z].*").matcher(search).matches();
if (argument) {
out.println("1!" + search);
int x = 0;
try {
movReturn = in.readLine();
if (movReturn.equals("0")) {
throw new noGenreException();
} else {
String columnNames[] = {"Movie", "Genre"};
String[] genreArray = movReturn.split("!");
Object rows[][] = new Object[(genreArray.length)][2];
for (int i = 0; i < genreArray.length; i++) {
if (i % 2 == 0) {
rows[x][0] = genreArray[i];
} else {
rows[x][1] = genreArray[i];
}
if (i % 2 != 0) {
x++;
}
}
SearchTable = new JTable(rows, columnNames);
SearchScrollPane.getViewport().add(SearchTable);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Error", 0);
} catch (noGenreException e) {
JOptionPane.showMessageDialog
(null, "Genre does not exist.", "Error", 0);
}
} else {
JOptionPane.showMessageDialog
(null, "No input in textbox", "Message", 0);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Error", 0);
}
}//GEN-LAST:event_GenreSearchButtonActionPerformed |
25206138-b58b-44af-adeb-da73729a2577 | 9 | public boolean isInterleave2(String s1, String s2, String s3){
if(s1.length() + s2.length() != s3.length()) return false;
boolean[][] matched = new boolean[s1.length() + 1][s2.length() + 1];
matched[0][0] = true;
for(int i1 = 1; i1 <= s1.length(); i1++){
if(s3.charAt(i1-1) == s1.charAt(i1-1)) {
matched[i1][0] = true;
}else break;
}
for(int i2 = 1; i2 <= s2.length(); i2++){
if(s3.charAt(i2 - 1) == s2.charAt(i2 - 1)) {
matched[0][i2] = true;
}else break;
}
for(int i1 = 1; i1 <= s1.length(); i1++){
char c1 = s1.charAt(i1 - 1);
for(int i2 = 1; i2 <= s2.length(); i2++){
int i3 = i1 + i2;
char c2 = s2.charAt(i2 - 1);
char c3 = s3.charAt(i3 - 1);
if(c1 == c3){
matched[i1][i2] |= matched[i1 - 1][i2];
}
if(c2 == c3){
matched[i1][i2] |= matched[i1][i2 - 1];
}
}
}
return matched[s1.length()][s2.length()];
} |
034d79d4-489c-48c9-b915-3510e97c85f1 | 5 | private void setToBlack(byte[] buffer, int lineOffset, int bitOffset,
int numBits) {
int bitNum = (8 * lineOffset) + bitOffset;
int lastBit = bitNum + numBits;
int byteNum = bitNum >> 3;
// Handle bits in first byte
int shift = bitNum & 0x7;
if (shift > 0) {
int maskVal = 1 << (7 - shift);
byte val = buffer[byteNum];
while ((maskVal > 0) && (bitNum < lastBit)) {
val |= maskVal;
maskVal >>= 1;
++bitNum;
}
buffer[byteNum] = val;
}
// Fill in 8 bits at a time
byteNum = bitNum >> 3;
while (bitNum < (lastBit - 7)) {
buffer[byteNum++] = (byte) 255;
bitNum += 8;
}
// Fill in remaining bits
while (bitNum < lastBit) {
byteNum = bitNum >> 3;
buffer[byteNum] |= (1 << (7 - (bitNum & 0x7)));
++bitNum;
}
} |
ba1005c8-0bd1-4bb0-b8ef-d78387b51cfc | 9 | public static List<Item> itemList(List<? extends Item> items, char c, HTTPRequest httpReq, boolean one)
{
if(items==null)
items=new Vector<Item>();
final Vector<Item> classes=new Vector<Item>();
List<Item> itemlist=null;
if(httpReq.isUrlParameter(c+"ITEM1"))
{
itemlist=RoomData.getItemCache();
for(int i=1;;i++)
{
final String MATCHING=httpReq.getUrlParameter(c+"ITEM"+i);
if(MATCHING==null)
break;
Item I2=RoomData.getItemFromAnywhere(itemlist,MATCHING);
if(I2==null)
{
I2=RoomData.getItemFromAnywhere(items,MATCHING);
if(I2!=null)
RoomData.contributeItems(new XVector(I2));
}
if(I2!=null)
classes.addElement(I2);
if(one)
break;
}
}
return classes;
} |
2c8ae5c6-8b80-41e3-850f-161c352bbffc | 2 | public void update(int delta){
if(direction==LEFT){
setX(getX()-(SPEED*delta));
}else if(direction==RIGHT){
setX(getX()+(SPEED*delta));
}
} |
c650bfe4-cba2-4515-b86f-fce2d4e0aedb | 7 | public ConditionalEditor() {
setTitle("Conditional Editor");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
switch(tabbedPane.getSelectedIndex()) {
case(0):
selfSwitch = true;
variable = false;
equipment = false;
break;
case(1):
selfSwitch = false;
variable = true;
equipment = false;
break;
case(2):
selfSwitch = false;
variable = false;
equipment = true;
break;
}
}
});
tabbedPane.setBounds(0, 0, 434, 227);
contentPanel.add(tabbedPane);
JPanel selfSwitchTab = new JPanel();
tabbedPane.addTab("Self Switch", null, selfSwitchTab, null);
selfSwitchTab.setLayout(null);
JLabel lblIf = new JLabel("If");
lblIf.setBounds(12, 13, 46, 14);
selfSwitchTab.add(lblIf);
rdbtnA = new JRadioButton("A");
rdbtnA.setSelected(true);
buttonGroup.add(rdbtnA);
rdbtnA.setBounds(22, 36, 50, 23);
selfSwitchTab.add(rdbtnA);
rdbtnB = new JRadioButton("B");
buttonGroup.add(rdbtnB);
rdbtnB.setBounds(76, 36, 50, 23);
selfSwitchTab.add(rdbtnB);
rdbtnC = new JRadioButton("C");
buttonGroup.add(rdbtnC);
rdbtnC.setBounds(130, 36, 50, 23);
selfSwitchTab.add(rdbtnC);
rdbtnD = new JRadioButton("D");
buttonGroup.add(rdbtnD);
rdbtnD.setBounds(184, 36, 50, 23);
selfSwitchTab.add(rdbtnD);
JLabel lblIsTrue = new JLabel("Is true");
lblIsTrue.setBounds(12, 68, 46, 14);
selfSwitchTab.add(lblIsTrue);
JPanel variableTab = new JPanel();
tabbedPane.addTab("Variable", null, variableTab, null);
variableTab.setLayout(null);
JLabel lblIf_1 = new JLabel("If");
lblIf_1.setBounds(12, 13, 46, 14);
variableTab.add(lblIf_1);
variableCombo = new JComboBox<String>();
variableCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
greaterSpinner.setEnabled(false);
lessThanSpinner.setEnabled(false);
equalToSpinner.setEnabled(false);
matchText.setEnabled(false);
char type = ((String)variableCombo.getSelectedItem()).charAt(((String)variableCombo.getSelectedItem()).indexOf(';') + 1);
switch(type) {
case 'I':
greaterSpinner.setEnabled(true);
greaterSpinner.setModel(new SpinnerNumberModel(new Integer(0), null, null, new Integer(1)));
lessThanSpinner.setEnabled(true);
lessThanSpinner.setModel(new SpinnerNumberModel(new Integer(0), null, null, new Integer(1)));
equalToSpinner.setEnabled(true);
equalToSpinner.setModel(new SpinnerNumberModel(new Integer(0), null, null, new Integer(1)));
break;
case 'B':
break;
case 'F':
greaterSpinner.setEnabled(true);
greaterSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
lessThanSpinner.setEnabled(true);
lessThanSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
equalToSpinner.setEnabled(true);
equalToSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
break;
case 'S':
matchText.setEnabled(true);
break;
}
}
});
variableCombo.setModel(buildVariableModel());
variableCombo.setBounds(22, 40, 115, 22);
variableTab.add(variableCombo);
lblGreaterThan = new JRadioButton(">");
lblGreaterThan.setSelected(true);
buttonGroup_1.add(lblGreaterThan);
lblGreaterThan.setBounds(32, 75, 46, 14);
variableTab.add(lblGreaterThan);
greaterSpinner = new JSpinner();
greaterSpinner.setModel(new SpinnerNumberModel(new Integer(0), null, null, new Integer(1)));
greaterSpinner.setEnabled(false);
greaterSpinner.setBounds(91, 73, 46, 20);
variableTab.add(greaterSpinner);
lessSpinner = new JRadioButton("<");
buttonGroup_1.add(lessSpinner);
lessSpinner.setBounds(145, 75, 56, 14);
variableTab.add(lessSpinner);
lessThanSpinner = new JSpinner();
lessThanSpinner.setEnabled(false);
lessThanSpinner.setBounds(204, 73, 46, 20);
variableTab.add(lessThanSpinner);
equalSpinner = new JRadioButton("==");
buttonGroup_1.add(equalSpinner);
equalSpinner.setBounds(258, 75, 46, 14);
variableTab.add(equalSpinner);
equalToSpinner = new JSpinner();
equalToSpinner.setEnabled(false);
equalToSpinner.setBounds(314, 73, 46, 20);
variableTab.add(equalToSpinner);
JLabel lblMatches = new JLabel("Matches");
lblMatches.setBounds(42, 110, 46, 14);
variableTab.add(lblMatches);
matchText = new JTextField();
matchText.setEnabled(false);
matchText.setBounds(107, 106, 116, 22);
variableTab.add(matchText);
matchText.setColumns(10);
JPanel equipmentTab = new JPanel();
tabbedPane.addTab("Equipment", null, equipmentTab, null);
equipmentTab.setLayout(null);
goldRadio = new JRadioButton("Gold");
goldRadio.setSelected(true);
goldRadio.setBounds(6, 50, 109, 23);
equipmentTab.add(goldRadio);
goldGreater = new JRadioButton(">");
goldGreater.setSelected(true);
buttonGroup_2.add(goldGreater);
goldGreater.setBounds(16, 76, 33, 23);
equipmentTab.add(goldGreater);
goldGreaterSpinner = new JSpinner();
goldGreaterSpinner.setBounds(55, 77, 42, 20);
equipmentTab.add(goldGreaterSpinner);
goldLess = new JRadioButton("<");
buttonGroup_2.add(goldLess);
goldLess.setBounds(105, 76, 33, 23);
equipmentTab.add(goldLess);
goldLessSpinner = new JSpinner();
goldLessSpinner.setBounds(144, 77, 42, 20);
equipmentTab.add(goldLessSpinner);
goldEqual = new JRadioButton("=");
buttonGroup_2.add(goldEqual);
goldEqual.setBounds(192, 76, 33, 23);
equipmentTab.add(goldEqual);
goldEqualSpinner = new JSpinner();
goldEqualSpinner.setBounds(231, 77, 42, 20);
equipmentTab.add(goldEqualSpinner);
equipmentActivator = new JRadioButton("Activator");
buttonGroup_3.add(equipmentActivator);
equipmentActivator.setSelected(true);
equipmentActivator.setBounds(6, 11, 69, 23);
equipmentTab.add(equipmentActivator);
equipmentSource = new JRadioButton("Source");
buttonGroup_3.add(equipmentSource);
equipmentSource.setBounds(77, 11, 69, 23);
equipmentTab.add(equipmentSource);
equipmentSelect = new JRadioButton("Select...");
buttonGroup_3.add(equipmentSelect);
equipmentSelect.setBounds(144, 11, 69, 23);
equipmentTab.add(equipmentSelect);
selectBox = new JComboBox<String>();
selectBox.setModel(buildSelectCombo());
selectBox.setBounds(219, 11, 109, 22);
equipmentTab.add(selectBox);
JSeparator separator = new JSeparator();
separator.setBounds(6, 41, 413, 2);
equipmentTab.add(separator);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
} |
4afca25c-d963-4ba9-b059-079b3896d044 | 7 | @Override
public void run() {
mainLoop:
while (true) {
// update running status
for (int i = 0; i < maxClients; i++) {
running[i] = listeners[i].clientRunning();
success[i] = listeners[i].success();
}
boolean tmp = true;
// check running status
int succ = 0;
for (int i = 0; i < maxClients; i++) {
if (running[i]) {
tmp = true;
break;
} else {
tmp = false;
if(success[i]){
succ++;
}
}
}
if (!tmp) {
// Everything finished running
elapsed = System.currentTimeMillis() - start;
System.out.println("Sent " + maxPackets * maxClients + " packets in " + elapsed + "ms");
System.out.println("Connections: " + succ + " succeeded, " + (maxClients-succ) + " failed.");
break;
}
try {
Thread.sleep(5);
} catch (InterruptedException ie) {
}
}
} |
9ae1c4ad-0550-404d-99c0-d60802d6a79e | 5 | public void changeSignature(String person, String path, String newSign) {
try {
ArrayList<User> users = DataBase.getInstance().getUsers();
for (Iterator it = users.iterator(); it.hasNext();) {
User user = (User) it.next();
if (user.getLogin().equals(person)) {
ArrayList<SignatureFile> files = user.getFiles();
for (Iterator iti = files.iterator(); iti.hasNext();) {
SignatureFile file = (SignatureFile) iti.next();
if (file.getFile().getAbsolutePath().equals(path)) {
SignatureGenerator generator = new SignatureGenerator();
generator.setSignatureListener(new GeneratorListener(file));
file.setAlgorithm(newSign);
generator.execute(file, user.getKeys().getPrivateKey());
DataBase.getInstance().save();
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
Logger.getLogger(ChangeSignature.class.getName()).log(Level.SEVERE, null, e);
}
} |
9532b099-f4b1-4c2b-b465-f101e9f3ef1b | 0 | @Override
public DataStructures getKit(){
return outData;
} |
68636602-3668-4a13-87cc-2d46a8c5c4eb | 9 | public boolean canMove(int player, Point position) throws
IllegalMoveException,
CorruptedBoardException,
GameEndedException,
DrawGameEndedException{
//previousBoard.print("PRZED RUCHEM (S)");
//checking if boards are equal
try{
areBoardsEqual();
}catch(CorruptedBoardException e){
throw e;
}
//checking if there is any empty field
if(!Gomoku.game.board.any(GomokuBoardState.EMPTY)){
throw new DrawGameEndedException(position);
}
// checking if move is not outside the board
if((position.x >= 0) && (position.x < rules.getSizeRectangle().width) && (position.y >= 0) && (position.y < rules.getSizeRectangle().height)){
//checking if field is empty
if(Gomoku.game.board.get(position) == GomokuBoardState.EMPTY){
//checking if it is first move
if(history.empty()){
previousBoard.clean();
}
//state of a field depends on which of players takes turn
previousBoard.set(position, GomokuBoardState.values()[player]);
history.push((Point) position.clone());
//previousBoard.print("PO RUCHU (S)");
//checking if one of players won
ArrayList<Point> tempListOfPoints = puttedMInRow(position, rules.getInRowToWin(), player);
if(!tempListOfPoints.isEmpty()){
throw new GameEndedException(position, tempListOfPoints);
}
return true;
}
}
throw new IllegalMoveException(position);
} |
57586bc5-9b71-4b1f-ba8a-a8608bd8f8f9 | 7 | public mainClass() {
long startTime = System.nanoTime();
//System.out.println("Time 1: " + (System.nanoTime() - startTime) / 1000000);
Globals.getInstance().mainFrame = this;
Globals.getInstance().listsPacks = this;
Globals.getInstance().initializeFolders();
Globals.getInstance().loadPreferences();
long tempTime = System.nanoTime();
Globals.getInstance().updateListings();
System.out.println("Perm listings update took: " + (System.nanoTime() - tempTime) / 1000000);
this.setTitle("Permissions Checker v 1.2.6"); // Set the window title
this.setPreferredSize(new Dimension(1100, 600)); // and the initial size
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
modPacksModel = new SortedListModel<>();
loadPacks(Globals.getInstance().preferences.saveFolder);
modPacksList = new NamedScrollingListPanel<>("ModPacks", 200, modPacksModel, true);
modPacksList.setAlignmentX(Component.LEFT_ALIGNMENT);
modPacksPanel = new ModPacksPanel(modPacksList);
Globals.getInstance().addListener(modPacksPanel);
updatePanel = new UpdatePanel();
Globals.getInstance().addListener(updatePanel);
permissionsPanel = new PermissionsPanel();
Globals.getInstance().addListener(permissionsPanel);
updatePanel.permPanel = permissionsPanel;
modPacksList.addListener(new NamedScrollingListPanelListener() {
@Override
public void selectionChanged(NamedSelectionEvent event) {
if(oldSelection != null && oldSelection.equals(modPacksList.getSelected())) return;
Globals.getInstance().setModPack(modPacksList.getSelected());
oldSelection = modPacksList.getSelected();
modPacksList.revalidate();
}
});
modPacksList.setSelected(0);
leftPanel.add(modPacksList);
this.add(leftPanel, BorderLayout.LINE_START);
tabbedPane = new JTabbedPane();
tabbedPane.add("Info", modPacksPanel);
tabbedPane.add("Update", updatePanel);
tabbedPane.add("Permissions", permissionsPanel);
this.add(tabbedPane);
JMenuBar menuBar = new JMenuBar(); // create the menu
JMenu menu = new JMenu("Temp"); // with the submenus
menuBar.add(menu);
JMenuItem updatePerms = new JMenuItem("Update Permissions");
updatePerms.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Globals.getInstance().updateListings();
permissionsPanel.invalidateContents();
}
});
menu.add(updatePerms);
JMenuItem newPack = new JMenuItem("Add pack");
newPack.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
addPack();
}
});
menu.add(newPack);
JMenuItem newPackFromCode = new JMenuItem("Add pack from code");
newPackFromCode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String code = JOptionPane.showInputDialog(
Globals.getInstance().mainFrame, "Pack code", "Add pack",
JOptionPane.PLAIN_MESSAGE);
if(code == null || code.length() <= 0) return;
ModPack temp = FileUtils.packFromCode(code).get(0);
if(temp == null) {
System.out.println("Couldn't find code");
return;
}
System.out.println("Adding pack "+temp);
temp.key = code;
addPack(temp);
}
});
menu.add(newPackFromCode);
JMenuItem openFolder = new JMenuItem("Open appdata");
openFolder.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!OsTypes.getOperatingSystemType().equals(OsTypes.OSType.Windows)) {
System.out.println("Os is not windows, can't open explorer");
return;
}
try {
Desktop.getDesktop().open(Globals.getInstance().appStore);
} catch (IOException e) {
System.out.println("Couldn't open explorer");
return;
}
}
});
menu.add(openFolder);
JMenuItem drastic = new JMenuItem("Drastic click here");
drastic.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(Globals.getInstance().mainFrame,
"More ram has been downloaded to your system.\nHave a nice day.");
}
});
menu.add(drastic);
this.setJMenuBar(menuBar);
pack();
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
setVisible(true);
long endTime = System.nanoTime();
System.out.println("Startup took: " + (endTime - startTime) / 1000000);
} |
180d8647-799f-43ca-957f-d617fa5daf7b | 3 | public SingleTreeNode treePolicy(StateObservation state) {
SingleTreeNode cur = this;
while (!state.isGameOver() && cur.m_depth < ROLLOUT_DEPTH)
{
if (cur.notFullyExpanded()) {
return cur.expand(state);
} else {
SingleTreeNode next = cur.uct(state);
cur = next;
}
}
return cur;
} |
9b5131b4-64ea-414f-8c04-f236e3f7544e | 2 | private void addSensorEx(){
Sensor input = new Sensor();
input.setUnity("m");
input.setAddDate(new Date(System.currentTimeMillis()));
input.setLowBattery(false);
input.setStatementFrequency(1222);
input.setSamplingFrequency(1000);
input.setGpsLocation(-0.127512, 51.507222);
input.setName("Sensor_Arrow");
input.setSensorType(SensorType.ARROW);
try {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource(URL_SERVEUR);
ClientResponse response = webResource.path("rest").path("sensor").path("post").accept("application/json").type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Sensor : " + output);
} catch (Exception e) {
e.printStackTrace();
}
} |
8a677d18-8cbb-4dd4-a65e-4424d1edfb55 | 0 | public static int getMaxStandardGenreId()
{
return MAX_STANDARD_GENRE_ID;
} |
dd5aa8a6-8d4b-4d3a-9be4-4a92fb3f6292 | 5 | public void changeSocket( int port, String host )
{
Socket newSocket;
System.out.println( "Connecting to " + host + ":" + port );
try
{
newSocket = new Socket( host, port );
System.out.println( "Connected to new socket" );
}
catch( ClosedByInterruptException ex )
{
System.out.println( "input stream interrupted" );
return;
}
catch( UnknownHostException ex )
{
System.out.println( "exception thrown in change socket line " + ex.getLocalizedMessage() );
ex.printStackTrace();
return;
}
catch( IOException ex )
{
System.out.println( "exception thrown in change socket line " + ex.getLocalizedMessage() );
ex.printStackTrace();
return;
}
if( newSocket.isConnected() )
{
System.out.println( "killing threads" );
inputListener.interrupt();
System.out.println( "InputListener killed" );
outputWritter.interrupt();
System.out.println( "OutputListener killed" );
this.socket = newSocket;
System.out.println( "Getting new listeners" );
try
{
outputWritter = new Thread( new OutputSender( outputBlockingQueue, newSocket ) );
outputWritter.start();
System.out.println( "has new output listener" );
inputListener = new Thread( new InputListener( actionsBlockingQueue, newSocket ) );
inputListener.start();
System.out.println( "has new Input listener" );
}
catch( Exception ex )
{
System.out.println( "exception thrown in change socket line " + ex.getLocalizedMessage() );
ex.printStackTrace();
}
System.out.println( "connected" );
}
} |
0ff03725-0f7d-4331-8934-71937052ef95 | 7 | boolean canMove() {
if (!isFull()) {
return true;
}
for (int x : _0123) {
for (int y : _0123) {
Tile t = tileAt(x, y);
if ((x < ROW - 1 && t.equals(tileAt(x + 1, y)))
|| (y < ROW - 1 && t.equals(tileAt(x, y + 1)))) {
return true;
}
}
}
return false;
} |
1609d831-af03-4855-b032-7e38c8b5727c | 5 | private void exec(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (DEBUG) {
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line != null) {
System.out.println(line);
line=reader.readLine();
}
}
}
catch(IOException e1) {}
catch(InterruptedException e2) {}
if (DEBUG) System.out.println("Finished running command: '" + cmd + "'");
} |
1928379a-bbc5-476f-ad63-8db0ac8a1e8e | 2 | @Override
public Writer addRecordEntry(final String columnName, final Object value) {
if (value != null) {
final ColumnMetaData metaData = this.getColumnMetaData(columnName);
final String valueString = value.toString();
if (valueString.length() > metaData.getColLength()) {
throw new IllegalArgumentException(valueString + " exceeds the maximum length for column " + columnName + "("
+ metaData.getColLength() + ")");
}
}
return super.addRecordEntry(columnName, value);
} |
01f667d9-3793-401d-8c83-cafaecb9841c | 1 | public void addVertices(Vertex[] vertices, int[] indices,
boolean calcNormals) {
if (calcNormals) {
calcNormals(vertices, indices);
}
size = indices.length;
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices),
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
Util.createFlippedBuffer(indices), GL_STATIC_DRAW);
} |
e2fdfa9a-f561-46ab-89c8-abb4e734fc1a | 5 | public void izvrsi(HttpServletRequest req, HttpServletResponse res){
try{
int opcija=Integer.parseInt(req.getParameter("rd"));
atributPretrage="";
if(opcija==1){
atributPretrage = "naziv";
}
if(opcija==2){
atributPretrage = "opis";
}
if(opcija==3){
atributPretrage = "kolicina";
}
if(opcija==4){
atributPretrage = "cena";
}
//req.getSession().setAttribute("atributPretrage", atributPretrage);
ArrayList<ProizvodBean> proizvodi = Kontroler.getInstance().pretragaProizvoda(atributPretrage, kljucnaRec);
session.setAttribute("proizvodi", proizvodi);
}
catch(Exception e){
e.printStackTrace();
greska="Konekcija sa bazom podataka nije uspostavljena!\n"+e;
proslediGresku(greska, req, res);
greska="";
}
} |
b04d5bb7-8267-4d87-91f1-1c37748559d9 | 8 | @Override
public void handle(Log log) {
String start = (String) this.getProperties().get("StartTime");
String end = (String) this.getProperties().get("EndTime");
if(start == null || end == null){
throw new IllegalArgumentException("Start and End Time NOT null");
}
List<Log> result = new ArrayList<Log>();
log.setResult(result);
Log _log = new Log(log.getName());
_log.appendName(start + "+").appendName(end);
result.add(_log);
List<String> content = log.getContent();
String currentDate = null;
boolean found = false;
for (String line : content) {
if (!matchDate(line)) {
if (currentDate == null) {
System.out.println("CurrentThreadName is NULL");
continue;
}
if (found) {
_log.getContent().add(line);
}
continue;
}
Matcher m = STARTWITH_DATE.matcher(line);
m.find();
String date = m.group().substring(0, 8);
if (bigger(date, start) && bigger(end, date)) {
found = true;
_log.getContent().add(line);
} else {
found = false;
}
}
} |
4aaa050d-e709-475b-8492-a0f14e65b4f6 | 6 | Object remove(Object key) throws IOException {
int hash = hashCode(key);
long child_recid = _children[hash];
if (child_recid == 0) {
// not bucket/page --> not found
return null;
} else {
HashNode node = (HashNode) _recman.fetch( child_recid );
// System.out.println("HashDirectory.remove() child is : "+node);
if (node instanceof HashDirectory) {
// recurse into next directory level
HashDirectory dir = (HashDirectory)node;
dir.setPersistenceContext( _recman, child_recid );
Object existing = dir.remove(key);
if (existing != null) {
if (dir.isEmpty()) {
// delete empty directory
_recman.delete(child_recid);
_children[hash] = 0;
_recman.update(_recid, this);
}
}
return existing;
} else {
// node is a bucket
HashBucket bucket = (HashBucket)node;
Object existing = bucket.removeElement(key);
if (existing != null) {
if (bucket.getElementCount() >= 1) {
_recman.update(child_recid, bucket);
} else {
// delete bucket, it's empty
_recman.delete(child_recid);
_children[hash] = 0;
_recman.update(_recid, this);
}
}
return existing;
}
}
} |
8382f315-c1c3-4d25-98fc-57f274e145ce | 5 | @SuppressWarnings("unused") // For the console clearer below.
public static void main(String[] args) throws InterruptedException {
// System.out.println("The other threads dont like all these turtles"
// + " drawing over each other,\nJust ignore the oncomming spam");
World world = new World();
Turtle starter = new Turtle(300, 400, world);
starter.setPenColor(FRACTAL_COLOR);
starter.hide();
starter.setPenWidth(FRACTAL_WIDTH);
int phase = LEN;
Set<Turtle> turtles = new HashSet<>();
turtles.add(starter);
while(world.isShowing() && phase >= 10) {
turtles.addAll(world.getTurtleList());
for(Turtle t : turtles) {
t.forward(phase);
normalize(t);
Turtle copy = copy(t, world);
normalize(copy);
copy.turnLeft();
t.turnRight();
}
phase *= SCALE;
Thread.sleep(TIMEOUT);
}
for( int i : new Range(10).range()) {
System.out.print("\n");
}
System.out.println("Close the window to end the program");
while(world.isShowing()) {} // Wait until the program is closed
} |
d4fc4f0b-e252-4d7f-9f13-b96db300bdc1 | 4 | public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
} |
28a4e8b9-c0e7-42c1-adb4-390f09db5176 | 9 | public Agent(int color, boolean learn){
bestMove = nullMove;
this.color = color;
if(color == Piece.BLACK){
currentMove = 1;
}
DatabaseParser parser = new DatabaseParser();
allOpeningMoves = parser.parseOpenings();
values = new HashMap<String, Integer>();
if(learn){
values.put("pawn",10);
values.put("bishop",30);
values.put("knight",30);
values.put("rook",50);
values.put("queen",90);
values.put("king",1000);
Random rand = new Random();
for(String s: values.keySet()){
int value = values.get(s);
value += rand.nextInt(value/2 - value/4);
values.put(s, value);
}
values.put("empty",0);
}else{
try {
BufferedReader reader = new BufferedReader(new FileReader("results.txt"));
int[] vals = new int[6];
int count = 0;
while(reader.ready()){
String line = reader.readLine();
if(line.equals("win") || line.equals("draw")){
count++;
for(int i=0; i<6; i++){
line = reader.readLine();
String[] split = line.split("=");
int value = Integer.parseInt(split[1]);
vals[i] += value;
}
}
}
for(int i=0; i<6; i++){
vals[i] = vals[i]/count;
}
values.put("pawn",vals[0]);
values.put("bishop",vals[1]);
values.put("knight",vals[2]);
values.put("rook",vals[3]);
values.put("queen",vals[4]);
values.put("king",vals[5]);
values.put("empty",0);
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
5845db06-351e-492d-9edf-66b7a1edc8fa | 1 | public static synchronized Compiler singleton(URLClassLoader parent) {
if (instance == null) {
instance = new Compiler(parent);
}
return instance;
} |
66df8908-3500-4484-adbc-02a17f2df1a7 | 3 | public Expression combine(CombineableOperator comb) {
Operator combOp = (Operator) comb;
if (comb.lvalueMatches(this)) {
/* We already checked in canCombine that subExpressions match */
comb.makeNonVoid();
combOp.parent = parent;
return combOp;
}
for (int i = 0; i < subExpressions.length; i++) {
Expression combined = subExpressions[i].combine(comb);
if (combined != null) {
subExpressions[i] = combined;
updateType();
return this;
}
}
return null;
} |
144dc041-7e57-4e96-a54c-ff6fb7a63376 | 9 | public void BuildAdventureWorld(String AdventureFile) throws IOException
{
String line;
String data[];
Scanner scan = new Scanner (new File(AdventureFile));
for (int linenr = 1; scan.hasNextLine (); ++linenr) {
//looking for "r,d,o,t"
//split line
//split command --> myString.split("\\s+");
line = scan.nextLine();
data = line.split(" ");
//Description
if (data[0].equals("d")&&CurrentRoom!=null) {
//read description from the file and update Room Description property
CurrentRoom.AddDescription(line.substring(1).trim());
//update hash map
//GameWorld.put(CurrentRoom.Name, CurrentRoom);
}
//Tag
else if (data[0].equals ("t")&&CurrentRoom!=null) {
CurrentRoom.AddTag(data[1]);
//GameWorld.put(CurrentRoom.Name, CurrentRoom);
}
//Options
else if (data[0].equals("o")&&CurrentRoom!=null) {
CurrentRoom.AddOption(line.substring(1).trim());
//update hash map
//GameWorld.put(CurrentRoom.Name, CurrentRoom);
}
//Make Room
else if (data[0]. equals("r")) {
Room tempRoom = new Room();
//need to add roomName to hashTable
tempRoom.Name = data[1];
//insert new room into hashmap
GameWorld.put (data[1],tempRoom);
//set Current room
CurrentRoom = tempRoom;
if (linenr==1) FirstRoomTag=tempRoom.Name;
}
}
scan.close();
return;
} |
ab3d463a-1b5a-467c-ac24-7036678b9f8d | 2 | public String getTypeSignature() {
if (clazz != null)
return "L" + clazz.getName().replace('.', '/') + ";";
else if (ifaces.length > 0)
return "L" + ifaces[0].getName().replace('.', '/') + ";";
else
return "Ljava/lang/Object;";
} |
7df5bc52-9f42-4fc1-a4ab-bad46e10211b | 8 | public static int[] twoPair(Carta[] j){
int[] arr = new int[15];
for (int i = 0; i < j.length; i++)
arr[j[i].valor]++;
int par1 = 0, par2 = 0, remaining = 0;
for (int i = 0; i < arr.length; i++)
if(arr[i] == 2 && par1==0)par1 = i;
else if(arr[i] == 2)par2 = i;
else if(arr[i] == 1)remaining = i;
return par1>0&&par2>0?new int[]{max(par1, par2), min(par1, par2), remaining}:null;
} |
d6050d6e-31a9-4e16-8712-56808eb036c7 | 6 | @Override
public void valueUpdated(Setting s, Value v) {
if (s.getName().equals(EndTrigger)) {
try {
boolean b = v.getBoolean();
if (b && endTrigger_ == null) {
endTrigger_ = addOutput("End trigger", ValueType.VOID);
} else if (!b && endTrigger_ != null) {
removeOutput(endTrigger_);
endTrigger_ = null;
}
} catch (Exception e) {
e.printStackTrace();
}
} else
super.valueUpdated(s, v);
} |
685b94c9-9aad-4001-98c8-07f11af4da5c | 2 | public void start() {
if(thread == null) {
thread = new Thread(this);
}
if(thread.getState() == Thread.State.NEW) {
thread.start();
}
} |
fc8b0dde-a6de-4f12-8d90-d76bfaecdbf7 | 3 | private void updateStateNotFound(List<Keyword> keywords, List<String> terms, List<String> approval) {
if (approval.size() == 1) {
if (approval.get(0).equals("yes") || approval.get(0).equals("Yes")) {
getCurrentDialogState().setCurrentState(Start.S_WAITING_FOR_EMPLOYEE_STATUS);
return;
}
else {
getCurrentDialogState().setCurrentState(Start.S_USER_DOESNT_WANT_TO_BE_SAVED);
getCurrentSession().setCurrentUser(new User());
return;
}
}
DialogManager.giveDialogManager().setInErrorState(true);
} |
d323b8ac-efa6-4260-8b2e-9fbab4a97d55 | 3 | public static Car driverCar(String car) throws Exception {
// 判断逻辑,返回具体的产品角色给Client
if (car.equalsIgnoreCase("Benz")) { // equalsIgnoreCase:String类的方法,两个字符串比较,不考虑大小写
return new Benz();
}
if (car.equalsIgnoreCase("Bmw")) {
return new Bmw();
}
if (car.equalsIgnoreCase("Audo")) {
return new Audo();
}
throw new Exception();
} |
e5ac963c-0827-4fbc-a672-b3325778e6b6 | 6 | private void initComponents() {
ListaAtracoes lstAtracoes = new ListaAtracoes();
PnlConjuntoImagens imagemMonumento = null;
JScrollBar scrollBar = new JScrollBar();
//Monumento mais Visto
Atracao monumento = lstAtracoes.monumetoMaisVisto();
try {
imagemMonumento = new PnlConjuntoImagens(monumento);
} catch (NullPointerException npe) {
}
JPanel painelMonumento = new JPanel();
painelMonumento.addMouseListener(acao(painelMonumento, monumento));
painelMonumento.setMinimumSize(new Dimension(300, 300));
painelMonumento.setPreferredSize(new Dimension(300, 300));
painelMonumento.setLayout(new BorderLayout());
painelMonumento.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
bundle.getString("monumento"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(51, 51, 255)));
JLabel lblMonumentoMaisVisto = new JLabel(bundle.getString("monumentoMaisVisto"));
lblMonumentoMaisVisto.setHorizontalAlignment(JLabel.CENTER);
painelMonumento.add(lblMonumentoMaisVisto, BorderLayout.PAGE_START);
if (imagemMonumento != null) {
painelMonumento.add(imagemMonumento.PnlPrimeiraImagen(300, 300), BorderLayout.CENTER);
painelMonumento.add(new JLabel(monumento.getNome(), JLabel.CENTER), BorderLayout.PAGE_END);
} else {
painelMonumento.add(new JLabel(bundle.getString("naoExisteMonumetosClassificados"), JLabel.CENTER), BorderLayout.CENTER);
}
//Restaurante Melhor Classificado
PnlConjuntoImagens imagemRestaurante = null;
restaurante = lstAtracoes.restauranteMelhorClassificado();
try {
imagemRestaurante = new PnlConjuntoImagens(restaurante);
} catch (NullPointerException npe) {
}
JPanel painelRestaurante = new JPanel();
painelRestaurante.addMouseListener(acao(painelRestaurante, restaurante));
painelRestaurante.setLayout(new BorderLayout());
painelRestaurante.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
bundle.getString("restaurante"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(51, 51, 255)));
JLabel lblmelhorRestaurante = new JLabel(bundle.getString("restauranteMelhorClassificado"));
lblmelhorRestaurante.setHorizontalAlignment(JLabel.CENTER);
painelRestaurante.add(lblmelhorRestaurante, BorderLayout.PAGE_START);
if (imagemRestaurante != null) {
painelRestaurante.add(imagemRestaurante.PnlPrimeiraImagen(300, 300), BorderLayout.CENTER);
painelRestaurante.add(new JLabel(restaurante.getNome(), JLabel.CENTER), BorderLayout.PAGE_END);
} else {
JLabel lblnaoRestaurante = new JLabel(bundle.getString("naoExisteRestaurantesClassificados"));
lblnaoRestaurante.setHorizontalAlignment(JLabel.CENTER);
painelRestaurante.add(lblnaoRestaurante, BorderLayout.CENTER);
}
//Hotel com mais comentarios
PnlConjuntoImagens imagemHotel = null;
Atracao hotel = lstAtracoes.hotelMaiscomentado();
try {
imagemHotel = new PnlConjuntoImagens(hotel);
} catch (NullPointerException npe) {
}
JPanel painelHotel = new JPanel();
painelHotel.addMouseListener(acao(painelHotel, hotel));
painelHotel.setLayout(new BorderLayout());
painelHotel.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
bundle.getString("hotel"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(51, 51, 255)));
JLabel lblMaisComentados = new JLabel(bundle.getString("hotelMaisComentarios"));
lblMaisComentados.setHorizontalAlignment(JLabel.CENTER);
painelHotel.add(lblMaisComentados, BorderLayout.PAGE_START);
if (imagemHotel != null) {
painelHotel.add(imagemHotel.PnlPrimeiraImagen(300, 300), BorderLayout.CENTER);
painelHotel.add(new JLabel(hotel.getNome(), JLabel.CENTER), BorderLayout.PAGE_END);
} else {
JLabel lblnaoComentarios = new JLabel(bundle.getString("naoExisteHoteiscomComentarios"));
lblnaoComentarios.setHorizontalAlignment(JLabel.CENTER);
painelHotel.add(lblnaoComentarios, BorderLayout.CENTER);
}
JPanel principal = new JPanel();
principal.setLayout(new GridLayout(1, 3));
principal.add(painelRestaurante);
principal.add(painelHotel);
principal.add(painelMonumento);
add(principal);
} |
35111258-e40b-4be3-bb2c-c4043a84fb8d | 1 | @Override
public void updateView() {
listModel.removeAllElements();
for (File p : controller.getModel().getFilesToExclude()) {
listModel.addElement(p);
}
excludedPathsList.setModel(listModel);
} |
dc2cc1e8-115b-4575-b128-a41cdb4da697 | 2 | @Override
public int hashCode()
{
return (sequence == null ? 0 : sequence.hashCode())
^ (value == null ? 0 : value.hashCode());
} |
9035a905-21d8-438d-9ed3-d88cf5d7c09f | 0 | public double getGyroAngle(){
return _gyro.getAngle();
} |
6bb97fc0-4420-4e62-b15a-e69b21165594 | 4 | public static String getHumanSpeed(Long speed) {
if (speed == null) {
return "";
}
String s = "";
double num = 0;
if (speed < 1024) {
num = speed;
} else if (speed < (1024 * 1024)) {
num = (double) speed / 1024;
s = "Kb/s";
} else if (speed < (1024 * 1024 * 1024)) {
num = (double) speed / (1024 * 1024);
s = "Mb/s";
} else {
num = (double) speed / (1024 * 1024 * 1024);
s = "Gb/s";
}
DecimalFormat oneDec = new DecimalFormat("0.0");
return oneDec.format(num) + " " + s;
} |
2d0e9a32-a30d-4b1c-84d9-bdf5d8504eb5 | 6 | public static int calcSoftFour(Session aSession, Lecture aLecture) {
int penalty = 0;
List<Student> studentsEnrolledInLec = aLecture.getEnrolledStudents();
for(Student student : studentsEnrolledInLec){
List<Lecture> studentsLectures = student.getEnrolledLectures();
List<Session> studentSessions = new ArrayList<Session>();
for(Lecture lecture: studentsLectures){
Session session = lecture.getSession();
if(session != null){
studentSessions.add(lecture.getSession());
}
}
int totalTimeOnDay = 0;
for(Session session: studentSessions){
if(session.getDay().equals(aSession.getDay())){
totalTimeOnDay += (session.getLength() + aSession.getLength());
}
}
if(totalTimeOnDay > 5){
penalty+=50;
}
}
return penalty;
} |
25cf1b92-afe5-4f3d-92ee-7aa5e57370c2 | 8 | private static ConnectedComponent findComponent(Long2ShortHashMapInterface hm, long startKmer,
LongArrayFIFOQueue queue,
int k, int b2, int newFreqThreshold) {
ConnectedComponent comp = new ConnectedComponent();
queue.clear();
boolean bigComp = false;
queue.enqueue(startKmer);
short value = hm.get(startKmer);
assert value > 0;
hm.put(startKmer, (short) -value); // removing
comp.add(startKmer, value);
while (queue.size() > 0) {
long kmer = queue.dequeue();
for (long neighbour : KmerOperations.possibleNeighbours(kmer, k)) {
value = hm.get(neighbour);
if (value > 0) { // i.e. if not precessed
queue.enqueue(neighbour);
hm.put(neighbour, (short) -value);
if (bigComp) {
if (value >= newFreqThreshold) {
comp.hm.put(neighbour, value);
}
comp.size++;
} else {
comp.add(neighbour, value);
if (comp.size == b2) {
// component is big one
bigComp = true;
comp.hm = new BigLong2ShortHashMap(4, 13);
for (long kk : comp.kmers) {
value = (short) -hm.get(kk);
assert value > 0;
if (value >= newFreqThreshold) {
comp.hm.put(kk, value);
}
}
comp.kmers = null;
}
}
}
}
}
return comp;
} |
dc743b65-1188-4675-86ba-8a467dbffb24 | 4 | public static String[] print(int[] result) {
String[] w = new String[result.length];
for (int i=0; i<w.length; i++) w[i] = "";
for (int i=0; i<result.length; i++) {
for (int j=0; j<result.length; j++) {
if(j == result[i]) {
w[i] = w[i] + "Q";
}
else {
w[i] = w[i] + ".";
}
}
}
return w;
} |
11266e52-3fd3-460b-a274-d86c4091d8bf | 0 | public static void main(String[] args) {
Demo02 demo = new Demo02();
demo.method_1(10, 20,new MyHanderInt() {
@Override
public int doThis(int a, int b) {
return a+b;
}
});
} |
29e44317-d930-4692-99fe-d07ba50bb65f | 4 | @Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
if(e.getSource().equals(file)){
new FilePopup(dw).show(source,0,getHeight());
}else if(e.getSource().equals(edit)){
new EditPopup(paint).show(source,0,getHeight());
}else if(e.getSource().equals(display)){
new DisplayPopup(dw).show(source,0,getHeight());
}else if(e.getSource().equals(help)){
new HelpPopup().show(source,0,getHeight());
}
} |
c5642cc7-3c4c-48e9-92dc-5ee37c8826f6 | 9 | public void keyPressed(boolean[] keys, KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode==37) parent.cellsManager.shiftSelectButton(-1);// left
if (keyCode==39) parent.cellsManager.shiftSelectButton(1);// right
if (keyCode==8) parent.cellsManager.deleteLastChar();
if (keyCode!=37 && keyCode!=39 && keyCode!=8 && keyCode!=16 && keyCode!=17 && keyCode!=18)
{
parent.cellsManager.write(e.getKeyChar());
}
} |
c3dee972-a93b-4dff-af03-87dd91190621 | 8 | @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("LineString")) {
inLineString = false;
}
if (inCoordinate && inLineString && qName.equals("coordinates")) {
String[] data = coordinates.toString().trim().split("\\s+");
double lastAlt = 0;
double distance = 0;
LatLngExtra lastPoint = null;
for (String p : data) {
//System.err.println("{{" + p + "}}");
String[] set = p.split(",");
double alt = Double.parseDouble(set[2]);
// Smoothing the altitude
double smoothAlt = lastAlt == 0 ? alt : SMOOTH_COEF
* lastAlt + (1 - SMOOTH_COEF) * alt;
lastAlt = smoothAlt;
LatLngExtra point = new LatLngExtra(
Double.parseDouble(set[1]),
Double.parseDouble(set[0]), smoothAlt);
if (lastPoint != null) {
distance += LatLngTool.distance(lastPoint, point,
LengthUnit.METER);
point.setDistance(Math.round(distance));
int bearing = (int) Math.round(LatLngTool
.initialBearing(lastPoint, point));
points.get(points.size() - 1).setBearing(bearing);
}
lastPoint = point;
points.add(point);
}
}
if (qName.equals("coordinates"))
{
inCoordinate = false;
}
} |
f084b5dc-80ff-4443-bd47-cb38ce615403 | 6 | public void actionPerformed(ActionEvent e) {
String selected = e.getActionCommand();
if (selected == "ダイアログ") {
displayDialog();
} else if(selected == "exit") {
Pref.saveLayout(getX(), getY());
Pref.save(tp.getBColor(), tp.getSColor(), tp.getFontName(), String.valueOf(tp.getFontSize()));
System.exit(0);
} else if(selected == "アナログ") {
tp.setDigitalFlag(false);
} else if(selected == "デジタル") {
tp.setDigitalFlag(true);
} else if (e.getActionCommand() == "OK") {
ok(dlg);
dlg.setVisible(false);
} else if (e.getActionCommand() == "Cancel") {
dlg.setVisible(false);
} else
System.out.println(e.getActionCommand());
} |
e40a98f1-1813-47aa-8120-c323ad71b6a4 | 8 | public static int[][] get(int x)
{
if(x == 1)
return level1;
else if(x == 2)
return level2;
else if (x == 3)
return level3;
else if (x == 4)
return level4;
else if(x == 5)
return level5;
else if (x == 6)
return level6;
else if (x == 7)
return level7;
else if (x == 8)
return level8;
else
return level9;
} |
35a8ebee-83be-4387-b186-128933413a2e | 5 | public double getCond() {
if (cond == Double.MIN_VALUE) {
Double max = Double.MIN_VALUE;
Double min = Double.MAX_VALUE;
double[] sngValues = getSingularValues();
for (int idx = 0; idx < sngValues.length; idx++) {
if (sngValues[idx] > max) {
max = sngValues[idx];
}
if (sngValues[idx] < min && sngValues[idx] > 1E-10) {
min = sngValues[idx];
}
}
cond = max / min;
}
return cond;
} |
7409360a-e685-4080-b1b2-7851fcbce236 | 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(VtnReporProveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VtnReporProveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VtnReporProveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VtnReporProveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VtnReporProveedores().setVisible(true);
}
});
} |
dc5b97e2-5878-4cf2-b8d3-55db77f00fd1 | 3 | @Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!typeKey.containsKey(o))
return false;
}
return true;
} |
63c4eec0-eecb-4975-adbe-b1cffff805cb | 0 | public void setPlayerSpawnLocation(Location playerspawn) {
this.playerspawn = playerspawn;
} |
206aedd4-7798-407d-9bd6-4938ac58f542 | 4 | public static void main(String[] rags) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] l = in.readLine().split(" ");
int n = Integer.parseInt(l[0]);
int total = n;
long c = Long.parseLong(l[1]);
ArrayList<Integer> chpts = new ArrayList<Integer>();
int index = 0;
l = in.readLine().split(" ");
while(n-->0){
chpts.add(Integer.parseInt(l[index]));
index++;
}
Collections.sort(chpts);
long result = 0;
for(int i=0;i<total;i++){
// System.out.println(chpts[i]+" "+c);
result+=c*((long)chpts.get(i));
if(c>1) c--;
else{
i++;
while(i<total){
result+=chpts.get(i);
i++;
}
}
}
System.out.println(result);
} |
bbf1567b-2924-47c6-81e1-20543f201bae | 7 | public boolean addFrame(BufferedImage im) {
if ((im == null) || !started) {
return false;
}
boolean ok = true;
try {
if (!sizeSet) {
// use first frame's size
setSize(im.getWidth(), im.getHeight());
}
image = im;
getImagePixels(); // convert to correct format if necessary
analyzePixels(); // build color table & map pixels
if (firstFrame) {
writeLSD(); // logical screen descriptior
writePalette(); // global color table
if (repeat >= 0) {
// use NS app extension to indicate reps
writeNetscapeExt();
}
}
writeGraphicCtrlExt(); // write graphic control extension
writeImageDesc(); // image descriptor
if (!firstFrame) {
writePalette(); // local color table
}
writePixels(); // encode and write pixel data
firstFrame = false;
} catch (IOException e) {
ok = false;
}
return ok;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.