method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
1c88b1e4-f52e-470d-93df-d998f306abc3
| 2
|
private static Map<String, Double> sortByComparator(Map<String, Double> unsortMap, final boolean order)
{
List<Entry<String, Double>> list = new LinkedList<Entry<String, Double>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Double>>()
{
public int compare(Entry<String, Double> o1,
Entry<String, Double> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
for (Entry<String, Double> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
|
f83f5f1b-1508-4149-8a9b-2f895d830ac9
| 1
|
@Override
public int attack(double agility, double luck) {
if(random.nextInt(100) < luck)
{
System.out.println("I just created an earthquake!");
return random.nextInt((int) agility) * 2;
}
return 0;
}
|
7cabbb24-d5fc-49eb-bf85-3e09be26d921
| 1
|
public void close_connection()
{
try
{
this.connection.close();
this.res_set.close();
this.connected = false;
}
catch(SQLException sqlEx)
{
System.err.println(sqlEx.getMessage());
}
}
|
5adc6715-2613-4a9d-898c-3d5a7f799de5
| 8
|
@Override
@SuppressWarnings("unchecked")
public int getHolidayIndex(String named)
{
final Object resp=getHolidayFile();
if(resp instanceof String)
{
return -1;
}
List<String> steps=null;
if(resp instanceof List)
steps=(List<String>)resp;
else
return -1;
Vector<String> lineV=null;
String line=null;
String var=null;
String cmd=null;
String step=null;
for(int v=1;v<steps.size();v++)
{
step=steps.get(v);
final List<String> stepV=Resources.getFileLineVector(new StringBuffer(step));
for(int v1=0;v1<stepV.size();v1++)
{
line=stepV.get(v1);
lineV=CMParms.parse(line);
if(lineV.size()>1)
{
cmd=lineV.elementAt(0).toUpperCase();
var=lineV.elementAt(1).toUpperCase();
if(cmd.equals("SET")&&(var.equalsIgnoreCase("NAME")))
{
final String str=CMParms.combine(lineV,2);
if(str.equalsIgnoreCase(named))
return v;
}
}
}
}
return -1;
}
|
7c6e6497-fb43-4bfd-9731-594314b24e0e
| 6
|
@EventHandler
public void onPlayerMoveIn(PlayerMoveEvent event){
final Player p = event.getPlayer();
String worldName = p.getWorld().getName();
if(worldName.contains("zombieRun")||worldName.equals("world")){
Material blockIsIn = p.getLocation().getBlock().getType();
World world = p.getWorld();
Location mapSpawn = world.getSpawnLocation();
if(blockIsIn == Material.WATER||blockIsIn == Material.STATIONARY_WATER){
p.teleport(mapSpawn);
p.sendMessage(ChatColor.RED + "[ZombieRun]" + ChatColor.AQUA + " Good luck next time!");
}else if(blockIsIn == Material.LAVA||blockIsIn == Material.STATIONARY_LAVA){
p.teleport(mapSpawn);
p.sendMessage(ChatColor.RED + "[ZombieRun]" + ChatColor.AQUA + " Good luck next time!");
}else{}
}
}
|
fb6d29ab-6de2-4748-8a8a-1bd2a6ab63dc
| 9
|
protected void quantize(String path, int numColors) throws IOException {
File file = new File(path).getCanonicalFile();
if (file == null || !file.exists() || !file.isFile() || !file.canRead()) {
throw new FileNotFoundException(path);
}
path = file.getAbsolutePath();
//Dither to DS colors
BufferedImage image = ImageIO.read(file);
int iw = image.getWidth();
int ih = image.getHeight();
int argb[] = image.getRGB(0, 0, iw, ih, null, 0, iw);
int alpha[] = new int[argb.length];
for (int n = 0; n < argb.length; n++) {
alpha[n] = argb[n] >>> 24;
argb[n] = 0xFF000000 | (argb[n] & 0xFFFFFF);
}
if (dithering) {
floydSteinberg(argb, iw, ih);
}
//Quantize to the number of colors we want
if (quant == Quant.NEUQUANT) {
image.setRGB(0, 0, iw, ih, argb, 0, iw);
ImageIO.write(image, "png", file);
Process p = ProcessUtil.execInDir(String.format(
"pngnq \"%s\" -n %d", path, numColors),
".");
ProcessUtil.waitFor(p);
ProcessUtil.kill(p);
file.delete();
new File(StringUtil.stripExtension(path)+"-nq8.png").renameTo(file);
image = ImageIO.read(file);
image.getRGB(0, 0, image.getWidth(), image.getHeight(),
argb, 0, image.getWidth());
} else if (quant == Quant.OCTREE) {
Octree tree = new Octree();
tree.quantize(argb, iw, numColors);
}
//Re-add alpha channel
for (int n = 0; n < argb.length; n++) {
argb[n] = (argb[n] & 0xFFFFFF) | (alpha[n]<<24);
}
image = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_ARGB);
image.setRGB(0, 0, iw, ih, argb, 0, iw);
ImageIO.write(image, "png", file);
//FileUtil.copyFile(file, new File(file.getParent()+"/temp2.png"));
}
|
ecf0ca17-40f3-4dd7-a496-611f0adf422f
| 4
|
public boolean checkSave()
{
if (hasChanged())
{
int c = JOptionPane.showConfirmDialog(frame,
Resources.getString("Jeie.UNSAVED_MESSAGE"),
Resources.getString("Jeie.UNSAVED_TITLE"),
JOptionPane.YES_NO_CANCEL_OPTION);
if (c == JOptionPane.CANCEL_OPTION) return false;
if (c == JOptionPane.YES_OPTION) return doSave(false);
if (c == JOptionPane.NO_OPTION) return true;
}
return true;
}
|
f9618388-4c9f-4721-92f1-a8f9fe2ef29a
| 7
|
public static boolean collidesWithRegion(SpaceRegion region, Vec3 position, Vec3 direction) {
// This is where the shit hits the fan
if ( region.isInside( position ) && direction.isValid() && !direction.isZero() ) {
//ok, that was easy. Even if very small, having a non-zero, valid,
//direction and being inside, means that at one point, that line
//gotta touch the inside walls of the region.
return true;
} else {
//here, I have a few options...I could go smart-ass and cheat
//or I could go with math and decompose into planes and check for intersections.
//I decided to go with math, for once.
for ( Direction d : Direction.values() ) {
if ( region instanceof Sector && ((Sector)region).links[ d.ordinal() ] == null ) {
continue;
}
if ( hitPlane( region, d, position, direction ) ) {
return true;
}
}
}
return false;
}
|
b1db5bcb-7279-418d-98eb-1ee75fc0434e
| 1
|
public GameLogging(Class<?> clazz) {
logger = LoggerFactory.getLogger(clazz);
}
|
a6e43d9c-fa75-45b5-b0fa-29011e2775d7
| 8
|
@Override
public double getDoubleVal()
{
Object pob = null;
Double d = null;
try
{
pob = getValue();
if( pob == null )
{
log.error( "Unable to calculate Formula at " + getLocation() );
return java.lang.Double.NaN;
}
d = (Double) pob;
}
catch( ClassCastException e )
{
try
{
Float f = (Float) pob;
d = f.doubleValue();
}
catch( ClassCastException e2 )
{
try
{
Integer in = (Integer) pob;
d = in.doubleValue();
}
catch( Exception e3 )
{
if( (pob == null) || pob.toString().equals( "" ) )
{
d = (double) 0;
}
else
{
try
{
Double dd = new Double( pob.toString() );
return dd;
}
catch( Exception e4 )
{// Logger.logWarn("Error in Ptg Calculator getting Double Value: " + e3);
return java.lang.Double.NaN;
}
}
}
}
}
catch( Throwable exp )
{
log.error( "Unexpected Exception in PtgCalculator.getDoubleValue()", exp );
}
return d;
}
|
a539423b-74a4-4c5c-add9-04308562261c
| 3
|
public String magnitudeString(int strength){
String convertedStrength;
if (strength == Relationship.HIGH){convertedStrength = "High";}
else if (strength == Relationship.MEDIUM){convertedStrength = "Med";}
else if (strength == Relationship.LOW){convertedStrength = "Low";}
else convertedStrength = "0";
return convertedStrength;
}
|
8d9d3c03-c710-4b8f-9fc6-583fa3558889
| 5
|
protected ListPanel getAlarmByFiremanId(int firemanId)
{
ArrayList<Time_Sheet> timeSheet = new ArrayList<Time_Sheet>();
ListPanel list = new ListPanel(parent.getWidth());
ArrayList<Alarm> alarms = new ArrayList<Alarm>();
try{
timeSheet = tsa.getTimeSheetsbyFiremanId(firemanId);
for(Time_Sheet c : timeSheet)
{
if(!arrayContainsAlarmId(alarms, c.getAlarmID())){
Alarm a = aal.getAlarmById(c.getAlarmID());
if ( a != null) alarms.add(a);
}
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(this, "Database call error: " + ex);
}
for(Alarm a : alarms){
list.addViewObject(ViewObjectFactory.getViewObject(a));
}
return list;
}
|
9c3b1da5-6596-48b6-ba24-3d98f9798cb1
| 9
|
private void assignAvailableMoves(){
// Track how many are available
int count = 0;
// Check every spot
for (int i = 0; i < 4; i++){
for (int j = 0; j < 12; j++){
// Anywhere is legal on first turn
if (turn == 0) {
available_locations[i][j] = true;
}
// If the spot is taken then it's not available
else if (board[i][j] != '.'){
available_locations[i][j] = false;
}
// Spot is available if it has an adjacent taken
else {
available_locations[i][j] = hasAdjacent(i, j);
}
// Keep count
if (available_locations[i][j]) {
count++;
}
}
}
if (count == 0) {
// This will throw an error- which we want to see rather than just having 0 possible moves.
available_locations_l = null;
}
else {
// Copy the locations into a list of Locations from the double-array
available_locations_l = new Location[count];
for (int r = 0; r < 4; r++){
for (int t = 0; t < 12; t++){
if (available_locations[r][t]){
available_locations_l[--count] = new Location(r, t);
}
}
}
}
}
|
726f0129-8ad6-48fd-ae56-a9aec17a2a3d
| 1
|
public void setGuardAngle(float angle) {
if(angle < 0) {
guardAngle = angle + MathUtil.PI * 2;
}
else {
guardAngle = angle;
}
}
|
498ac687-53a6-4fd9-ac76-469d5254406d
| 3
|
static final public void select_statement() throws ParseException {
String str;
String path;
jj_consume_token(SELECT);
System.out.println("Select\ubb38 \ud638\ucd9c!");
str = select_regex();
label_1:
while (true) {
jj_consume_token(39);
select_regex();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 39:
;
break;
default:
jj_la1[1] = jj_gen;
break label_1;
}
}
System.out.println("String " + str+ " \uad6c\ubb38 \ucd9c\ub825!");
jj_consume_token(FROM);
System.out.println("From \uad6c\ubb38 \ucd9c\ub825!");
path = from_path();
System.out.println("String " + path + " \uad6c\ubb38 \ucd9c\ub825!");
jj_consume_token(40);
System.out.println("; \uad6c\ubb38 \ucd9c\ub825!");
}
|
3510cb33-d2ca-43f1-879d-6dfcb631dc2c
| 9
|
protected void forward(DatasetExample example) {
int size = example.size();
// Initialize the alpha[0] values.
Vector<Double> first = alpha.get(0);
if (tagged[0]) {
// Set all state probabilities to zero.
for (int state = 0; state < numStates; ++state)
first.set(state, 0.0);
// Get the correct state.
int taggedState = example.getFeatureValue(0, stateFeature);
taggedState = model.featureToState.get(taggedState);
// Set its probability.
int emission = example.getFeatureValue(0, observationFeature);
double emisProb = model.getEmissionProbability(emission,
taggedState)
* model.getInitialStateProbability(taggedState);
first.set(taggedState, emisProb);
} else {
int emission = example.getFeatureValue(0, observationFeature);
for (int state = 0; state < numStates; ++state) {
double startProb = model
.getEmissionProbability(emission, state)
* model.getInitialStateProbability(state);
first.set(state, startProb);
}
}
for (int token = 1; token < size; ++token) {
// Get the emission symbol in this token.
int emission = example.getFeatureValue(token, observationFeature);
if (tagged[token]) {
// Set the probabilities of every state to zero.
for (int stateTo = 0; stateTo < numStates; ++stateTo)
alpha.get(token).set(stateTo, 0.0);
// Get the correct state.
int taggedState = example.getFeatureValue(token, stateFeature);
taggedState = model.featureToState.get(taggedState);
// Probability of arriving at this state (without emission).
double prevTokenProb = 0.0;
for (int stateFrom = 0; stateFrom < numStates; ++stateFrom) {
double transProb = model.getTransitionProbability(
stateFrom, taggedState);
prevTokenProb += transProb
* alpha.get(token - 1).get(stateFrom);
}
// Complete probability of arriving in this state and emits
// the current symbol.
double emisProb = model.getEmissionProbability(emission,
taggedState);
alpha.get(token).set(taggedState, emisProb * prevTokenProb);
} else {
for (int stateTo = 0; stateTo < numStates; ++stateTo) {
// Probability of arriving at this state (without emission).
double prevTokenProb = 0.0;
for (int stateFrom = 0; stateFrom < numStates; ++stateFrom) {
double transProb = model.getTransitionProbability(
stateFrom, stateTo);
prevTokenProb += transProb
* alpha.get(token - 1).get(stateFrom);
}
// Complete probability of arriving in this state and emits
// the current symbol.
double emisProb = model.getEmissionProbability(emission,
stateTo);
alpha.get(token).set(stateTo, emisProb * prevTokenProb);
}
}
}
}
|
8bcdb77e-ed1f-4cf8-8af5-508497b6fbdc
| 5
|
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final WorkType other = (WorkType) obj;
if (this.id != other.id) {
return false;
}
if ((this.workType == null) ? (other.workType != null) : !this.workType.equals(other.workType)) {
return false;
}
return true;
}
|
07bc8e4b-01c9-4515-9881-736faaa10665
| 5
|
private IService initService(Class<?> serviceClass, Properties properties) throws ServiceException{
if (IService.class.isAssignableFrom(serviceClass)){
IService service;
try {
service = (IService) serviceClass.newInstance();
service.init(properties);
return service;
} catch (InstantiationException e) {
throw new ServiceException(e.getMessage());
} catch (IllegalAccessException e) {
throw new ServiceException(e.getMessage());
} catch (ServiceException e) {
throw new ServiceException(e.getMessage());
}
}
throw new ServiceException("Can't instantiate service "+serviceClass.toString());
}
|
d019da00-efc6-4af2-a320-4aa0c0bed7c4
| 1
|
@Override
public Iterator<Data<?>> iterator() {
return data.iterator();
}
|
254abf6f-6684-4d49-9742-6984f0e137ee
| 4
|
private void calcula(String operador, String numero) {
int num = Integer.parseInt(numero);
switch (operador) {
case "+":
CALCULADO += num;
break;
case "-":
CALCULADO -= num;
break;
case "*":
CALCULADO *= num;
break;
case "/":
CALCULADO /= num;
break;
}
}
|
f6c08a0d-a62b-49c3-86e1-9367b3b7531e
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PeriodSBU other = (PeriodSBU) obj;;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (ourCompany == null) {
if (other.ourCompany != null)
return false;
} else if (!ourCompany.equals(other.ourCompany))
return false;
return true;
}
|
efc0f801-2cb9-4b4c-84aa-ef9ba020cc72
| 8
|
public byte[] getEContent() {
SignerInfo signerInfo = getSignerInfo(signedData);
ASN1Set signedAttributesSet = signerInfo.getAuthenticatedAttributes();
ContentInfo contentInfo = signedData.getEncapContentInfo();
byte[] contentBytes = ((DEROctetString) contentInfo.getContent())
.getOctets();
if (signedAttributesSet.size() == 0) {
/* Signed attributes absent, return content to be signed... */
return contentBytes;
} else {
/*
* Signed attributes present (i.e. a structure containing a hash of
* the content), return that structure to be signed...
*/
/*
* This option is taken by ICAO passports and assumingly by ISO18013
* license? TODO: ?
*/
byte[] attributesBytes = signedAttributesSet.getDEREncoded();
String digAlg = signerInfo.getDigestAlgorithm().getObjectId()
.getId();
try {
/*
* We'd better check that the content actually digests to the
* hash value contained! ;)
*/
Enumeration<?> attributes = signedAttributesSet.getObjects();
byte[] storedDigestedContent = null;
while (attributes.hasMoreElements()) {
Attribute attribute = new Attribute(
(DERSequence) attributes.nextElement());
DERObjectIdentifier attrType = attribute.getAttrType();
if (attrType.equals(RFC_3369_MESSAGE_DIGEST_OID)) {
ASN1Set attrValuesSet = attribute.getAttrValues();
if (attrValuesSet.size() != 1) {
System.err
.println("WARNING: expected only one attribute value in signedAttribute message digest in eContent!");
}
storedDigestedContent = ((DEROctetString) attrValuesSet
.getObjectAt(0)).getOctets();
}
}
if (storedDigestedContent == null) {
System.err
.println("WARNING: error extracting signedAttribute message digest in eContent!");
}
MessageDigest dig = MessageDigest.getInstance(digAlg);
byte[] computedDigestedContent = dig.digest(contentBytes);
if (!Arrays.equals(storedDigestedContent,
computedDigestedContent)) {
System.err
.println("WARNING: error checking signedAttribute message digest in eContent!");
}
} catch (NoSuchAlgorithmException nsae) {
System.err
.println("WARNING: error checking signedAttribute in eContent! No such algorithm "
+ digAlg);
}
return attributesBytes;
}
}
|
a0208f9d-66e8-4b3b-b9a5-e8ff4edd09ed
| 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(History_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(History_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(History_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(History_info.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 History_info().setVisible(true);
}
});
}
|
3fc0d1d3-74e8-4c50-a961-a314dd6c26a5
| 2
|
public static SocketBase zmq_socket (Ctx ctx_, int type_)
{
if (ctx_ == null || !ctx_.check_tag ()) {
throw new IllegalStateException();
}
SocketBase s = ctx_.create_socket (type_);
return s;
}
|
4674a397-d372-4bfa-89f9-f70cfed94de4
| 1
|
public static boolean removePreLive(final String name) {
if (CallGraph.preLive == null) {
CallGraph.init();
}
return (CallGraph.preLive.remove(name));
}
|
fc65c6b6-d1b6-4926-9684-1425eddd31e0
| 7
|
private static Instances clusterInstances(Instances data) {
XMeans xmeans = new XMeans();
Remove filter = new Remove();
Instances dataClusterer = null;
if (data == null) {
throw new NullPointerException("Data is null at clusteredInstances method");
}
//Get the attributes from the data for creating the sampled_data object
ArrayList<Attribute> attrList = new ArrayList<Attribute>();
Enumeration attributes = data.enumerateAttributes();
while (attributes.hasMoreElements()) {
attrList.add((Attribute) attributes.nextElement());
}
Instances sampled_data = new Instances(data.relationName(), attrList, 0);
data.setClassIndex(data.numAttributes() - 1);
sampled_data.setClassIndex(data.numAttributes() - 1);
filter.setAttributeIndices("" + (data.classIndex() + 1));
data.remove(0);//In Wavelet Stream of MOA always the first element comes without class
try {
filter.setInputFormat(data);
dataClusterer = Filter.useFilter(data, filter);
String[] options = new String[4];
options[0] = "-L"; // max. iterations
options[1] = Integer.toString(noOfClassesInPool - 1);
if (noOfClassesInPool > 2) {
options[1] = Integer.toString(noOfClassesInPool - 1);
xmeans.setMinNumClusters(noOfClassesInPool - 1);
} else {
options[1] = Integer.toString(noOfClassesInPool);
xmeans.setMinNumClusters(noOfClassesInPool);
}
xmeans.setMaxNumClusters(data.numClasses() + 1);
System.out.println("No of classes in the pool: " + noOfClassesInPool);
xmeans.setUseKDTree(true);
//xmeans.setOptions(options);
xmeans.buildClusterer(dataClusterer);
System.out.println("Xmeans\n:" + xmeans);
} catch (Exception e) {
e.printStackTrace();
}
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(xmeans);
try {
eval.evaluateClusterer(data);
int classesToClustersMap[] = eval.getClassesToClusters();
//check the classes to cluster map
int clusterNo = 0;
for (int i = 0; i < data.size(); i++) {
clusterNo = xmeans.clusterInstance(dataClusterer.get(i));
//Check if the class value of instance and class value of cluster matches
if ((int) data.get(i).classValue() == classesToClustersMap[clusterNo]) {
sampled_data.add(data.get(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ((Instances) sampled_data);
}
|
d7ca9b29-6f18-46a3-a114-3df851d5dc16
| 6
|
public List<Jvm> parse(String[] processes)
{
List<Jvm> jvms = new ArrayList<Jvm>();
for(String process : processes)
{
if(!process.isEmpty()
&& !process.contains("process information unavailable"))
{
String[] datas = process.split(" ");
if( datas.length>=2 )
{
Jvm jvm = new Jvm(datas[0], datas[1]);
if(datas.length>2)
{
for(int optionIdx = 2; optionIdx<datas.length; optionIdx++)
{
jvm.addOption(datas[optionIdx]);
}
}
jvms.add(jvm);
}
}
}
return jvms;
}
|
4c087dcb-85ca-40e9-be25-47c41688b045
| 3
|
@Override
public boolean isMine(String command) {
if (super.isMine(command)) {
if ((command.indexOf("(") == -1) || (command.indexOf(")") == -1)) {
error = hint;
return false;
}
types = command.substring(command.indexOf("("), command.lastIndexOf(")") + 1);
return true;
}
return false;
}
|
c0979d0c-c143-411e-95f9-a48959485854
| 2
|
private void shrinkBase()
{
while (this.base != 0 && this.base % 10 == 0)
{
this.base /= 10;
this.factor--;
}
}
|
9a395a7b-f0f3-4a1c-89da-a4f9fe475f0f
| 0
|
@Override
public boolean supportsMoveability() {return true;}
|
d1864865-fc5d-4e69-b9dc-ba31bcf57175
| 8
|
public AssetTransactionEditDialog(JFrame parent, String title, TransactionPanel transactionPanel,
TransactionRecord transaction) {
super(parent, title, Dialog.ModalityType.DOCUMENT_MODAL);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.transactionPanel = transactionPanel;
this.transaction = transaction;
account = transactionPanel.getTransactionAccount();
//
// Get the transaction specifics for an existing transaction
//
String name = null;
double decrease = 0.00;
double increase = 0.00;
double amount;
if (transaction != null) {
name = transaction.getName();
amount = transaction.getAmount();
if (amount < 0.0)
decrease = -amount;
else if (amount > 0.0)
increase = amount;
}
//
// Get the transaction date
//
dateField = new JFormattedTextField(new EditDate());
dateField.setColumns(8);
dateField.setInputVerifier(new EditInputVerifier(false));
dateField.addActionListener(new FormattedTextFieldListener(this));
if (transaction != null)
dateField.setValue(transaction.getDate());
else
dateField.setValue(Main.getCurrentDate());
//
// Get the description
//
if (name != null)
nameField = new JTextField(name, 20);
else
nameField = new JTextField(20);
//
// Get the memo
//
if (transaction != null)
memoField = new JTextField(transaction.getMemo(), 25);
else
memoField = new JTextField(25);
//
// Get the decrease in value
//
decreaseField = new JFormattedTextField(new EditNumber(2, true));
decreaseField.setColumns(10);
decreaseField.setInputVerifier(new EditInputVerifier(true));
decreaseField.addActionListener(new FormattedTextFieldListener(this));
if (decrease != 0.00)
decreaseField.setValue(new Double(decrease));
//
// Get the increase in value
//
increaseField = new JFormattedTextField(new EditNumber(2, true));
increaseField.setColumns(10);
increaseField.setInputVerifier(new EditInputVerifier(true));
increaseField.addActionListener(new FormattedTextFieldListener(this));
if (increase != 0.00)
increaseField.setValue(new Double(increase));
//
// Create the edit pane
//
// Date: <text-field>
// Description: <text-field>
// Memo: <text-field>
// Decrease: <text-field>
// Increase: <text-field>
//
JPanel editPane = new JPanel(new GridLayout(0, 2, 5, 5));
editPane.add(new JLabel("Date:", JLabel.RIGHT));
editPane.add(dateField);
editPane.add(new JLabel("Description:", JLabel.RIGHT));
editPane.add(nameField);
editPane.add(new JLabel("Memo:", JLabel.RIGHT));
editPane.add(memoField);
editPane.add(new JLabel("Decrease:", JLabel.RIGHT));
editPane.add(decreaseField);
editPane.add(new JLabel("Increase:", JLabel.RIGHT));
editPane.add(increaseField);
//
// Create the buttons (OK, Cancel, Help)
//
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
JButton button = new JButton("OK");
button.setActionCommand("ok");
button.addActionListener(this);
buttonPane.add(button);
getRootPane().setDefaultButton(button);
buttonPane.add(Box.createHorizontalStrut(10));
button = new JButton("Cancel");
button.setActionCommand("cancel");
button.addActionListener(this);
buttonPane.add(button);
buttonPane.add(Box.createHorizontalStrut(10));
button = new JButton("Help");
button.setActionCommand("help");
button.addActionListener(this);
buttonPane.add(button);
//
// Set up the content pane
//
JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setOpaque(true);
contentPane.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
contentPane.add(editPane);
contentPane.add(Box.createVerticalStrut(15));
contentPane.add(buttonPane);
setContentPane(contentPane);
}
|
e4303a96-7d2d-4d26-a751-43ed5f114766
| 1
|
public int getNewKeys() {
int allNewSize = 0;
for (int i = 0; i < 256; ++i) {
allNewSize += files[i].getNewKeys();
}
return allNewSize;
}
|
79dca91e-994e-41b0-8f46-826c142385cd
| 1
|
public String getMBS32(String key)
{
long now = System.currentTimeMillis();
String tmp = "";
System.out.println("panjang " + key.length());
for(int i = 0; i < key.length(); i++)
{
tmp = "" + this.getSHA("" + key.charAt(i));
}
String a1 = this.getSHA(tmp);
String a2 = this.getMD5(a1);
String a4 = this.getMD5(a2);
ab.system.libraries.security.ABSecurity rc4 = new ab.system.libraries.security.ABSecurity();
result = rc4.enkodeRC4(a4);
result = this.getSHA(result);
lamanya = System.currentTimeMillis() - now;
return result;
}
|
ebde50f8-63af-4398-9026-b4dbba750af2
| 8
|
public double run() {
double nextStartNumber, nextEndNumber, currentEndNumber;
boolean stopped = false;
pi = 4;
nCompletedCalculations = 0;
/*
* Create a threadpool have fixed number of threads
*/
executor = Executors.newFixedThreadPool(nThreads);
taskPool = createTaskPool();
Iterator<AlgorithmTask> taskIterator = taskPool.iterator();
AlgorithmTask currentTask = null;
LeibnizParameter input = new LeibnizParameter();
currentEndNumber = 0;
/*
* Loop until all calculations are completed. If taskList have enough
* task for threads in thread pool to do, then invokeAll these tasks. If
* the last remained calculation not enough to divide into task for each
* thread, then reduce size of taskList.
*/
while (nCompletedCalculations < nCalculations && !stopped) {
if (taskIterator.hasNext()) {
currentTask = taskIterator.next();
nextStartNumber = currentEndNumber;
nextEndNumber = nextStartNumber + nCalcEachThread;
if (currentEndNumber >= nCalculations) {
taskIterator.remove();
continue;
} else if (nextEndNumber > nCalculations) {
nextEndNumber = nCalculations;
}
currentEndNumber = nextEndNumber;
input.setParameters(nextStartNumber + 1, nextEndNumber);
currentTask.setAlgorithmInput(input);
} else {
List<Future<IAlgorithm>> results;
try {
results = executor.invokeAll(taskPool);
for (Future<IAlgorithm> result : results) {
pi += result.get().getResult();
nCompletedCalculations += result.get().getDoneNumber();
/*
* When stop() method of algorithm is invoked,
* CalculationTask in task list turn on the sign
* stopping. If previous task didn't finish all its
* calculations then next task calculations had been
* done will not count to result
*/
if (result.get().getDoneNumber() < nCalcEachThread) {
stopped = true;
break;
}
}
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
taskIterator = taskPool.iterator(); // reset index of task
}
}
/*
* Thread pool accept no more task
*/
executor.shutdown();
return pi;
}
|
a1cad4c0-66bc-4484-9dea-5aa5d0c30f2e
| 9
|
private void gameRender(Graphics2D gScr) {
countFramesForAttackingHero++;
// Hintergrund faerben
gScr.setColor(Color.black);
gScr.fillRect(0, 0, pWidth, pHeight);
gScr.setFont(font);
gScr.setColor(Color.black);
switch(state) {
case INTRO :
state = state.MENU;
break;
case MENU :
new menu.MainMenu(gScr, positionInMainMenu, mWidth, mHeight);
state = state.RUN;
break;
case LOADLEVEL :
gScr.setColor(Color.RED);
gScr.fillRect(0, 0, pWidth, pHeight);
BufferedImage foo = null;
try {
foo = ImageIO.read(new File("images/angela_merkel.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
gScr.drawImage(foo, 400, 400, null);
break;
case RUN :
drawBackground(gScr);
drawMobs(gScr);
drawNPCs(gScr);
drawHUD(gScr);
drawHero(gScr); // get ya hero on the screen!
drawHitFrame(gScr);
break;
case PAUSE :
break;
}
if (debugMode) {
int temp = 1;
gScr.setFont(font);
gScr.setColor(Color.black);
gScr.drawString("FPS: "+fps, 20, 20);
gScr.drawString("Hero: HP = "+hero.getHp()+", Position: x = "+hero.getPositionX()+", y = "+hero.getPositionY(), 20, 40);
gScr.drawString("Map: x = "+getMapPosX()+", y = "+getMapPosY(), 20, 60);
gScr.drawString("Keyboard: up: "+up+", right: "+right+", down: "+down+", left: "+left, 20, 80);
gScr.drawString("Sword: slash: "+slash+", x: "+hero.getSword().getX()+", y: "+hero.getSword().getY()+", damage: "+hero.getSword().getDamage(), 20, 100);
gScr.drawString("Turbomode: "+turboMode, 20, 120);
/////////////////////////////////////////// Rechte Seite //////////////////////////////////////////////////////////
LinkedList<Mob> Mobs = AssetCreator.getMobs();
if (!Mobs.isEmpty()) {
gScr.drawString("Mobs",mWidth-300,20*temp);
temp++;
for (int i = 0; i < Mobs.size(); i++) {
Mob mob = Mobs.get(i);
gScr.drawString("Mob "+temp+": x = "+mob.getPositionX()+", y = "+mob.getPositionY(),mWidth-300,20*temp);
gScr.drawString("IsHeroInRange: "+mob.isHeroInRange(), mWidth-300, 20*(temp+1));
temp += 2;
}
}
}
}
|
3e1cca6c-9028-4ac3-847b-d60cabf5c8c6
| 6
|
public boolean updateVecs(Equation e, Integer i) {
if (e.TypeSel.getSelectedIndex() == Equation.posCartLine) {
float[] out = getInput(e.cartLInputs);
vecs[i] = createCartLine(out);
return true;
}
if (e.TypeSel.getSelectedIndex() == Equation.posVecLine) {
float[] out = getInput(e.vecLInputs);
vecs[i] = createVectorLine(out);
return true;
}
if (e.TypeSel.getSelectedIndex() == Equation.posCartPlane) {
float[] out = getInput(e.cartPInputs);
vecs[i] = createCartPlane(out);
return true;
}
if (e.TypeSel.getSelectedIndex() == Equation.posVecPlane) {
float[] out = getInput(e.vecPInputs);
vecs[i] = createVectorPlane(out);
return true;
}
if (e.TypeSel.getSelectedIndex() == Equation.posNone) {
Vector3D[] vector = new Vector3D[4];
for (int n = 0; n < 4; n++) { vector[n] = new Vector3D(0,0,0); }
vecs[i] = vector;
return false;
}
return false;
}
|
2842eeb7-57b7-4884-a9bc-d65520160fe9
| 5
|
public void connecterServeur(CallbackListener callback) throws IOException {
coucheReseau = new InterfaceReseau(Protocole.TCP, Constantes.IPDistante, portLocal, Constantes.portDistantTCP);
coucheReseau.envoyer("INIT "+portLocal);
if((reponse = coucheReseau.recevoir()).equals("200 READY")) {
String[] reponseParsed;
int idControleur;
reponse = coucheReseau.recevoir();//ID CONTROLEUR + JSON LIGNES
reponseParsed = reponse.split(";");
//{"id_controleur":2, "lignes":["ligne1", "ligne2", "ligne3"]}
jsonObject = (JSONObject) JSONValue.parse(reponseParsed[1]);
JSONArray jsonArray = (JSONArray) jsonObject.get("lignes");
idControleur = Integer.parseInt(""+jsonObject.get("id_controleur"));
//traitement JSON
if(jsonArray.size() > 0) {
synchronized(Main.controleur) {
Main.controleur.setId(idControleur);
}
//S'il y a des lignes de disponibles
if(jsonArray.size() > 0 && !jsonArray.get(0).equals("")) {
synchronized(Main.lignes) {
for (int i = 0; i < jsonArray.size(); i++) {
String nomLigne = (String)jsonArray.get(i);
int idLigne = Integer.parseInt(nomLigne.substring(nomLigne.length() - 1));
Ligne newLigne = new Ligne(nomLigne,idLigne);
((HashMap) Main.lignes).put(nomLigne, newLigne);
}
coucheApplication.mettreAJourLignes();
}
}
}
}
callback.onReturn(true);
}
|
32ea33cd-7d2a-46f8-8f05-7b7774e15975
| 0
|
@Override
protected void generateFrameData(ResizingByteBuffer bb)
throws FileNotFoundException, IOException {
// TODO: generate, don't reload
bb.put(this.reload());
}
|
2bdee9a4-4b52-4077-acac-b6a53137219c
| 5
|
static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) {
int diff = 0;
long savedDate = fromDate.getTimeInMillis();
while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) {
savedDate = fromDate.getTimeInMillis();
fromDate.add(type, future ? 1 : -1);
diff++;
}
diff--;
fromDate.setTimeInMillis(savedDate);
return diff;
}
|
6551aa35-970f-4635-9c6b-188943877cc9
| 9
|
static void project( Region src, float x, float y, Region dest, int destX, int destY ) {
dest.clear();
final int rayCount=512;
for( int i=0; i<rayCount; ++i ) {
// 64 rays!
float angle = i*(float)Math.PI*2/rayCount;
float dx = (float)Math.cos(angle);
float dy = (float)Math.sin(angle);
float cx = x, cy = y;
float visibility = 1;
for( int j=100; j>=0 && visibility > 0; cx += dx, cy += dy, --j ) {
int cellX = (int)Math.floor(cx), cellY = (int)Math.floor(cy);
Block[] stack = src.getStack( cellX, cellY );
if( stack == null ) break;
int destCX = destX+cellX-(int)Math.floor(x);
int destCY = destY+cellY-(int)Math.floor(y);
if( destCX < 0 || destCX >= dest.w ) break;
if( destCY < 0 || destCY >= dest.h ) break;
dest.setStack( destCX, destCY, stack );
for( Block b : stack ) visibility -= b.opacity;
}
}
}
|
81af6a61-a464-45c3-9420-1fd19fbaef6e
| 0
|
public void setCliente(int cliente) {
this.cliente = cliente;
}
|
206a8bf1-b886-4945-80ad-d1dfc3fe489f
| 9
|
static double term(Reader in, Set<Integer> terminators) throws ParserException, IOException {
boolean negative = false;
if (read(in) == '-') {
negative = true;
} else {
in.reset(); //return to mark
}
Set<Integer> multTerminators = new HashSet<>(terminators);
multTerminators.add((int) '*');
multTerminators.add((int) '/');
multTerminators.add((int) '%');
double result = mult(in, multTerminators);
if (negative) {
result = -result;
}
while (true) {
int c = read(in);
if (terminators.contains(c)) {
in.reset();
break;
}
if (c != '*' && c != '/' && c != '%') {
throw new ParserException("unexpected term-level operation: " + (char) c);
}
double multValue = mult(in, multTerminators);
if (c == '*') {
result = result * multValue;
} else if (c == '/') {
result = result / multValue;
} else {
result = result % multValue;
}
}
return result;
}
|
1249f63c-e81f-46c3-ad5e-9ebe331e7407
| 0
|
public GenericContainer() {
}
|
cc4f4414-de7c-478d-a765-0535fad44809
| 2
|
protected void initializeFilepaths(){
filePaths = new String[mapSizeY][mapSizeX];
int n = 1;
for(int i = 0; i < mapSizeY; i++){
for(int j = 0; j < mapSizeX; j++){
filePaths[i][j] = filePath + "testLevel" + n;
n++;
}
}
}
|
431cff69-1911-4c64-913b-03a2f7132109
| 6
|
public void move() {
if (isVisible == true && (lovelyStrip == 0 || lovelyStrip == 3)){
area.x += moveX;
if(!isInsideStripArea()){
isVisible = false;
}
} else if(isVisible == true){
area.x -= moveX;
if(!isInsideStripArea()){
isVisible = false;
}
}
}
|
7c386c90-eef1-47ef-bc2c-8e2e52f95dbc
| 5
|
@Override
public void caseAParaComando(AParaComando node)
{
inAParaComando(node);
if(node.getVariavel() != null)
{
node.getVariavel().apply(this);
}
if(node.getIPara() != null)
{
node.getIPara().apply(this);
}
if(node.getPasso() != null)
{
node.getPasso().apply(this);
}
if(node.getNPara() != null)
{
node.getNPara().apply(this);
}
{
List<PComando> copy = new ArrayList<PComando>(node.getComando());
for(PComando e : copy)
{
e.apply(this);
}
}
outAParaComando(node);
}
|
f5cb457b-7a38-428a-8ce2-f9031603e362
| 4
|
public static void compare( final int ARRAY_SIZE, final int iterations, SortAlgorithm[] algos ) {
int size = algos.length;
long means[] = new long[ size ];
for(int i = 0; i < size; means[i++] = 0) {
// nothing to do
}
for(int i = 0; i < iterations; ++i) {
System.out.print("Iteration " + (i+1) + "...");
int[] initialList = Utils.generate(ARRAY_SIZE);
for( int j = 0; j < size; ++j ) {
int[] copy = initialList.clone();
long begin = System.currentTimeMillis();
algos[j].sort(copy);
long diff = System.currentTimeMillis() - begin;
means[j] += diff;
System.out.print( algos[j].toString() + ": " + diff + "ms / ");
}
System.out.println();
}
for( int i = 0; i < size; ++i ) {
means[i] /= iterations;
System.out.println(algos[i].toString() + " average time: " + means[i] + "ms");
}
}
|
673d71a0-9123-4b53-8d7e-fdf2d5b6457b
| 0
|
public void setStartVariable(String variable) {
myStartVariable = variable;
}
|
ccad2996-99ed-44e2-ba85-4014b48961f1
| 5
|
public static Double[][] randCostArray(int n)
{
n = n < 2 ? randInt(5,1000):n;
Double[][] array = new Double[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if( j > i)
array[i][j] = (double) randInt(1, 100);
else if( i == j)
array[i][j] = 0.0;
else
array[i][j] = Double.POSITIVE_INFINITY;
}
}
return array;
}
|
e2069f79-39a2-42df-a8c2-b24271d8a4e8
| 3
|
public void logToFile(String message)
{
try {
warnLog = new File(dataFolder + File.separator + "WarnLog.txt");
//Bukkit.broadcastMessage("Test1: " + warnLog.getPath());
File dataFolder = getDataFolder();
if (!dataFolder.exists()) {
dataFolder.mkdir();
}
if (!warnLog.exists()) {
warnLog.createNewFile();
}
FileWriter fw = new FileWriter(warnLog, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(message);
pw.println("");
pw.close();
} catch (IOException e) {
//e.printStackTrace();
}
}
|
dd88840b-4df1-438f-b9ed-ee9c7f2d09f1
| 8
|
public static void CheckEndGame() {
// TODO: Implement game checking code here.
int winningPlayer = -1;
switch(Instance.gameMode) {
case DOMINATION : //First player to control >= 75% of all planets in the game.
float limit = (float) (Instance.numPlanets) * 0.75f;
for(int i = 0; i < TurnManager.numPlayers; i++) {
Player p = TurnManager.getPlayer(i + 1);
if(p.getTerritory().size() >= limit) {
Instance.gameOver = true;
winningPlayer = i+1;
}
}
break;
case SURVIVAL : //Game ends when all players have died. (PvE style)
break;
case DEATHMATCH : //Last player to still have his Capital ship wins.
break;
case CONQUEST : //Last player with any ship alive wins.
}
if(Instance.gameOver) {
TurnManager.currentPlayer = -1;
TurnManager.NoFoW = true;
Instance.winner = winningPlayer;
Instance.alertListeners(new GameEvent(GameEvent.GAME_OVER));
if(debug) System.out.println("Player " + winningPlayer + " wins");
}
}
|
e3ad9d54-cf77-4a9d-868e-cac9b2aab00d
| 1
|
public static <T> CycList<T> makeDottedPair(final T normalElement, final T dottedElement) {
if (CycObjectFactory.nil.equals(dottedElement)) {
return new CycList<T>(normalElement);
}
final CycList<T> cycList = new CycList<T>(normalElement);
cycList.setDottedElement((T) dottedElement);
return cycList;
}
|
394a4417-d706-4eb0-8ebd-5851adb7167b
| 4
|
static final public Behavior behavior() throws ParseException {
Behavior result; Token name; MessageHandler handler;
jj_consume_token(BEHAVIOR);
name = jj_consume_token(BEHAVIORIDENT);
result = new Behavior(name.image);
jj_consume_token(LPAREN);
if (jj_2_6(4)) {
var_ident_list(result.getParameters());
} else {
;
}
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
label_6:
while (true) {
handler = msg_handler_clause();
result.getHandlers().add(handler);
if (jj_2_7(4)) {
;
} else {
break label_6;
}
}
jj_consume_token(RBRACE);
{if (true) return result;}
throw new Error("Missing return statement in function");
}
|
91958879-0ffd-4939-89a1-e6b20c53679a
| 5
|
public boolean add(VetVisit visitX)
{
boolean visitAdded = false;
if(visitX.equals(null))
return visitAdded; //returns false
/* check to verify visitX isn't already in the list. if it isn't already in the
* list, proceed to add visitX to list (if visitX successfully added to list,
* return true); otherwise, return false */
if(!this.contains(visitX))
{
Node<VetVisit> currentNode = this.firstNode;
Node<VetVisit> previousNode = null; //no previous node if you're at firstNode
Node<VetVisit> node = new Node<VetVisit>();
node.data = visitX;
/* determine where to add visitX in the linked list: we want to find the
* first "node.data" already in the list that is larger than visitX
* when position determined,
* add visitX to linked list by altering the links of the node to be before it
* and the node to be after it to include links to VisitX
*/
while(currentNode != null)
{
/* if currentNode.data is less than visitX data, break out of loop */
if(currentNode.data.compareTo(visitX) < 0)
{
break;
}
/* move on to next node */
previousNode = currentNode;
currentNode = currentNode.link;
}//end WHILE
if(previousNode == null)
{
node.link = this.firstNode;
this.firstNode = node;
}
else
{
node.link = previousNode.link;
previousNode.link = node;
}
visitAdded = true;
this.visitCount++;
}//end IF(!this.contains(visitX))
//else if(this.contains(visitX)){}
return visitAdded;
}//end add()
|
af5f09fa-79b3-4081-866a-bd0c3a692f12
| 7
|
private boolean isHovering(MouseEvent e) {
Rectangle r1 = new Rectangle(sRect1.x + (int)sXPos - 1, sRect1.y + (int)sYPos - 1, sRect1.width+2, sRect1.height+2);
Rectangle r2 = new Rectangle(sRect2.x + (int)sXPos - 1, sRect2.y + (int)sYPos - 1, sRect2.width+2, sRect2.height+2);
Rectangle w1 = new Rectangle(wRect1.x + (int)wXPos - 1, wRect1.y + (int)wYPos - 1, wRect1.width+2, wRect1.height+2);
Rectangle w2 = new Rectangle(wRect2.x + (int)wXPos - 1, wRect2.y + (int)wYPos - 1, wRect2.width+2, wRect2.height+2);
Rectangle tTop1 = new Rectangle(tTopRect1.x + (int)topTXPos - 1, tTopRect1.y + (int)topTYPos - 1, tTopRect1.width+2, tTopRect1.height+2);
Rectangle tTop2 = new Rectangle(tTopRect2.x + (int)topTXPos - 1, tTopRect2.y + (int)topTYPos - 1, tTopRect2.width+2, tTopRect2.height+2);
Rectangle tBot1 = new Rectangle(tBottomRect1.x + (int)botTXPos - 1, tBottomRect1.y + (int)botTYPos - 1, tBottomRect1.width+2, tBottomRect1.height+2);
Rectangle tBot2 = new Rectangle(tBottomRect2.x + (int)botTXPos - 1, tBottomRect2.y + (int)botTYPos - 1, tBottomRect2.width+2, tBottomRect2.height+2);
return ( r1.contains(e.x, e.y) || r2.contains(e.x, e.y)
|| w1.contains(e.x, e.y) || w2.contains(e.x, e.y)
|| tTop1.contains(e.x, e.y) || tTop2.contains(e.x, e.y)
|| tBot1.contains(e.x, e.y) || tBot2.contains(e.x, e.y) );
}
|
7ebfb6bf-6bf6-4993-9aab-22ce7ff9e6ea
| 2
|
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i]=in.nextInt();
}
String result = check(a);
System.out.println(result);
if(result.equals("yes"))
System.out.println(range[0]+" "+range[1]);
}
|
7d749747-e1fe-4ed2-ad8a-5930f14b8eb2
| 1
|
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (DATA_FLAVOR.equals(flavor)) {
return this;
}
throw new UnsupportedFlavorException(flavor);
}
|
2f0782fc-0957-43d5-83d0-685cb9e3950a
| 7
|
public byte mean(String fileName) throws IOException {
FileInputStream is = null;
DataInputStream dis = null;
BufferedWriter br = new BufferedWriter(new FileWriter("mean_bin.txt"));
NumberFormat formatter = new DecimalFormat();
formatter = new DecimalFormat("0.000E00");
try {
is = new FileInputStream(fileName);
dis = new DataInputStream(new BufferedInputStream(is));
int senones = (int)dis.readFloat();
int gaussians = (int)dis.readFloat();
br.write("param " + senones + " 1 " + gaussians);
br.newLine();
for(int i = 0; i < senones; i++)
{
br.write("mgau " + i +" ");
br.newLine();
br.write("feat 0");
br.newLine();
for(int j = 0; j < gaussians; j++)
{
br.write("density " + j +" ");
for(int k = 0 ; k < 39; k++)
br.write(formatter.format(dis.readFloat()) + " ");
br.newLine();
}
}
}
catch(Exception e){
e.printStackTrace();
return 0;
}
finally{
if(is != null)is.close();
if(dis != null)dis.close();
if(br != null){
br.flush();
br.close();
}
}
return 1;
}
|
26b20ad3-6d29-4f4c-97e3-c5e1f3c7ab98
| 1
|
public void setBackgroundWithoutHandling(Path img) {
if (FileUtil.control(img)) {
this.imgBackground = img;
this.backgroundImgChanged = true;
} else {
this.imgBackground = null;
this.backgroundImgChanged = false;
}
somethingChanged();
}
|
4bbbd27b-cdc8-4ab3-9ff6-91bdde1189ee
| 6
|
@EventHandler
public void SpiderInvisibility(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSpiderConfig().getDouble("Spider.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getSpiderConfig().getBoolean("Spider.Invisibility.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getSpiderConfig().getInt("Spider.Invisibility.Time"), plugin.getSpiderConfig().getInt("Spider.Invisibility.Power")));
}
}
|
c480fda7-ee1c-49ec-8472-9ab29a65395a
| 3
|
private void createSuggestionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createSuggestionButtonActionPerformed
String subject = subjectTextField.getText();
String description = descriptionTextArea.getText();
boolean success;
if(suggestion != null && suggestion.getId() > -1) {
success = SuggestionLogic.updateSuggestion(suggestion, subject, description);
} else {
success = SuggestionLogic.createSuggestion(subject, description);
}
if (success) {
System.out.println("Successfully added a suggestion.");
FOTE.getMainFrame().loadSuggestions();
this.dispose();
} else {
System.out.println("There was an error. Please try again.");
}
}//GEN-LAST:event_createSuggestionButtonActionPerformed
|
78e4d177-3019-4f25-a716-ae325bf0480e
| 2
|
public void startFile(String logfile) {
File parent = new File(logfile).getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
logger.warning("Could not create log folder: " + parent);
}
Handler fileHandler = new RotatingFileHandler(logfile);
fileHandler.setFormatter(new DateOutputFormatter(FILE_DATE));
logger.addHandler(fileHandler);
}
|
54518a53-6e60-4736-96d9-3dda1739995a
| 1
|
public static void main(String[] args) {
try {
AppGameContainer app = new AppGameContainer(new main());
app.setDisplayMode(1280, 768, false); //was 960 and 1080
app.setTargetFrameRate(60);
app.setFullscreen(false);;
app.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
|
a97e7427-60ec-425f-8de6-bde9edbad3fe
| 2
|
public boolean isEmpty(int checkId) {
ListElement currentRobot = this.robotPlace.getHead();
while (currentRobot != null) {
if (currentRobot.getId() == checkId) {
return false;
}
currentRobot = currentRobot.getNext();
}
return true;
}
|
113c3967-4bb2-4a7b-8c46-a6c6b72b2446
| 3
|
public static void arrayDisplay(int x[][]){
//loops through the rows, then loops through the columns if there is any
for(int row = 0; row < x.length; row++){
System.out.println("Row: " + row);
if(x[row].length <= 1)//detects the amount of columns the row in the array has
{
System.out.println("There is a total of " + x[row].length + " column!");
}else{
System.out.println("There are a total of " + x[row].length + " columns!");
}
//for every column there is in the certain row of the index we called, execute this code.
for(int column = 0; column < x[row].length; column++){
System.out.println("Column/Index " + column + ": " + x[row][column] );//prints out the column value
}
System.out.println(); //just for spacing at the end.
}
}
|
f0622048-7ead-4b39-bd36-b23854bf26b5
| 0
|
public synchronized static void setDone(boolean done) {
RaceCondition2.done = done;
}
|
b1f83a9b-27ef-4156-a536-6381b4c0ee5d
| 9
|
protected Document parseXmlResponse (String xmlString) throws Exception {
Document xmlDoc;
try {
xmlDoc = XmlUtils.parseXmlString(xmlString);
}
catch (SAXParseException e1) {
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "Error parsing xml", e1);
}
catch (SAXException e2) {
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "Some other error occurred processing xml response", e2);
}
try {
NodeList rspElems = xmlDoc.getElementsByTagName("rsp");
if(rspElems.getLength() < 1){
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "No response (rsp) element found in web service response.");
}
Element rsp = (Element)rspElems.item(0);
String status = rsp.getAttribute("stat");
if(status == null){
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "Expected 'stat' attribute on <rsp> tag.");
}
if(!status.equals("ok")){
Element err = (Element)rsp.getFirstChild();
if(err == null){
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "Expected <err> element to be first child of <rsp> element");
}
String errCode = err.getAttribute("code");
String errMsg = err.getAttribute("msg");
if(errCode == null || errMsg == null){
throw new ServiceException(INVALID_WEB_SERVICE_RESPONSE, "Expected 'code' and 'msg' attributes on <err> element");
}
}
return xmlDoc;
}
catch (ServiceException se){
throw new ServiceException(se.getErrorCode(), se.getMessage() + " Response text: " + xmlString);
}
}
|
68772bca-a339-4a92-8000-16f1fdcc5c0b
| 8
|
public void analyseLargestComponentMembership(String dir){
File[] files = new File(dir).listFiles();
String line;
String[] parts;
int[] monthsT = new int[files.length];
int index =0;
Map<Integer,File> fileMap = new HashMap<Integer,File>();
for(File file : files)
{
if(file.isFile() && file.getName().contains("betweenness"))
{
monthsT[index] = findNumberInString(file.getName());
fileMap.put(monthsT[index], file);
index++;
}
}
int[] months = new int[index];
System.arraycopy(monthsT, 0, months, 0, months.length);
Arrays.sort(months);
Analyser A = new Analyser();
try
{
for(int i : months)
{
index = 0;
if(!fileMap.containsKey(i))
continue;
BufferedReader read = new BufferedReader(new FileReader(fileMap.get(i)));
while((line=read.readLine())!= null)
{
A.addToBin(0, Integer.parseInt(line.split(" ")[0]), 1);
}
read.close();
}
int[][] B = A.getBins(0);
for(int[] b : B)
{
A.addToBin(1, b[1], 1);
}
System.out.println("Here we go!");
A.printBins(1);
}
catch (Exception ex)
{
Logger.getLogger(NetworkAnalyser.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
0382fa2f-b2b0-444d-9635-0b95a1226662
| 1
|
public void start() {
if (running)
return;
running = true;
beater = new Beater(this);
beater.start();
}
|
bbea6090-e444-438c-bd45-6da6cbaa0b4e
| 3
|
public void vuoro(int x, int y, int rivi, int sarake) {
if (this.logiikka.getVuoro() == 1) {
this.logiikka.suoritaVuoro(1, rivi, sarake);
if (this.logiikka.getRistinAsetus() == 1) {
this.piirtoalusta.piirraNormaaliRisti(x, y);
} else {
this.piirtoalusta.piirraLatinalainenRisti(x, y);
}
loppuukoPeli();
} else {
this.logiikka.suoritaVuoro(2, rivi, sarake);
if (this.logiikka.getNollanAsetus() == 1) {
this.piirtoalusta.piirraNormaaliNolla(x, y);
} else {
this.piirtoalusta.piirraHymynaama(x, y);
}
loppuukoPeli();
}
}
|
3ffce718-beab-4eed-9766-9652cbbc63e2
| 1
|
public void place(String string, World world) {
this.loadFromFile(string, world);
for (Blocks bl : blocks) {
bl.set();
}
}
|
7e6c754e-46cd-40dd-9299-654ef5b096ad
| 6
|
public void render() {
bg.bind();
Molybdenum.GLQuad(0, 0, Display.getWidth(), Display.getHeight());
Molybdenum.setAwtColor(Color.WHITE);
Molybdenum.getText().drawStringS("Molybdenum | Properties", 16, 16, Text.LEFT, 3f,4);
Molybdenum.setAwtColor(Color.DARK_GRAY);
Molybdenum.getText().drawString("Version "+Molybdenum.VERSION, 0, Display.getHeight()-16, Text.LEFT, 1);
//Render all selections
Molybdenum.setAwtColor(Color.WHITE);
for(int i=0;i<items.length;i++){
String current = items[i];
int xset = 0;
if(i==item){
current = "> "+current;
xset = (int)(16*2);
}
if(i==0){
current+=" "+input_player;
}
if(i==1){
current+=" "+red;
}
if(i==2){
current+=" "+green;
}
if(i==3){
current+=" "+blue;
}
Molybdenum.getText().drawStringS(current, 128-xset, 128+(32*i), Text.LEFT, 2f,4);
}
}
|
8ec1b317-9fdd-4c74-97be-25f664a25e48
| 4
|
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
if (userId != null) {
return userId.equals(((User) that).userId);
}
return super.equals(that);
}
|
38e13956-bbff-4916-a438-9b501609d787
| 3
|
public void printSccs() {
Iterator<Integer> it = sccsOfLeader.keySet().iterator();
int j = 0;
while (it.hasNext() && j < 10) {
int leaderVertex = it.next();
System.out.print((leaderVertex + 1) + ":");
for (int i = 0; i < sccsOfLeader.get(leaderVertex).size(); i++) {
System.out.print((sccsOfLeader.get(leaderVertex).get(i) + 1)
+ ",");
}
System.out.println();
j++;
}
}
|
81f5a0b3-27c4-4594-9ea4-162f5490f55e
| 7
|
int[] LIS(int[] num) {
ArrayList<Integer> trace = new ArrayList<Integer>(); // for back-tracing
ArrayList<Integer> lis = new ArrayList<Integer>(); // recording the current optimal LIS
trace.add(-1);
lis.add(0);
for (int i = 1; i < num.length; i++) {
int l = 0, r = lis.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (num[lis.get(mid)] < num[i])
l = mid + 1;
else
r = mid - 1;
}
trace.add(r >= 0 ? lis.get(r) : -1);
if (r == lis.size() - 1) { // find a longer sequence
lis.add(i);
} else if (num[lis.get(r + 1)] > num[i]) { // decrease previous value
lis.set(r + 1, i);
}
}
int[] res = new int[lis.size()];
int i = lis.size();
int tmp = lis.get(i - 1);
while ((--i) >= 0) {
res[i] = num[tmp];
tmp = trace.get(tmp);
}
return res;
}
|
0d4bfdf4-d795-4f57-ac3a-65f338da242e
| 4
|
public boolean canPlace() {
if (! super.canPlace()) return false ;
for (Tile t : Spacing.perimeter(area(), origin().world)) if (t != null) {
if (t.owningType() >= this.owningType()) return false ;
}
return true ;
}
|
2d9b04c3-ded7-4e87-adf2-adc9e910d1c1
| 8
|
private boolean isPacketLine(String line)
{
if (line.isEmpty())
{
return false;
}
if (this.accumulator == null && line.length() < 32)
{
return false;
}
for (char c : line.toCharArray())
{
if ((c < '0' || c > '9') && (c < 'A' || c > 'F'))
{
return false;
}
}
return true;
}
|
99f38aa9-6713-451d-a714-4b3ec4589808
| 1
|
@Override
public void flush() {
for (int i = 0; i < printStreams.length; i++){
printStreams[i].flush();
};
}
|
3d6709e4-8169-4f2d-9d42-a048d3a367b0
| 4
|
public int[] findZ(int base){
int[] z = new int[2];
int pos = base-1;
while (true){
if (this.getN(pos) == 0){
z[0] = pos;
break;
}else{
--pos;
}
}
pos = base + 1;
while (true){
if (this.getN(pos) == 0){
z[1] = pos;
break;
}else{
++pos;
}
}
// FIXME:
return z;
}
|
7289fb27-bf31-48b6-8f9d-b22d42ac5a57
| 8
|
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
boolean createFile = !updaterConfigFile.exists();
try {
if (createFile) {
updaterConfigFile.createNewFile();
this.config.options().copyDefaults(true);
this.config.save(updaterConfigFile);
} else {
this.config.load(updaterConfigFile);
}
} catch (final Exception e) {
if (createFile) {
plugin.getLogger().severe("The updater could not create configuration at " + updaterFile.getAbsolutePath());
} else {
plugin.getLogger().severe("The updater could not load configuration at " + updaterFile.getAbsolutePath());
}
plugin.getLogger().log(Level.SEVERE, null, e);
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e);
this.result = UpdateResult.FAIL_BADID;
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
|
920fd47d-0224-4103-b6f3-195f9c6e9781
| 3
|
private int countG (Point currentCell) {
Point localCell = currentCell;
int G = 0;
while (!localCell.equals(startCell)) {
Point parentCell = field[localCell.x][localCell.y].getParent();
if (localCell.x == parentCell.x || localCell.y == parentCell.y) {
G += DIRECT_TRANSFER;
} else {
G += DIAGONAL_TRANSFER;
}
localCell = parentCell;
}
return G;
}
|
2d2e236b-2d8a-4cfa-ba2a-b356a58d4f63
| 1
|
public void setCount(int count) {
if (count < 1) {
throw new ComponentException("Illegal number of test cases: " + count);
}
this.count = count;
}
|
d287e415-17ef-40ea-a216-a7b5d170d434
| 3
|
public static int romanValueOf(String roman) {
roman = roman.toUpperCase();
if (roman.length() == 0)
return 0;
for (int i = 0; i < symbol.length; i++) {
int pos = roman.indexOf(symbol[i]);
if (pos >= 0)
return value[i] - romanValueOf(roman.substring(0, pos))
+ romanValueOf(roman.substring(pos + 1));
}
throw new IllegalArgumentException("Invalid Roman Symbol.");
}
|
8b1129f1-6c37-496b-9b7e-6512a87a2ed3
| 0
|
public int getBitsPerPixel() {
return bitsPerPixel;
}
|
74a096b9-5cac-4f36-aa28-05454eb4fc7f
| 9
|
public static void startGame() {
GameGUI.song.play();
GameGUI.song.loop();
// This allows us to restart the game without quitting the program
if (gui != null){ // Is a replay, close the old game, clear the disks prompt, show it
gui.close();
}
// Contents of dialogue
final String[] options = {"Play","Main"};
final JPanel panel = new JPanel();
JLabel lbl = new JLabel("Number of Disks (3 to 25): ");
final JTextField txt = new JTextField(10);
final JPanel title = new JPanel();
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(2,1,0,10));
JButton playbutton =new JButton("Play");
JButton exit = new JButton("Exit");
buttons.add(playbutton);
buttons.add(exit);
title.setLayout( new BorderLayout());
final JFrame frame = new JFrame();
try{
BufferedImage myPicture = ImageIO.read(new File("src/edu/ucsb/cs56/projects/games/towers_of_hanoi/utility/images/ToHtitle.png"));
JLabel picLabel = new JLabel (new ImageIcon(myPicture));
title.add(picLabel, BorderLayout.NORTH);
title.add(buttons, BorderLayout.SOUTH);
}catch(IOException ioe) {
System.err.println("yo, error foo");
System.exit(0);
}
panel.add(lbl);
panel.add(txt);
frame.add(title);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
//when you hit play, calls the dialogs preceding play
playbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// title.removeAll();
//frame.revalidate();
// frame.repaint();
frame.setVisible(false);
int numberOfDisks = 0;
int choice = JOptionPane.showOptionDialog(null,"Tower of Hanoi: \n\nThe goal of this game is to move all the disks from the leftmost tower to either the middle tower or rightmost tower, adhering to the following rules:\n 1) Move only one disk at a time.\n 2) A larger disk may not be placed ontop of a smaller disk.\n 3) All disks, except the one being moved, must be on a tower. \n\n Please press the OK button to continue","CHOOSE AN OPTION?", JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE, null, new Object[]{"Yes","No"}, null);
if(choice ==1){
frame.removeAll();
frame.validate();
frame.setVisible(false);
GUIMain.startGame();
return;
}
// Keep looping through the dialogue until a valid number is entered
while (numberOfDisks > 25 || numberOfDisks < 3) {
// Show the dialogue
int userResponse = JOptionPane.showOptionDialog(null, panel, "Towers of Hanoi", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null);
if (userResponse == 1) {
frame.removeAll();
frame.validate();
frame.setVisible(false);
GUIMain.startGame();
return;
}
// Try to parse the number they entered
try {
numberOfDisks = Integer.parseInt(txt.getText());
if (numberOfDisks < 3 || numberOfDisks >25) {
JOptionPane.showMessageDialog(frame, "Please input a valid integer between 3 and 25 (inclusive)");
continue;
}
} catch (NumberFormatException nf) {
JOptionPane.showMessageDialog(frame,"Please input a valid integer between 3 and 25 (inclusive)");
continue; // NaN -> show dialogue again
}
}
int winx = numberOfDisks * 50 + 100;
int winy = 100 + (numberOfDisks)*20;
gui = new GameGUI(winx, winy);
gui.setState(new TowersOfHanoiState(numberOfDisks));
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
|
d4e23ebd-e40e-4a9e-a155-920bc5dba2c9
| 7
|
static private int jjMoveStringLiteralDfa0_0()
{
switch(curChar)
{
case 40:
return jjStopAtPos(0, 12);
case 41:
return jjStopAtPos(0, 13);
case 42:
return jjStopAtPos(0, 7);
case 43:
return jjStopAtPos(0, 5);
case 45:
return jjStopAtPos(0, 6);
case 47:
return jjStopAtPos(0, 8);
case 59:
return jjStopAtPos(0, 11);
default :
return jjMoveNfa_0(0, 0);
}
}
|
fd93c471-6fce-44fa-8389-1d0109f5f438
| 0
|
public long getSeatType() {
return this._seatType;
}
|
ee31c3be-9f4b-4165-8fc6-74269c6d78ce
| 4
|
@Override
public void draw(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
if(!ready){
esm.panel.add(initiationLabel);
esm.panel.updateUI();
} else if(ready){
drawFixationCross(g);
if(drawSaccadeCrossOne){
drawSaccadeCross(g, 1);
}
if(drawSaccadeCrossTwo){
drawSaccadeCross(g, 2);
}
}
}
|
09292ffe-1616-4c38-9e98-1d7ec77c9a45
| 5
|
public ConnectFourPanel(ConnectFourPiece[][] pieces) {
//Initialise m_pieces
m_pieces = new ConnectFourPiece[BOARD_WIDTH][BOARD_HEIGHT];
updatePieces(pieces);
//Load board image
ImageIcon boardImage;
try {
boardImage = new ImageIcon(this.getClass()
.getResource("Board.png"));
m_board = boardImage.getImage();
} catch (Exception e) {
System.out.println("Board not found");
}
//Load Yellow Piece Image
ImageIcon yellowPieceImage;
try {
yellowPieceImage = new ImageIcon(this.getClass()
.getResource("Yellow75.png"));
m_yellowPiece = yellowPieceImage.getImage();
} catch (Exception e) {
System.out.println("Yellow Piece: not found");
}
//Load Yellow Star Image
ImageIcon yellowPieceStarImage;
try {
yellowPieceStarImage = new ImageIcon(this.getClass()
.getResource("Yellow75Final.png"));
m_yellowPieceStar = yellowPieceStarImage.getImage();
} catch (Exception e) {
System.out.println("Yellow star Piece: not found");
}
//Load Red Image
ImageIcon redPieceImage;
try {
redPieceImage = new ImageIcon(this.getClass()
.getResource("Red75.png"));
m_redPiece = redPieceImage.getImage();
} catch (Exception e) {
System.out.println("Red Piece: not found");
}
//Load Red Star Image
ImageIcon redPieceStarImage;
try {
redPieceStarImage = new ImageIcon(this.getClass()
.getResource("Red75Final.png"));
m_redPieceStar = redPieceStarImage.getImage();
} catch (Exception e) {
System.out.println("Red Star Piece: not found");
}
}
|
8cdad0de-1d0e-44c5-8088-b4114293e436
| 9
|
* @param nodeSet the set of desired nodes
* @param weight the score multiplier
*/
protected void bestSpot2AwayFromANodeSet(Hashtable nodesIn, Vector nodeSet, int weight)
{
Enumeration nodesInEnum = nodesIn.keys();
while (nodesInEnum.hasMoreElements())
{
Integer nodeCoord = (Integer) nodesInEnum.nextElement();
int node = nodeCoord.intValue();
int score = 0;
final int oldScore = ((Integer) nodesIn.get(nodeCoord)).intValue();
Enumeration nodeSetEnum = nodeSet.elements();
while (nodeSetEnum.hasMoreElements())
{
int target = ((Integer) nodeSetEnum.nextElement()).intValue();
if (node == target)
{
break;
}
else if (node == (target - 0x20))
{
score = 100;
}
else if (node == (target + 0x02))
{
score = 100;
}
else if (node == (target + 0x22))
{
score = 100;
}
else if (node == (target + 0x20))
{
score = 100;
}
else if (node == (target - 0x02))
{
score = 100;
}
else if (node == (target - 0x22))
{
score = 100;
}
}
/**
* multiply by weight
*/
score *= weight;
nodesIn.put(nodeCoord, new Integer(oldScore + score));
//D.ebugPrintln("BS2AFANS -- put node "+Integer.toHexString(node)+" with old score "+oldScore+" + new score "+score);
}
}
|
1a961642-a8d3-43a6-8e84-a03245a599c7
| 1
|
public void aloitaUusiPeli(){
this.pause = false;
this.jatkuu = true;
this.pisteet = 0;
this.taso = 1;
this.rivit = 0;
this.alkutaso = 0;
this.viive = 2000;
this.pelipalikat = new Palikka[20][];
for (int i = 0; i < 20; i++) {
pelipalikat[i] = new Palikka[10];
}
luoUusiPutoava();
paivitaPisteetJaTaso();
status.setText("Paina P pysäyttääksesi pelin");
}
|
7508466c-f2b5-43b6-aa05-c64b8141f2e9
| 3
|
public static void main(String[] args) throws UnknownHostException, IOException, NumberFormatException, InterruptedException {
// Connect to the server
socket = new Socket("localhost", PORT);
// Write and read from the server through sockets
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Create a new instance of a client
PongClone client = new PongClone();
// Wait for the ACTIVE method to start the client
while (true) {
String message = in.readLine();
if (message != null) {
if (message.startsWith("ACTIVE")) {
client.ID = Integer.parseInt(message.substring("ACTIVE".length() + 1));
game.setID(Integer.parseInt(message.substring("ACTIVE".length() + 1)));
client.setActive();
break;
}
}
}
}
|
d9a70acc-3e31-4d3b-a233-c3e639c7b3c3
| 2
|
public void addDefaultBalances() {
Balance resultBalance = createResultBalance(accounts);
Balance relationsBalance = createRelationsBalance(accounts);
Balance yearBalance = createClosingBalance(accounts);
try {
addBusinessObject(resultBalance);
addBusinessObject(relationsBalance);
addBusinessObject(yearBalance);
} catch (EmptyNameException e) {
System.err.println("The Name of a Balance can not be empty.");
} catch (DuplicateNameException e) {
System.err.println("The Name of a Balance already exists. ");
}
}
|
f2f1c46b-b8ad-4d50-b680-3285086e5cbf
| 4
|
public static void creer(String pseudo, String motDePasse, String courriel, byte[] avatar, String avatarType, HttpServletRequest requete)
throws ChampInvalideException, ChampVideException, UtilisateurExistantException, MessagingException {
EntityTransaction transaction = UtilisateurRepo.get().transaction();
try {
transaction.begin();
Utilisateur u = new Utilisateur();
u.setPseudo(pseudo);
u.setMotDePasse(motDePasse);
u.setAdresseCourriel(courriel);
u.setCompteActive(false);
u.setRole(Role.Utilisateur);
validerUtilisateur(u, motDePasse, false, false, false);
if (avatar != null && avatarType != null)
u.setAvatar(FichierService.genererAvatar(avatar, avatarType));
UtilisateurRepo.get().creer(u);
CourrielActivationService.envoyerCourrielActivation(u, requete);
transaction.commit();
}
catch (ChampVideException |
ChampInvalideException |
UtilisateurExistantException |
MessagingException |
RuntimeException e) {
if (transaction.isActive())
transaction.rollback();
throw e;
}
}
|
a67dcd70-66a0-4861-97b8-e1e271eb1081
| 0
|
@Test
public void testAdjacentCell() {
System.out.println("adjacentCell");
Cell instance = new Cell(2,2);
int[] result = instance.adjacentCell(0);
assertEquals(2, result[0]);
assertEquals(3, result[1]);
result = instance.adjacentCell(1);
assertEquals(3, result[0]);
assertEquals(2, result[1]);
result = instance.adjacentCell(2);
assertEquals(3, result[0]);
assertEquals(1, result[1]);
result = instance.adjacentCell(3);
assertEquals(2, result[0]);
assertEquals(1, result[1]);
result = instance.adjacentCell(4);
assertEquals(1, result[0]);
assertEquals(1, result[1]);
result = instance.adjacentCell(5);
assertEquals(1, result[0]);
assertEquals(2, result[1]);
instance = new Cell(1,1);
result = instance.adjacentCell(0);
assertEquals(1, result[0]);
assertEquals(2, result[1]);
result = instance.adjacentCell(1);
assertEquals(2, result[0]);
assertEquals(2, result[1]);
result = instance.adjacentCell(2);
assertEquals(2, result[0]);
assertEquals(1, result[1]);
result = instance.adjacentCell(3);
assertEquals(1, result[0]);
assertEquals(0, result[1]);
result = instance.adjacentCell(4);
assertEquals(0, result[0]);
assertEquals(1, result[1]);
result = instance.adjacentCell(5);
assertEquals(0, result[0]);
assertEquals(2, result[1]);
}
|
1f81b45a-5158-42d5-a7ee-2e3561cf28af
| 9
|
private AbstractBarcodeBean createBarcode(BarcodeTypes barcodeType)
throws NotSupportedException {
AbstractBarcodeBean bean = null;
if (barcodeType == BarcodeTypes.CODE39) {
bean = new Code39Bean();
((Code39Bean)bean).setWideFactor(3);
}
else if (barcodeType == BarcodeTypes.CODE128) {
bean = new Code128Bean();
}
else if (barcodeType == BarcodeTypes.INTERLEAVED_2_OF_5) {
bean = new Interleaved2Of5Bean();
}
else if (barcodeType == BarcodeTypes.POSTNET) {
bean = new POSTNETBean();
}
else if (barcodeType == BarcodeTypes.EAN8) {
bean = new EAN8Bean();
}
else if (barcodeType == BarcodeTypes.EAN13) {
bean = new EAN13Bean();
}
else if (barcodeType == BarcodeTypes.EAN128) {
bean = new EAN128Bean();
}
else if (barcodeType == BarcodeTypes.UPCA) {
bean = new UPCABean();
}
else if (barcodeType == BarcodeTypes.UPCE) {
bean = new UPCEBean();
}
else {
throw new NotSupportedException(barcodeType.toString());
}
return bean;
}
|
fabea6e9-8a4f-4e17-a186-57867de2ce46
| 5
|
private void addEmployee() throws EndDataEntry {
try {
System.out.print("Enter the employee's name: ");
String name = IOGeneric.getString();
if (name.length() == 0)
throw new EndDataEntry();
System.out.print("Enter the employee's ID: ");
int id = IOGeneric.getInteger();
if (id == 0)
throw new EndDataEntry();
if (!emp_data.isNewID(id))
throw new DuplicateDataEntry();
emp_data.add(id, name);
System.out.print("\n");
} catch(BadInput e) {
System.out.println("Data enetered incorrectly. Try again!");
} catch(DuplicateDataEntry e) {
System.out.println("That ID already exists. Try again!\n");
}
}
|
a38e38d8-2917-4161-bd9d-1568e786ccb6
| 6
|
public void setTitleForAudioPlayer(String streamName, String title, boolean isErrorMessage) {
if(title != null && audioPanel != null)
{
String gesTitle = streamName + " : " + title;
//if the title is empty, change the title to
//the program name
if(title == null || title.trim().equals(""))
{
editWindowTitle("StreamRipStar");
//show title messages in the streamrbowser, too
audioPanel.setTitle("",isErrorMessage);
if(streamBrowser != null)
{
streamBrowser.setStatusText("",isErrorMessage);
}
} else {
editWindowTitle(title);
//show title messages in the streamrbowser, too
audioPanel.setTitle(gesTitle,isErrorMessage);
if(streamBrowser != null)
{
streamBrowser.setStatusText(gesTitle,isErrorMessage);
}
}
}
}
|
dc7d2e21-d863-48fc-b7e2-4535ef669b11
| 4
|
public static String getProjectName() {
if (GuiPackage.getInstance() == null)
return null;
String projectPath = GuiPackage.getInstance().getTestPlanFile();
String filename = "untitled";
if (projectPath != null) {
filename = new File(projectPath).getName();
if (filename.length() > 4)
filename = filename.toLowerCase().endsWith(".jmx") ? filename.substring(0, filename.length() - 4) : filename;
}
return filename;
}
|
d47bfc56-e088-4c5f-be57-76c1c91129b8
| 4
|
private void create_hash(String k,HashMap<String,Character> map)
{
String k_u=k.toUpperCase();
boolean[] filled=new boolean[26];
int total_cnt=0;
for(char c:k_u.toCharArray())
{
int pos=c-'A';
if(!filled[pos])
{
String d=get_alphabet_morse(total_cnt);
map.put(d, Character.valueOf(c));
filled[pos]=true;
total_cnt+=1;
}
else
{
continue;
}
}
for(int i=0;i<26;i++)
{
if(!filled[i])
{
String d=get_alphabet_morse(total_cnt);
char cur_c=(char)('A'+i);
map.put(d, Character.valueOf(cur_c));
filled[i]=true;
total_cnt+=1;
}
else
{
continue;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.