method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
b6091a34-082f-43dc-92f4-d372c6778d09 | 3 | public synchronized int addWalkBatch(int vertex, int numWalks) {
if (sourceSeqIdx >= sources.length)
throw new IllegalStateException("You can have a maximum of " + sources.length + " random walk sources");
if (sourceSeqIdx > 0) {
if (sources[sourceSeqIdx - 1] > vertex) {
throw new IllegalArgumentException("You need to add sources in order!");
}
}
sources[sourceSeqIdx] = vertex;
sourceWalkCounts[sourceSeqIdx] = numWalks;
totalWalks += numWalks;
sourceSeqIdx++;
return sourceSeqIdx - 1;
} |
0b6cf10c-42dc-4482-8b16-26a8b818f621 | 0 | public static void main(String[] args) throws Exception {
new HelloWorldAWTGL().loop();
} |
9c96f64c-d17d-4a6e-b4fb-cd189fd2258d | 9 | public List<Class<? super T>> inheritance() {
return unfold(
(java.lang.Class<? super T> c2) -> {
if (c == null)
return none();
else {
final P2<java.lang.Class<? super T>, java.lang.Class<? super T>> p =
new P2<java.lang.Class<? super T>, java.lang.Class<? super T>>() {
public java.lang.Class<? super T> _1() {
return c;
}
@SuppressWarnings({"unchecked"})
public java.lang.Class<? super T> _2() {
return c.getSuperclass();
}
};
return some(p);
}
}, c).map(c1 -> clas(c1));
} |
c7d02b27-271f-4b95-8613-2292d20db24e | 1 | public static void main(String[] args) {
//获取枚举类型中的全部枚举值
Week[] days = Week.values();
for(Week day : days) {
//返回枚举常量的名称
String name = day.name();
//返回枚举常量的序数(常量在枚举声明中的位置,从0开始)
int ordinal = day.ordinal();
String toString = day.toString();
Class declaringClass = day.getDeclaringClass();
Class superClass = declaringClass.getSuperclass();
System.out.println(
"Name: " + name
+ "\n"
+ "Ordinal: " + ordinal
+ "\n"
+ "ToString: " + toString
+ "\n"
+ "DeclaringClass: " + declaringClass
+ "\n"
+ "SuperClass: " + superClass
+ "\n"
);
}
//创建枚举变量
//直接创建枚举常量
Week mon = Week.MONDAY;
//使用Enum的valueOf()静态方法创建枚举常量
Week tues = Enum.valueOf(Week.class, "TUESDAY");
//使用枚举类型的valueOf()静态方法创建枚举常量
Week wed = Week.valueOf("WEDNESDAY");
//比较枚举变量,实际上是比较它们序数的大小
System.out.println(mon.compareTo(tues));
System.out.println(tues.compareTo(wed));
System.out.println(wed.compareTo(mon));
} |
b0969ce3-e304-44df-9d9d-02fd97f64c8a | 1 | public static String fetchLink(String lineText)
{
if(linkExists(lineText)) return link.get(lineText);
return null;
} |
82e4ef10-3f4e-425b-8cf8-a3bbd80e4436 | 5 | public String getPiece() {
boolean readString = true;
String piece = getString("What type of piece would you like to be? Enter x or o.");
while (readString) {
if (!(piece.equals("x") || piece.equals("X") || piece.equals("o") || piece.equals("O"))) {
System.out.println( "Oops, you must enter x or o, try again." );
piece = getString("What type of piece would you like to be? Enter x or o.");
}
else {
readString = false;
}
}
return piece;
} |
b1241fb5-e89f-42a6-9c19-8c2e7a09443f | 8 | public static void addMethods( Class<?> c, MethodDepth depth )
{
switch (depth)
{
case DEFINED:
for (Method m : c.getDeclaredMethods())
{
addMethod( m );
}
break;
case PUBLIC_INHERITED:
for (Method m : c.getMethods())
{
addMethod( m );
}
break;
case ALL_INHERITED:
for (Method m : c.getDeclaredMethods())
{
addMethod( m );
}
if (c.getSuperclass() != Object.class)
{
addMethods( c.getSuperclass(), depth );
}
break;
}
} |
af0075b5-09a5-465a-ac26-4e9f6b91af89 | 5 | public static boolean warpNextMap(final MapleCharacter c, final boolean fromResting) {
final int currentmap = c.getMapId();
final ChannelServer ch = c.getClient().getChannelServer();
if (!fromResting) {
clearMap(ch.getMapFactory().getMap(currentmap), true);
c.gainItem(Items.currencyType.Sight, 1);
c.setDojoPoints(c.getDojoPoints() + 10);
c.getClient().getSession().write(MulungDojoPackets.Mulung_Pts(10, c.getDojoPoints()));
}
if (currentmap >= 925023800 && currentmap <= 925023814) {
final MapleMap map = ch.getMapFactory().getMap(925020003);
c.gainItem(Items.currencyType.Sight, 20);
c.changeMap(map, map.getPortal(1));
return true;
}
final int temp = (currentmap - 925000000) / 100;
final int thisStage = (int) (temp - (Math.floor(temp / 100) * 100));
final int nextmapid = 925020000 + ((thisStage + 1) * 100);
for (int i = nextmapid; i < nextmapid + 15; i++) {
final MapleMap map = ch.getMapFactory().getMap(i);
if (map.getCharactersSize() == 0) {
clearMap(map, false);
c.changeMap(map, map.getPortal(0));
spawnMonster(map, thisStage + 1);
return true;
}
}
return false;
} |
8b81dbab-f0ce-4ead-95c7-f75ee3da7e32 | 7 | private static Collection liveMethods(final Collection classes,
final BloatContext context) {
// Determine the roots of the call graph
final Set roots = new HashSet();
Iterator iter = classes.iterator();
while (iter.hasNext()) {
final String className = (String) iter.next();
try {
final ClassEditor ce = context.editClass(className);
final MethodInfo[] methods = ce.methods();
for (int i = 0; i < methods.length; i++) {
final MethodEditor me = context.editMethod(methods[i]);
if (!me.name().equals("main")) {
continue;
}
BloatBenchmark.tr(" Root " + ce.name() + "." + me.name()
+ me.type());
roots.add(me.memberRef());
}
} catch (final ClassNotFoundException ex1) {
BloatBenchmark.err.println("** Could not find class: "
+ ex1.getMessage());
System.exit(1);
}
}
if (roots.isEmpty()) {
BloatBenchmark.err.print("** No main method found in classes: ");
iter = classes.iterator();
while (iter.hasNext()) {
final String name = (String) iter.next();
BloatBenchmark.err.print(name);
if (iter.hasNext()) {
BloatBenchmark.err.print(", ");
}
}
BloatBenchmark.err.println("");
}
context.setRootMethods(roots);
final CallGraph cg = context.getCallGraph();
final Set liveMethods = new TreeSet(new MemberRefComparator());
liveMethods.addAll(cg.liveMethods());
return (liveMethods);
} |
f311d8b5-6abc-44dd-96f0-82aabe07d18c | 3 | public static boolean isEmptyString(String str, boolean showError)
{
boolean bool = false;
if (Utils.isNull(str, true))
{
}
if (str.replaceAll(" ", "").isEmpty())
{
bool = true;
if (showError)
{
final IllegalArgumentException as = new IllegalArgumentException("The Parameter Cannot Be Empty!");
as.printStackTrace();
exit();
}
}
return bool;
} |
ef4dcfbc-8ea4-4d2c-af9b-5f8cc3996444 | 5 | private void idCmbxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idCmbxActionPerformed
String id = "";
if (idCmbx.getSelectedItem() != null && idCmbx.getSelectedIndex() != 0) {
id = idCmbx.getSelectedItem().toString();
try {
Student student = controller.searchStudentByID(id);
addTxt.setText(student.getAddress());
phoneTxt.setText(student.getMobileNumber());
genderTxt.setText(student.isMale()? "Male" : "Female");
gurdNameTxt.setText(student.getGuardianName());
guardPhnTxt.setText(student.getGuardianNumber());
nameCmbx.setSelectedItem(student.getFirstName() + " " + student.getLastName());
imgLbl.setIcon(student.getImage());
ResultSet rst = controller.getClassDetails(id);
while(rst.next()){
tableModel.addRow(new String[] {rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4)});
}
} catch (SQLException ex) {
}
}
}//GEN-LAST:event_idCmbxActionPerformed |
bfd9abe4-0433-404b-8971-e39c92f914a6 | 7 | public void start() throws InstantiationException, IllegalAccessException{
//new intance
for(Class<? extends IModule> clazz:classSet){
IModule module=(IModule)clazz.newInstance();
this.moduleSet.add(module);
}
//init context
for(IModule module:moduleSet){
moduleContext.addModule(module);
for(Entry<Class<? extends ISimpleService>,ISimpleService> e:module.getServiceImpls().entrySet()){
moduleContext.addService(e.getKey(), e.getValue());
}
}
//module start
for(IModule module:moduleSet){
module.init(moduleContext);
}
for(IModule module:moduleSet){
module.startUp(moduleContext);
}
} |
5d460f2c-86fb-4c6a-a3ea-1ee85861fc63 | 6 | public void overwriteTRNS(byte r, byte g, byte b) {
if(hasAlphaChannel()) {
throw new UnsupportedOperationException("image has an alpha channel");
}
byte[] pal = this.palette;
if(pal == null) {
transPixel = new byte[] { 0, r, 0, g, 0, b };
} else {
paletteA = new byte[pal.length/3];
for(int i=0,j=0 ; i<pal.length ; i+=3,j++) {
if(pal[i] != r || pal[i+1] != g || pal[i+2] != b) {
paletteA[j] = (byte)0xFF;
}
}
}
} |
9f3eb9bf-8c8f-4e57-b544-adf4f8d37b0a | 7 | @Override
public BodyElement process(BodyElement source) {
JsArray<Node> toProcess = (JsArray<Node>) JsArray.createArray();
extractChild(source, toProcess);
Node node;
while ((node = toProcess.shift()) != null) {
int type;
try {
type = node.getNodeType();
if (type == Node.TEXT_NODE) {
if (node.getNodeValue().isEmpty()) {
// On supprime les noeuds textes vides
node.removeFromParent();
}
} else if (type == Node.ELEMENT_NODE) {
Element element = (Element) node;
if (element.getAttribute(DOMUtil.DIRTY_ATTRIBUTE) != null
&& element.getAttribute(DOMUtil.DIRTY_ATTRIBUTE).equals("true")) {
node.removeFromParent();
} else {
extractChild(node, toProcess);
}
}
} catch (Exception e) {
node.removeFromParent();
}
}
return source;
} |
e82cb137-8ae0-40fa-b7a5-291182a66f99 | 9 | private void sendSuccessfulResponse(SipRequest sipRequest, Dialog dialog) {
SipHeaders reqHeaders = sipRequest.getSipHeaders();
SipHeaderFieldValue contentType =
reqHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE));
if (RFC3261.CONTENT_TYPE_SDP.equals(contentType)) {
//TODO
// String sdpResponse;
// try {
// sdpResponse = sdpManager.handleOffer(
// new String(sipRequest.getBody()));
// } catch (NoCodecException e) {
// sdpResponse = sdpManager.generateErrorResponse();
// }
} else {
// TODO manage empty bodies and non-application/sdp content type
}
//TODO if mode autoanswer just send 200 without asking any question
SipResponse sipResponse =
RequestManager.generateResponse(
sipRequest,
dialog,
RFC3261.CODE_200_OK,
RFC3261.REASON_200_OK);
// TODO 13.3 dialog invite-specific processing
// TODO timer if there is an Expires header in INVITE
// TODO 3xx
// TODO 486 or 600
byte[] offerBytes = sipRequest.getBody();
SessionDescription answer;
try {
if (offerBytes != null && contentType != null &&
RFC3261.CONTENT_TYPE_SDP.equals(contentType.getValue())) {
// create response in 200
try {
SessionDescription offer = sdpManager.parse(offerBytes);
answer = sdpManager.createSessionDescription(offer);
mediaDestination = sdpManager.getMediaDestination(offer);
} catch (NoCodecException e) {
answer = sdpManager.createSessionDescription(null);
}
} else {
// create offer in 200 (never tested...)
answer = sdpManager.createSessionDescription(null);
}
sipResponse.setBody(answer.toString().getBytes());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
SipHeaders respHeaders = sipResponse.getSipHeaders();
respHeaders.add(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE),
new SipHeaderFieldValue(RFC3261.CONTENT_TYPE_SDP));
ArrayList<String> routeSet = dialog.getRouteSet();
if (routeSet != null) {
SipHeaderFieldName recordRoute = new SipHeaderFieldName(RFC3261.HDR_RECORD_ROUTE);
for (String route : routeSet) {
respHeaders.add(recordRoute, new SipHeaderFieldValue(route));
}
}
// TODO determine port and transport for server transaction>transport
// from initial invite
// FIXME determine port and transport for server transaction>transport
ServerTransaction serverTransaction = transactionManager
.getServerTransaction(sipRequest);
if (serverTransaction == null) {
// in re-INVITE case, no serverTransaction has been created
serverTransaction = (InviteServerTransaction)
transactionManager.createServerTransaction(sipResponse,
userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this,
sipRequest);
}
serverTransaction.start();
serverTransaction.receivedRequest(sipRequest);
serverTransaction.sendReponse(sipResponse);
// TODO manage retransmission of the response (send to the transport)
// until ACK arrives, if no ACK is received within 64*T1, confirm dialog
// and terminate it with a BYE
// logger.getInstance().debug("before dialog.receivedOrSent2xx();");
// logger.getInstance().debug("dialog state: " + dialog.getState());
} |
fa01f919-b05a-4387-a82c-20fa9f77c162 | 0 | @Override
public void windowClosed(WindowEvent e)
{
} |
1af744f0-595c-4ce3-9e5e-1a556e437925 | 8 | public int computeAreaPart(int top, int bottom, Box topBox, Box bottomBox, Box current) {
int area = 0;
if (top < MAX_VALUE && bottom < MAX_VALUE) {
if (current.in(topBox) && current.in(bottomBox)) {
area = -current.area();
} else {
int topLength = current.intersectionLength(topBox);
int bottomLength = current.intersectionLength(bottomBox);
if (topLength == bottomLength) {
area = -current.area();
} else if (topLength > bottomLength) {
area = -(bottomLength * current.weight());
area += ((topLength - bottomLength) * topBox.weightDistance(current));
} else {
area = -(topLength * current.weight());
area += ((bottomLength - topLength) * current.weightDistance(bottomBox));
}
}
} else if (top < MAX_VALUE) {
area = current.intersectionArea(topBox);
} else if (bottom < MAX_VALUE) {
area = current.intersectionArea(bottomBox);
}
return area;
} |
565191ef-d1bd-4786-9dbc-2ecabb589e32 | 9 | public void drawAsLine(Graphics graphics, double xmin, double xmax, double ymin, double ymax, Dimension componentSize) {
Graphics2D g = (Graphics2D) graphics;
double b1 = a*xmin + b;
double b2 = a*xmax + b;
double y1 = VisualPoint.bToY(b1, ymin, ymax, componentSize);
double y2 = VisualPoint.bToY(b2, ymin, ymax, componentSize);
/*double yscale = componentSize.getHeight() / (ymax - ymin);
double y1 = a*xmin + b;
double y2 = a*xmax + b;
double dy1 = ((-y1)+ ymax)*yscale;
double dy2 = ((-y2)+ ymax)*yscale;*/
if (this.type == PointType.BLUE) {
if (this.highlighted) {
if (this.deleted) {
g.setColor(new Color(200, 255, 255));
} else {
g.setColor(Color.cyan);
}
} else {
if (this.deleted) {
g.setColor(new Color(200, 200, 255));
} else {
g.setColor(Color.blue);
}
}
} else if (this.type == PointType.RED) {
if (this.highlighted) {
if (this.deleted) {
g.setColor(new Color(255, 255, 200));
} else {
g.setColor(Color.orange);
}
} else {
if (this.deleted) {
g.setColor(new Color(255, 200, 200));
} else {
g.setColor(Color.red);
}
}
} else {
throw new IllegalStateException("Invalid point type.");
}
if (this.deleted) {
g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{3}, 0));
g.drawLine(0,(int) componentSize.getHeight() - (int) y1,(int) componentSize.getWidth(), (int) componentSize.getHeight() - (int) y2);
g.setStroke(new BasicStroke(1));
} else {
g.drawLine(0,(int) componentSize.getHeight() - (int) y1,(int) componentSize.getWidth(), (int) componentSize.getHeight() - (int) y2);
}
} |
bf97dc3f-cd51-4185-ae65-783c0d41e838 | 3 | public int temaLookback( int optInTimePeriod )
{
int retValue;
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 30;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
retValue = emaLookback ( optInTimePeriod );
return retValue * 3;
} |
74ddbdcd-5d5f-4e93-b6f1-1d5d3d79ec14 | 1 | public void stop() {
System.out.println("Stopping attack. . .");
for (Flooder flooder : flooders) {
flooder.stop();
}
running = false;
} |
d33e25e1-8cf9-45d4-82a4-b4b1008e7881 | 4 | public String genJSONRequest(String method, String field, String id) {
try {
JsonObject req = new JsonObject();
req.addProperty("method", method);
JsonObject arguments = new JsonObject();
//FIELDS
Scanner sc = new Scanner(field).useDelimiter(", *");
//JsonObject args = new JsonObject();
JsonArray argsarray = new JsonArray();
while (sc.hasNext()) {
//args.append("fields", sc.next());
argsarray.add(new JsonPrimitive(sc.next()));
}
//req.add("arguments", fields);
arguments.add("fields", argsarray);
//IDS
if(id != null){
sc = new Scanner(id).useDelimiter(", *");
JsonArray idsarray = new JsonArray();
while (sc.hasNext()) {
//args.append("fields", sc.next());
idsarray.add(new JsonPrimitive(Integer.parseInt(sc.next())));
}
//req.add("arguments", idsarg);
arguments.add("ids", idsarray);
}
req.add("arguments", arguments);
return req.toString();
} catch (JsonIOException e) {
return null;
}
} |
cffe4852-3374-4492-88ed-85f77bde47a8 | 3 | @Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof Position))
return false;
Position pos = (Position)other;
return ((this.row == pos.row) && (this.col == pos.col));
} |
feec5f3d-1964-4fe7-bdac-ebb6053f89a8 | 5 | private static int[] getFirstK(double[] sum, int k) {
Map<Integer, Double> m = new TreeMap<Integer, Double>();
for (int i = 0; i < sum.length; i++) {
m.put(i, sum[i]);
}
List<Map.Entry<Integer, Double>> mappingList = null;
mappingList = new ArrayList<Map.Entry<Integer, Double>>(m.entrySet());
Collections.sort(mappingList,
new Comparator<Map.Entry<Integer, Double>>() {
public int compare(Map.Entry<Integer, Double> mapping1,
Map.Entry<Integer, Double> mapping2) {
return mapping1.getValue().compareTo(
mapping2.getValue());
}
});
Map<Integer, Double> newMap = new HashMap<Integer, Double>();
int count = 0;
for (Map.Entry<Integer, Double> mapping : mappingList) {
newMap.put(mapping.getKey(), mapping.getValue());
count++;
if (count == k) {
break;
}
}
int array[] = new int[k];
Iterator<Integer> iterator = newMap.keySet().iterator();
while (iterator.hasNext() && k > 0) {
array[k - 1] = (int) iterator.next();
k--;
}
return array;
} |
37e643a9-cb1e-4d9a-a764-e9d28be59255 | 2 | public Object open() {
createContents();
UI.centerShell(getParent(), shell);
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
} |
8dec63ee-0544-4abb-8849-9d92aa7fd4b4 | 8 | static private void parseDataVariables(DodsV parent, Enumeration children) throws NoSuchVariableException {
while (children.hasMoreElements()) {
opendap.dap.BaseType bt = (opendap.dap.BaseType) children.nextElement();
DodsV dodsV = new DodsV(parent, bt);
parent.children.add(dodsV);
if (bt instanceof DGrid) {
DGrid dgrid = (DGrid) bt;
if (dodsV.parent.bt == null) { // is top level
// top level grids are replaced by their "data array"
dodsV.darray = (DArray) dgrid.getVar(0);
processDArray( dodsV);
} else {
// nested grids are made into Structures
dodsV.makeAllDimensions();
}
java.util.Enumeration enumerate2 = dgrid.getVariables();
parseDataVariables(dodsV, enumerate2);
} else if (bt instanceof DSequence) {
DSequence dseq = (DSequence) bt;
int seqlen = dseq.getRowCount();
if (seqlen > 0) {
DArrayDimension ddim = new DArrayDimension(seqlen, null);
dodsV.dimensions.add(ddim);
}
dodsV.makeAllDimensions();
java.util.Enumeration enumerate2 = dseq.getVariables();
parseDataVariables(dodsV, enumerate2);
} else if (bt instanceof DConstructor) {
DStructure dcon = (DStructure) bt;
dodsV.makeAllDimensions();
java.util.Enumeration enumerate2 = dcon.getVariables();
parseDataVariables(dodsV, enumerate2);
} else if (bt instanceof DArray) {
dodsV.darray = (DArray) bt;
processDArray( dodsV);
dodsV.bt = dodsV.elemType;
if (dodsV.elemType instanceof DStructure) {
DStructure dcon = (DStructure) dodsV.elemType;
java.util.Enumeration nestedVariables = dcon.getVariables();
parseDataVariables(dodsV, nestedVariables);
}
} else {
dodsV.makeAllDimensions();
}
}
} |
b492da07-addc-47be-89c6-4e3eeb735766 | 9 | @Override
public boolean importData(TransferSupport support) {
if(!canImport(support))
return false;
Transferable transferable = support.getTransferable();
try {
ArrayList<Object> data = (ArrayList<Object>) transferable.getTransferData(
new DataFlavor((DataFlavor.javaJVMLocalObjectMimeType + ";class=java.util.ArrayList"))
);
boolean valid = true;
for(Object element : data) {
if(!(element instanceof Song || element instanceof Playlist)) {
valid = false;
}
}
if(valid) {
for(Object element : data) {
((DefaultListModel)_myList.getModel()).insertElementAt(element, _myList.getModel().getSize());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
} |
ffa39f77-531d-4f61-a146-cf94e0863f7b | 6 | public void handlePlayerInfo(Packet201PlayerInfo par1Packet201PlayerInfo)
{
GuiPlayerInfo var2 = (GuiPlayerInfo)this.playerInfoMap.get(par1Packet201PlayerInfo.playerName);
if (var2 == null && par1Packet201PlayerInfo.isConnected)
{
var2 = new GuiPlayerInfo(par1Packet201PlayerInfo.playerName);
this.playerInfoMap.put(par1Packet201PlayerInfo.playerName, var2);
this.playerNames.add(var2);
}
if (var2 != null && !par1Packet201PlayerInfo.isConnected)
{
this.playerInfoMap.remove(par1Packet201PlayerInfo.playerName);
this.playerNames.remove(var2);
}
if (par1Packet201PlayerInfo.isConnected && var2 != null)
{
var2.responseTime = par1Packet201PlayerInfo.ping;
}
} |
86c3d1ba-1b18-45ed-8d15-f827a79afcc6 | 7 | public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} |
8f67b829-2b85-46b9-b695-a338046e11d1 | 4 | public List<Position> getPath2(int x, int y){
try{
Pattern pattern= Pattern.compile("(\\d+)");
List<Position> posList= new ArrayList<>();
int X,Y = 0;
if(posicao(pacmanX(),pacmanY())){
String str=intelFant(x, y, pacmanX(), pacmanY(),"solve2");
Matcher matcher=pattern.matcher(str);
while(matcher.find()){
X=Integer.parseInt(matcher.group());
if(matcher.find()){
Y=Integer.parseInt(matcher.group());
}
posList.add(new Position(X,Y));
}
}
return posList;
} catch(NumberFormatException ex){
return new ArrayList<>();
}
} |
9b9ea96d-66a3-44a3-95b5-f810bfab4fd7 | 7 | protected T fetchOverlappingInterval(T queryInterval) {
Node<U, T> node = (Node<U, T>) binarySearchTree.getRoot();
while (node != null) {
if (node.getValue().overlaps(queryInterval)) {
return node.getValue();
}
Node<U, T> leftChild = node.getLeft();
node = node.getRight();
if (leftChild != null) {
int cmp = leftChild.getSubtreeSpanHigh().compareTo(queryInterval
.getLow());
if (cmp > 0 || cmp == 0 && leftChild.isClosedOnSubtreeSpanHigh()
&& queryInterval.isClosedOnLow()) {
node = leftChild;
}
}
}
return null;
} |
188fed8c-8a1f-48bd-8712-101fab4ee3c3 | 3 | public void setAvalie(PExpLogica node)
{
if(this._avalie_ != null)
{
this._avalie_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._avalie_ = node;
} |
f07b4ed2-11d7-420a-8257-c8c4e0ab508a | 4 | public static TreeNode initNormalTree(int id){
TreeNode root = new TreeNode(1);
if(id==1) {
/**
* 1
* 2 3
* 4 5 6 7
*/
TreeNode l = new TreeNode(2);
TreeNode r = new TreeNode(3);
root.left = l;
root.right = r;
TreeNode ll = new TreeNode(4);
TreeNode lr = new TreeNode(5);
l.left = ll;
l.right = lr;
TreeNode rl = new TreeNode(6);
TreeNode rr = new TreeNode(7);
r.left = rl;
r.right = rr;
}else if(id==2){
/**
* 1
* 2
*/
TreeNode l = new TreeNode(2);
root.left = l;
}else if(id==4){
/**
* 2
* 1 3
*/
root.val = 2;
TreeNode l = new TreeNode(1);
TreeNode r = new TreeNode(3);
root.left = l;
root.right = r;
}else if(id==3){
/**
* [5,3,6,2,4,null,null,1]
* 5
* 3 6
* 2 4 n n
* 1
node with value 1
node with value 3
*/
root.val = 5;
TreeNode l = new TreeNode(3);
TreeNode r = new TreeNode(6);
root.left = l;
root.right = r;
TreeNode ll = new TreeNode(2);
TreeNode lr = new TreeNode(4);
l.left = ll;
l.right = lr;
TreeNode lll = new TreeNode(1);
ll.left = lll;
// TreeNode rl = new TreeNode(6);
// TreeNode rr = new TreeNode(7);
// r.left = rl;
// r.right = rr;
}
return root;
} |
fd41fb48-a0c5-4a50-8d46-927a48850cae | 6 | public Set<Map.Entry<K,Integer>> entrySet() {
return new AbstractSet<Map.Entry<K,Integer>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TObjectIntMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if ( o instanceof Map.Entry ) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TObjectIntMapDecorator.this.containsKey( k ) &&
TObjectIntMapDecorator.this.get( k ).equals( v );
} else {
return false;
}
}
public Iterator<Map.Entry<K,Integer>> iterator() {
return new Iterator<Map.Entry<K,Integer>>() {
private final TObjectIntIterator<K> it = _map.iterator();
public Map.Entry<K,Integer> next() {
it.advance();
final K key = it.key();
final Integer v = wrapValue( it.value() );
return new Map.Entry<K,Integer>() {
private Integer val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry &&
( ( Map.Entry ) o ).getKey().equals( key ) &&
( ( Map.Entry ) o ).getValue().equals( val );
}
public K getKey() {
return key;
}
public Integer getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Integer setValue( Integer value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<K,Integer> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
K key = ( ( Map.Entry<K,Integer> ) o ).getKey();
_map.remove( key );
modified = true;
}
return modified;
}
public boolean addAll(Collection<? extends Map.Entry<K,Integer>> c) {
throw new UnsupportedOperationException();
}
public void clear() {
TObjectIntMapDecorator.this.clear();
}
};
} |
acc367b1-de9b-479d-9286-307acb02c85d | 1 | public void testDES() {
String source = "abcdefghijklmnopqrstuvwxyz";
try {
String key = DESCoder.initKey(source);
byte[] data = DESCoder
.encrypt(source.getBytes(), key, DESCoder.DES);
byte[] result = DESCoder.decrypt(data, key, DESCoder.DES);
assertEquals(source, new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} |
89dbbbb6-8130-4201-b252-8f26528d730b | 1 | public boolean isDelete() {
return !(myAdd || myChange);
} |
98b65241-cae4-4cda-8a9d-2536a06a701f | 2 | public static void main(String[] args) throws Exception {
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock = sersock.accept( );
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from client ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;
while(true) {
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println("Client>> "+receiveMessage);
}
sendMessage =keyRead.readLine();
pwrite.println(sendMessage);
System.out.flush();
}
} |
58674004-d3f0-47a7-8fcc-051045109465 | 3 | public String getDefaultName() {
switch (typecode) {
case TC_LONG:
return "l";
case TC_FLOAT:
return "f";
case TC_DOUBLE:
return "d";
default:
return "local";
}
} |
0165ffe8-6c34-4246-addc-08c74761abe6 | 3 | @Override
public GameState doAction(GameState state, Card card, int time) {
if(time == Time.DAY)
{
//Do nothing
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
state = temp.doAction(state, card, time);
}
else if(time == Time.NIGHT)
{
state = waitressNightAction(state, card);
}
return state;
} |
32e72894-717a-4719-aa60-206ac128ebf0 | 5 | public boolean isPressed() {
if (KeyMapping.xboxController.isAttached()) {
if (button != null && button.isPressed()) {
return true;
}
}
if (Keyboard.isKeyDown(keyboardValue)) {
if (!keyHeld) {
keyHeld = true;
return true;
}
} else {
keyHeld = false;
}
return false;
} |
7a6e900a-9527-44d0-b35a-a10845122cf3 | 2 | private void travelTree(TreeNode node, List<Integer> result) {
//record
result.add(node.val);
TreeNode left = node.left;
TreeNode right = node.right;
//travel left
if(null != left) travelTree(left, result);
//travel right
if(null != right) travelTree(right, result);
} |
8fc0f865-f03a-4165-ad7a-a80e4d575b3c | 1 | private boolean VerifySelectedObject() {
if(world.getSelectObject() == null)
return selectObjectName.equals("null");
else
return selectObjectName.equals(world.getSelectObject().getName());
} |
b27070ad-6d07-45e0-8c4c-196013a94d58 | 4 | public void frame254(int i1, int i2, int i3, int i4, int i5)
{
outStream.createFrame(254);
outStream.writeByte(i1);
if(i1 == 1)
{
outStream.writeWord(i2);
}
if(i1 >= 2 && i1 <= 6)
{
outStream.writeWord(i3);
outStream.writeWord(i4);
outStream.writeByte(i5);
}
if(i1 == 10)
{
outStream.writeWord(i2);
}
sendMessage("Frame 254 tested");
updateRequired = true;
appearanceUpdateRequired = true;
} |
c30e0c8f-8a02-4279-9af6-99d2266d697b | 6 | @Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(e.isControlDown() && uManager.canUndo()) {
// C-z でUndo実行
if(key == KeyEvent.VK_Z && uManager.canUndo()) {
uManager.undo();
e.consume();
}
// C-y でRedo実行
if(key == KeyEvent.VK_Y && uManager.canRedo()) {
uManager.redo();
e.consume();
}
}
} |
c53812e5-a8d0-4ef1-99e6-375702da1225 | 8 | public static void main(String[] args) throws Exception {
if (args.length != 9) {
System.err.print("Syntax error. Correct syntax:\n"
+ " <trainfile_supervised>" + " <trainfile_semisupervised>"
+ " <supervised_weight>" + " <observation_feature>"
+ " <state_feature>" + " <modelfile>" + " <numiterations>"
+ " <encoding>" + " <seed>" + "\n");
System.exit(1);
}
int arg = 0;
String trainFileNameS = args[arg++];
String trainFileNameSS = args[arg++];
double weightS = Double.parseDouble(args[arg++]);
String observationFeatureLabel = args[arg++];
String stateFeatureLabel = args[arg++];
String modelFileName = args[arg++];
int numIterations = Integer.parseInt(args[arg++]);
String encodingFileName = args[arg++];
int seed = Integer.parseInt(args[arg++]);
System.out.println(String.format(
"Unsupervised training HMM model with the following parameters:\n"
+ "\tSupervised train file: %s\n"
+ "\tSemi-supervised train file: %s\n"
+ "\tSupervised weight: %f\n"
+ "\tObservation feature: %s\n"
+ "\tState feature: %s\n" + "\tModel file: %s\n"
+ "\t# iterations: %d\n" + "\tEncoding file: %s\n"
+ "\tSeed: %d\n", trainFileNameS, trainFileNameSS,
weightS, observationFeatureLabel, stateFeatureLabel,
modelFileName, numIterations, encodingFileName, seed));
if (seed > 0)
RandomGenerator.gen.setSeed(seed);
// State labels from the initial model.
String[] stateFeaturesV = { "0", "B-PER", "I-PER", "B-LOC", "I-LOC",
"B-ORG", "I-ORG", "B-MISC", "I-MISC" };
// Load the encoding.
FeatureValueEncoding encoding = new FeatureValueEncoding(
encodingFileName, true);
// Load the first trainset (supervised).
Corpus trainsetS = new Corpus(trainFileNameS, encoding);
int size1 = trainsetS.getNumberOfExamples();
// Load the second trainset (semi-supervised).
Corpus trainsetSS = new Corpus(trainFileNameSS, encoding);
int size2 = trainsetSS.getNumberOfExamples();
// Join the two datasets.
trainsetS.add(trainsetSS);
trainsetSS = null;
// Create and fill the weight vector.
Vector<Object> weights = new Vector<Object>(size1 + size2);
weights.setSize(size1 + size2);
int idxExample = 0;
for (; idxExample < size1; ++idxExample)
weights.set(idxExample, weightS);
for (; idxExample < size1 + size2; ++idxExample)
weights.set(idxExample, 1.0);
// Supervised train an initial model on the joined dataset.
WeightedHmmTrainer wHmmTrainer = new WeightedHmmTrainer();
wHmmTrainer.setWeights(weights);
HmmModel modelSupervised = wHmmTrainer.train(trainsetS,
observationFeatureLabel, stateFeatureLabel, "0");
// Fill the tagged flag vector.
Vector<Object> flags = new Vector<Object>(size1 + size2);
// All examples in the first dataset are flagged as tagged.
idxExample = 0;
for (; idxExample < size1; ++idxExample)
flags.add(new Boolean(true));
// The tokens tagged different of 0 are flagged as tagged. The rest are
// flagged as untagged.
for (; idxExample < size1 + size2; ++idxExample) {
DatasetExample example = trainsetS.getExample(idxExample);
Vector<Boolean> flagsEx = new Vector<Boolean>(example.size());
for (int token = 0; token < example.size(); ++token) {
if (example.getFeatureValueAsString(token, stateFeatureLabel)
.equals("0"))
flagsEx.add(false);
else
flagsEx.add(true);
}
flags.add(flagsEx);
}
// Train an HMM model.
SemiSupervisedHmmTrainer ssHmmTrainer = new SemiSupervisedHmmTrainer();
ssHmmTrainer.setTaggedExampleFlags(flags);
ssHmmTrainer.setWeights(weights);
ssHmmTrainer.setInitialModel(modelSupervised);
HmmModel model = ssHmmTrainer.train(trainsetS, observationFeatureLabel,
stateFeatureLabel, stateFeaturesV, numIterations);
// Save the model.
model.save(modelFileName);
} |
f111765d-0970-4ea5-ac2f-56519577d45e | 1 | private void jjCheckNAddStates(int start, int end)
{
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
} |
2579b3cd-daa5-481d-8435-077005c0b9ab | 4 | @Override
protected int getCountInternal(Query query) throws IOException {
// TODO: support query filter
Filter filter = query.getFilter();
if (filter != null) {
//LOGGER.severe("Unhandled filter in getCountInternal" + query.getFilter());
LOGGER.warning("Unable handler filter in getCountInternal" + query.getFilter().getClass().getName());
}
int count = -1;
try {
Statement q = getDataStore().getConnection().createStatement();
ResultSet res = q.executeQuery("SELECT COUNT(*) FROM " + typeName);
count = res.getInt(1);
res.close();
q.close();
} catch (SQLException e) {
throw new IOException(e);
}
if (checkLimitOffset(query)) {
final int limit = query.getMaxFeatures();
if (limit > count) {
count = limit;
}
}
System.out.println("FeatureCount: " + count);
return count;
} |
a2f1964e-779e-416e-8d87-cad12d2cdc9e | 0 | public String getName() {
return name;
} |
eb5c2da5-1382-406a-871b-47cc578d7974 | 3 | public synchronized boolean removalStep()
{
long l1 = this.TopMessageFinishedAt + 6000L;
long l2 = System.currentTimeMillis();
if (l1 > l2)
{
startRemovalDelay((int)(l1 - l2));
}
else if (this.CurrentMessages.size() > 0)
{
remove((Component)this.CurrentMessages.elementAt(0));
doLayout();
this.CurrentMessages.removeElementAt(0);
if (this.CurrentMessages.size() == 0) {
disappear();
}
else
{
this.TopMessageFinishedAt = l2;
startRemovalDelay(6000);
}
}
return false;
} |
a6628a65-a232-4f99-b091-b9a9ef2300af | 2 | public void connect() throws ErrorException {
try {
Class.forName( this.DRIVER );
} catch( ClassNotFoundException e ) {
throw new ErrorException( "Brak sterownika JDBC" );
}
try {
polaczenie = DriverManager.getConnection( DB_URL, username, password );
komunikat = polaczenie.createStatement();
} catch( SQLException e ) {
throw new ErrorException( "Problem z podłączeniem do bazy danych.");
}
} |
117b7324-1113-407a-b4e4-de1236ab7780 | 9 | public String getDescription(Hand other) {
if (isRoyalFlush()) return "Royal Flush";
if (isStraightFlush()) return "Straight Flush";
if (hasFourOfAKind()) return "Four of a Kind";
if (isFullHouse()) return "Full House";
if (isFlush()) return "Flush";
if (isStraight()) return "Straight";
if (hasThreeOfAKind()) return "Three of a Kind";
if (hasTwoPairs()) return "Two Pairs";
if (hasOnePair()) return "Pair";
return "High Card " + getHighCards(this, other).get(0);
} |
81ccc559-6c03-44d6-8fd8-7f29e99060fe | 7 | private Task updateTask(Task currentTask, Task taskToUpdated) {
if (currentTask.getDescription() != null) {
taskToUpdated.setDescription(currentTask.getDescription());
}
if (currentTask.getFromDateTime() != null
&& currentTask.getToDateTime() != null) {
taskToUpdated.setFromDateTime(currentTask.getFromDateTime());
taskToUpdated.setToDateTime(currentTask.getToDateTime());
}
if (currentTask.getFromDateTime() != null
&& currentTask.getToDateTime() == null) {
taskToUpdated.setFromDateTime(currentTask.getFromDateTime());
taskToUpdated.setToDateTime(null);
}
if (currentTask.getLabels() != null) {
if (!super.getTask().getLabels().isEmpty()) {
taskToUpdated.setLabels(currentTask.getLabels());
}
}
Task updatedTask = taskToUpdated;
return updatedTask;
} |
264053f4-e8cb-4c5b-ab17-d17187571af1 | 0 | public static ArrayList<Excel> rotateZ(int angle, ArrayList<Excel> toScale)
{
return Rotate.rotateZ(angle, toScale);
} |
c8dcdbb0-8e01-476d-abec-ea7d71d138ac | 3 | public static byte[] decode(InputStream in) throws IOException {
byte first = (byte) in.read();
if (first == -1) {
throw new IOException("End of stream");
}
int length;
if (first >= 0) {
length = first + 1;
} else {
length = (first & 0x1F) + 1;
int count = (first & 0x60) >>> 5;
for (int i = 0; i < count; i++) {
length += in.read() << (i << 3) + 5;
}
}
byte[] buffer = new byte[length];
in.read(buffer, 0, length);
return buffer;
} |
41f3b2cc-cb85-4758-b967-945442068e8a | 3 | protected void cellsResized(Object[] cells)
{
if (cells != null)
{
mxIGraphModel model = getGraph().getModel();
model.beginUpdate();
try
{
for (int i = 0; i < cells.length; i++)
{
if (!isCellIgnored(cells[i]))
{
cellResized(cells[i]);
break;
}
}
}
finally
{
model.endUpdate();
}
}
} |
1cbc958d-939d-450b-a36f-24b1e9ee9226 | 1 | public static double processFancyHouse(FancyHouse fancyHouse) {
long timeStart = System.currentTimeMillis();
while (!fancyHouse.canBeLifted()) {
//Random balloon with diameter 20..30 cm and fullness 80..100%
Balloon b = Balloon.getRandomBalloon(0.10, 0.15, 0.8, 1.0);
fancyHouse.addBalloon(b);
}
long timeFinish = System.currentTimeMillis();
long execTime = timeFinish - timeStart;
return execTime;
} |
9cb0cd20-2217-439d-8db4-79e4a542b230 | 9 | @Override
public boolean getDados() {
preenchido = true;
String msg =bundle.getString("Os Campos: ");
nome = txtNome.getText();
localizacao = txtLocalizacao.getText();
desc = txtaDesc.getText();
descIng = txtaDescIng.getText();
qtQuartos = (int) spNQuartos.getValue();
precoMedio = (double) spPrecoMedio.getValue();
if (precoMedio <= 0) {
preenchido = false;
msg +=bundle.getString("PrecoMedio")+ ", ";
}
if (nome.isEmpty()) {
preenchido = false;
msg +=bundle.getString("Nome")+ ", ";
lblNomeAV.setVisible(true);
}
if (localizacao.isEmpty()) {
preenchido = false;
msg +=bundle.getString("Localizacao")+ ", ";
lblLocalizacaoAV.setVisible(true);
}
if (desc.isEmpty()) {
preenchido = false;
msg +=bundle.getString("Descricao")+", ";
lblDescAV.setVisible(true);
}
if (descIng.isEmpty()) {
preenchido = false;
msg +=bundle.getString("Descrição em Ingles")+ ", ";
lblDescAV.setVisible(true);
}
if (qtQuartos <= 0) {
preenchido = false;
msg +=bundle.getString("NQuartos")+ " , ";
}
try {
nEstrelas = Integer.parseInt(jCEstrelas.getSelectedItem().toString());
} catch (NumberFormatException e) {
nEstrelas = 0;
}
if (nEstrelas == 0) {
preenchido = false;
msg += bundle.getString("Numero de Estrelas")+", ";
}
if (!preenchido) {
Sound erro = new Sound("/som/error.wav");
erro.play();//som erro
msg +=bundle.getString("estão mal preenchidos");
JOptionPane.showMessageDialog(null, msg,bundle.getString("Campos mal Inseridos"), JOptionPane.ERROR_MESSAGE);
}
return preenchido;
} |
b89c98b2-5d50-41e6-8ef3-c5576bbd83d6 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final List<Ability> offensiveAffects=returnOffensiveAffects(target);
if((success)&&(offensiveAffects.size()>0))
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_OK_VISUAL,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
if((!CMLib.flags().isStillAffectedBy(target,offensiveAffects,false))&&(target.location()!=null))
target.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> feel(s) better now."));
}
}
// return whether it worked
return success;
} |
afd29279-e163-4ec2-adad-5255ebfb4cdc | 8 | public Set<Map.Entry<Long,Byte>> entrySet() {
return new AbstractSet<Map.Entry<Long,Byte>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TLongByteMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TLongByteMapDecorator.this.containsKey(k)
&& TLongByteMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Long,Byte>> iterator() {
return new Iterator<Map.Entry<Long,Byte>>() {
private final TLongByteIterator it = _map.iterator();
public Map.Entry<Long,Byte> next() {
it.advance();
long ik = it.key();
final Long key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
byte iv = it.value();
final Byte v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Long,Byte>() {
private Byte val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Long getKey() {
return key;
}
public Byte getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Byte setValue( Byte value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Long,Byte> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Long key = ( ( Map.Entry<Long,Byte> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Long, Byte>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TLongByteMapDecorator.this.clear();
}
};
} |
ba760717-f20c-441e-83f6-28ef988e5353 | 0 | @XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "CanonicalizationMethod")
public JAXBElement<CanonicalizationMethodType> createCanonicalizationMethod(CanonicalizationMethodType value) {
return new JAXBElement<CanonicalizationMethodType>(_CanonicalizationMethod_QNAME, CanonicalizationMethodType.class, null, value);
} |
e41dd457-3c25-4792-b522-0c59f5db5bbd | 7 | public final TLParser.equExpr_return equExpr() throws RecognitionException {
TLParser.equExpr_return retval = new TLParser.equExpr_return();
retval.start = input.LT(1);
Object root_0 = null;
Token set115=null;
TLParser.relExpr_return relExpr114 = null;
TLParser.relExpr_return relExpr116 = null;
Object set115_tree=null;
try {
// src/grammar/TL.g:151:3: ( relExpr ( ( '==' | '!=' ) relExpr )* )
// src/grammar/TL.g:151:6: relExpr ( ( '==' | '!=' ) relExpr )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_relExpr_in_equExpr1064);
relExpr114=relExpr();
state._fsp--;
adaptor.addChild(root_0, relExpr114.getTree());
// src/grammar/TL.g:151:14: ( ( '==' | '!=' ) relExpr )*
loop21:
do {
int alt21=2;
int LA21_0 = input.LA(1);
if ( ((LA21_0>=Equals && LA21_0<=NEquals)) ) {
alt21=1;
}
switch (alt21) {
case 1 :
// src/grammar/TL.g:151:15: ( '==' | '!=' ) relExpr
{
set115=(Token)input.LT(1);
set115=(Token)input.LT(1);
if ( (input.LA(1)>=Equals && input.LA(1)<=NEquals) ) {
input.consume();
root_0 = (Object)adaptor.becomeRoot((Object)adaptor.create(set115), root_0);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_relExpr_in_equExpr1076);
relExpr116=relExpr();
state._fsp--;
adaptor.addChild(root_0, relExpr116.getTree());
}
break;
default :
break loop21;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} |
4d2409ca-f4fd-4650-8f47-6bbba11a7d7d | 9 | public void gererTour()
{
// Temps max pour test
this.J1.setTempsEcoule(10);
this.J2.setTempsEcoule(10);
boolean fini = false;
while(!fini)
{
if(this.getTour()%2 == 1 && this.J2.getTempsEcoule() != 0)
{
while(!defilerTemps(this.J1))
{
defilerTemps(this.J1);
}
}
if(this.getTour()%2 == 0 && this.J1.getTempsEcoule() != 0)
{
while(!defilerTemps(this.J2))
{
defilerTemps(this.J2);
}
}
if(this.J1.getTempsEcoule() == 0 || this.J2.getTempsEcoule() == 0)
{
fini = true;
}
}
} |
8fe7ee10-591b-4d47-a150-773291a299ae | 6 | public static boolean isPalindrome(String str) {
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
char a = str.charAt(i);
char b = str.charAt(j);
if (!(Character.isLowerCase(a) || Character.isUpperCase(a))) {
j++;
continue;
}
if (!(Character.isLowerCase(b) || Character.isUpperCase(b))) {
i--;
continue;
}
String aStr = "" + a;
String bStr = "" + b;
if (!aStr.equalsIgnoreCase(bStr))
return false;
}
return true;
} |
db8ec875-ac3c-49ac-b8a2-a31536d40d61 | 0 | @Override
public void documentAdded(DocumentRepositoryEvent e) {} |
3df429f6-c4aa-4ed5-9fe8-8195bb7573f8 | 9 | private int updateCellCount(int cellValue, int count) {
if (count == 0) {
if (cellValue == 1) {
return -1;
}
if (cellValue == 2) {
return 1;
}
} else {
if (count < 0) {
if (cellValue == 1) {
return count - 1;
}
if (cellValue == 2) {
return 1;
}
}
if (count > 0) {
if (cellValue == 1) {
return -1;
}
if (cellValue == 2) {
return count + 1;
}
}
}
return 0;
} |
b91ad5a1-c1e4-4779-a764-df8b71eef537 | 2 | @Override
public void valueChanged(ListSelectionEvent selEvt) {
// TODO Auto-generated method stub
if (selEvt.getValueIsAdjusting())
return;
if (selEvt.getSource().equals(riverList))
refreshEditData ();
} |
3579debf-3915-4812-b838-f9497d426a9a | 4 | private static double getJaccardBtw2User(User u1, User u2){
double same = 0.0;
for (Business business1 : u1.businesses){
for (Business business2 : u2.businesses){
if(business1.id.equals(business2.id)){
double star1 = ubStar.get(u1.u_id + ";" + business1.id);
double star2 = ubStar.get(u2.u_id + ";" + business2.id);
if (Math.abs(star1 - star2) <= DELTA){
same += 1;
}
}
}
}
int total = u1.businesses.size() + u2.businesses.size();
return same/total;
} |
086c7bce-d87e-4c99-8941-f22578015a3b | 4 | private Node sumExpression() {
// term ((PLUS^|MINUS^) term)*
Node termExpression = term();
while (lookAhead(1) == TokenType.PLUS ||
lookAhead(1) == TokenType.MINUS) {
if (lookAhead(1) == TokenType.PLUS) {
termExpression = new AddOpNode(match(TokenType.PLUS).getPosition(),
termExpression, term());
} else if (lookAhead(1) == TokenType.MINUS) {
termExpression = new SubtractOpNode(match(TokenType.MINUS).getPosition(),
termExpression, term());
}
}
return termExpression;
} |
54496875-0dd6-44d0-b824-9487971e5076 | 8 | @Override
protected void onJoin(final String channel, final String sender,
final String login, final String hostname) {
if (sender.equals(getNick())) {
if (trustNickServ && (nickPass != null) && !loggedIn) {
attemptIdentify();
}
sendMessage(getIntendedChannel(), "Initialized - " + getVersion());
if (welcomeMsg != null && !welcomeMsg.equalsIgnoreCase("")) {
sendMessage(getIntendedChannel(), welcomeMsg);
}
}
for (final Module m : enabledModules.values()) {
if (m.onJoin(channel, sender, login, hostname)) {
break;
}
}
} |
834669b6-5a81-4042-831b-294c7bf1ea7d | 7 | protected void fitLogistic(Instances insts, int cl1, int cl2,
int numFolds, Random random)
throws Exception {
// Create header of instances object
FastVector atts = new FastVector(2);
atts.addElement(new Attribute("pred"));
FastVector attVals = new FastVector(2);
attVals.addElement(insts.classAttribute().value(cl1));
attVals.addElement(insts.classAttribute().value(cl2));
atts.addElement(new Attribute("class", attVals));
Instances data = new Instances("data", atts, insts.numInstances());
data.setClassIndex(1);
// Collect data for fitting the logistic model
if (numFolds <= 0) {
// Use training data
for (int j = 0; j < insts.numInstances(); j++) {
Instance inst = insts.instance(j);
double[] vals = new double[2];
vals[0] = SVMOutput(-1, inst);
if (inst.classValue() == cl2) {
vals[1] = 1;
}
data.add(new DenseInstance(inst.weight(), vals));
}
} else {
// Check whether number of folds too large
if (numFolds > insts.numInstances()) {
numFolds = insts.numInstances();
}
// Make copy of instances because we will shuffle them around
insts = new Instances(insts);
// Perform three-fold cross-validation to collect
// unbiased predictions
insts.randomize(random);
insts.stratify(numFolds);
for (int i = 0; i < numFolds; i++) {
Instances train = insts.trainCV(numFolds, i, random);
/* SerializedObject so = new SerializedObject(this);
BinarySMO smo = (BinarySMO)so.getObject(); */
BinarySMO smo = new BinarySMO();
smo.setKernel(Kernel.makeCopy(SMO.this.m_kernel));
smo.buildClassifier(train, cl1, cl2, false, -1, -1);
Instances test = insts.testCV(numFolds, i);
for (int j = 0; j < test.numInstances(); j++) {
double[] vals = new double[2];
vals[0] = smo.SVMOutput(-1, test.instance(j));
if (test.instance(j).classValue() == cl2) {
vals[1] = 1;
}
data.add(new DenseInstance(test.instance(j).weight(), vals));
}
}
}
// Build logistic regression model
m_logistic = new Logistic();
m_logistic.buildClassifier(data);
} |
133ad62a-164f-44ce-b12f-b7b04166343c | 9 | public int removeDuplicates(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if (A == null)
return 0;
if (A.length < 3)
return A.length;
int i = -1, tag = 0, count = 1, cur = 1;
while (cur < A.length) {
if (A[cur] == A[tag])
count++;
else {
A[++i] = A[tag];
if (count > 1)
A[++i] = A[tag + 1];
count = 1;
tag = cur;
}
if (count == 3) {
A[++i] = A[tag];
A[++i] = A[tag + 1];
while (cur < A.length && A[cur] == A[tag])
cur++;
tag = cur;
count = 1;
}
cur++;
}
while (tag < A.length)
A[++i] = A[tag++];
return (i + 1);
} |
8e215f66-73ba-4c82-bb40-01bc2729ea38 | 6 | public void mDisplayLCS()
{
System.out.println("Length of Longest Common Sequence is "+
length[seq1.length-1][seq2.length-1]);
LinkedList<Integer> list = new LinkedList<Integer>();
int row = seq1.length-1, col = seq2.length - 1, temp = -1, index = -1;
while ((row != 0) && (col != 0)) {
if ((seq1[row] == seq2[col]) && (length[row][col] == (length[row-1][col-1]+1))) {
list.addFirst(seq1[row]);
row--;
col--;
} else if (length[row][col] == length[row-1][col]) {
row--;
} else {
col--;
}
}
Integer i = list.poll();
while (i != null) {
System.out.print(i);
i = list.poll();
}
System.out.println();
} |
75a127db-affe-4174-a9b0-3c50bd14d264 | 6 | private void renderStats(GUIContext container, Graphics g) {
g.setColor(new Color(0, 0, 0, 0.4f));
g.fillRoundRect(430, 20, 280, 160, 15);
g.setColor(Color.black);
g.drawRoundRect(430, 20, 280, 160, 15);
g.setColor(Color.white);
g.setFont(bigFont);
if (wavesHaveBegun) {
g.drawString("Wave " + (waveIndex + 1), 470, 30);
}
g.setFont(NORMAL_FONT);
if (wavesHaveBegun) {
if (!waveHasMoreSpawns && !isFinalWave) {
String extraString = waveIsCleared ? " press s to skip" : "";
g.drawString("(" + secondsUntilNextWave + ")" + extraString, 470, 70);
}
} else {
g.drawString("First wave in " + secondsUntilNextWave + "s.", 470, 48);
g.drawString("press s to start", 470, 70);
}
if (!isHeroDead) {
g.drawString("HERO:", 470, 100);
} else {
g.drawString("REVIVAL IN " + (int)(timeUntilHeroResurrection / 1000.0) + " s", 470, 100);
}
RenderUtil.renderStatBar(g, new Point(470, 120), new Dimension(200, 8), Color.black, new Color(170,0,0), heroPartHealth, 2);
RenderUtil.renderStatBar(g, new Point(470, 130), new Dimension(200, 8), Color.black, new Color(0,0,170), heroPartMana, 2);
g.setColor(Color.white);
g.drawString("BASE:", 470, 140);
RenderUtil.renderStatBar(g, new Point(470, 160), new Dimension(200, 8), Color.black, new Color(170,0,0), life / (double) maxLife, 2);
g.setColor(Color.white);
g.setFont(NORMAL_FONT);
int heroStatsX = 545;
g.drawString("Life: " + life + " / " + maxLife, heroStatsX, 955);
g.drawString("Money: " + money, heroStatsX, 975);
g.drawString("Max health: " + maxHealth, heroStatsX, 1005);
g.drawString("Max mana: " + maxMana, heroStatsX, 1025);
DecimalFormat df = new DecimalFormat("#.##");
g.drawString("Armor: " + df.format(armor), heroStatsX, 1045);
g.drawString("Movement speed: " + movementSpeed, heroStatsX, 1065);
g.drawString("x dmg: " + df.format(damageMultiplier), heroStatsX, 1085);
g.drawString("Unspent points: " + numAvailableStatpoints, heroStatsX, 1135);
g.setColor(new Color(0.5f, 1f, 0.6f));
g.drawString("" + heroStats.get(HeroStat.STRENGTH), heroStatsX + 4, LOWER_ROW_Y + ICON_WIDTH / 2 - 10);
g.drawString("" + heroStats.get(HeroStat.DEXTERITY), heroStatsX + 4 + ICON_WIDTH + ICON_GAP, LOWER_ROW_Y + ICON_WIDTH / 2 - 10);
g.drawString("" + heroStats.get(HeroStat.INTELLIGENCE), heroStatsX + 4 + 2 * (ICON_WIDTH + ICON_GAP), LOWER_ROW_Y + ICON_WIDTH / 2 - 10);
} |
531b27d0-be0e-45eb-9538-10a568d26f49 | 1 | private boolean jj_2_43(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_43(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(42, xla); }
} |
904b188d-05da-4c77-887f-5af2da8fe189 | 3 | public static Client getClientById(long id) {
Client ClientHolder = null;
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
ClientHolder = (Client) session.get(Client.class, id);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return ClientHolder;
} |
6fc71edf-3431-4850-9ea7-58b26bbd9bb1 | 4 | public void menuItemUpdate() {
save_to_file.setSelected(theApp.getLogging());
CROWD36_item.setSelected(theApp.isCROWD36());
XPA_10_item.setSelected(theApp.isXPA_10());
XPA_20_item.setSelected(theApp.isXPA_20());
XPA2_item.setSelected(theApp.isXPA2());
CIS3650_item.setSelected(theApp.isCIS3650());
CCIR493_item.setSelected(theApp.isCCIR493());
GW_item.setSelected(theApp.isGW());
experimental_item.setSelected(theApp.isExperimental());
FSK_item.setSelected(theApp.isFSK());
FSK200500_item.setSelected(theApp.isFSK200500());
FSK2001000_item.setSelected(theApp.isFSK2001000());
debug_item.setSelected(theApp.isDebug());
soundcard_item.setSelected(theApp.isSoundCardInput());
invert_item.setSelected(theApp.isInvertSignal());
bitstream_item.setSelected(theApp.isBitStreamOut());
freeChannelMarkerGW_item.setSelected(theApp.isViewGWChannelMarkers());
DisplayBad_item.setSelected(theApp.isDisplayBadPackets());
DisplayUTC_item.setSelected(theApp.isLogInUTC());
RTTY_item.setSelected(theApp.isRTTY());
// Triggers
List<Trigger> trigList=theApp.getListTriggers();
int a;
for (a=0;a<trigList.size();a++) {
trigger_items.get(a).setSelected(trigList.get(a).isActive());
}
// Audio sources
MenuElement[] devs=audioDevicesMenu.getSubElements();
if (devs.length>0){
for (MenuElement m : devs[0].getSubElements()){
if (((JRadioButtonMenuItem)m).getText().equals(theApp.inputThread.getMixerName())){
((JRadioButtonMenuItem)m).setSelected(true);
break;
}
}
}
} |
0bd831c6-56c4-482c-93cb-47a2bf327087 | 5 | public static List<String> compareAll(Object o1, Object o2) throws Exception {
final List<String> diffs = new ArrayList<String>();
if (o1.getClass() != o2.getClass()) {
fail("Can't compare different classes");
}
final Field[] fields = o1.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true); // yes, we compare private fields
Object f1 = f.get(o1);
Object f2 = f.get(o2);
if ((f1 == null) != (f2 == null)) { // only one is null => different
diffs.add(String.format("%s(%s,%s)", f.getName(), f1, f2));
continue;
}
if (f1 == null) // both are null => same
continue;
if (!f1.equals(f2)) {
diffs.add(String.format("%s(%s,%s)", f.getName(), f1, f2));
}
}
return diffs;
} |
94ff9133-2c71-4bb0-a7c9-29711c026b2f | 9 | private Value getValueForType(Body body, LocalGenerator gen,
Type tp, Set<SootClass> constructionStack, Set<SootClass> parentClasses) {
// Depending on the parameter type, we try to find a suitable
// concrete substitution
if (isSimpleType(tp.toString()))
return getSimpleDefaultValue(tp.toString());
else if (tp instanceof RefType) {
SootClass classToType = ((RefType) tp).getSootClass();
if(classToType != null){
// If we have a parent class compatible with this type, we use
// it before we check any other option
for (SootClass parent : parentClasses)
if (isCompatible(parent, classToType)) {
Value val = this.localVarsForClasses.get(parent.getName());
if (val != null)
return val;
}
// Create a new instance to plug in here
Value val = generateClassConstructor(classToType, body, constructionStack, parentClasses);
// If we cannot create a parameter, we try a null reference.
// Better than not creating the whole invocation...
if(val == null)
return NullConstant.v();
return val;
}
}
else if (tp instanceof ArrayType) {
Value arrVal = buildArrayOfType(body, gen, (ArrayType) tp, constructionStack, parentClasses);
if (arrVal == null){
logger.warn("Array parameter substituted by null");
return NullConstant.v();
}
return arrVal;
}
else {
logger.warn("Unsupported parameter type: {}", tp.toString());
return null;
}
throw new RuntimeException("Should never see me");
} |
7753b55c-0074-463a-97a6-0a3bcd265bfa | 8 | public String eval(final String messageTemplate, final Object problem)
{
try
{
final StringBuilder results = new StringBuilder(
messageTemplate.length());
int state = STATE_OUT_OF_EXPRESSION;
int expStartIndex = 0;
/*
* So you may have guessed that writing compilers is not my strong
* suit. Okay so this isn't exactly the fastest or most attractive
* code in the world, but it solved the problem in a hurry and
* didn't require much of a state machine. If you think my code
* sucks, at least I got it working in 30 minutes. If you think you
* can do better please send me a patch.
*/
for (int i = 0, length = messageTemplate.length(); i < length; ++i)
{
final char current = messageTemplate.charAt(i);
char nextChar = 0x0000;
if (i + 1 < length)
{
nextChar = messageTemplate.charAt(i + 1);
}
switch (state)
{
case STATE_IN_EXPRESSION:
if (nextChar == '}')
{
final String found = messageTemplate.substring(
expStartIndex, ++i);
final Object result = evaluate(problem, found);
results.append(result);
state = STATE_OUT_OF_EXPRESSION;
}
break;
default:
// Start expression
if (current == '$' && nextChar == '{')
{
// skip $ and {
++i;
expStartIndex = ++i;
state = STATE_IN_EXPRESSION;
}
else
{
results.append(current);
}
break;
}
}
/*
* append the entire escape just incase they left it open, so
* ${problem.value gets printed in the results if there is no
* closing brace;
*/
if (state == STATE_IN_EXPRESSION)
{
final String openExpression = messageTemplate.substring(
expStartIndex - 2, messageTemplate.length());
throw new InterpolationException(openExpression);
}
return results.toString();
}
catch (final Throwable t)
{
throw new InterpolationException(t);
}
} |
9c9e3d4a-f6c6-4110-8c50-1e369fe3672d | 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(NewAppDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(NewAppDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(NewAppDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(NewAppDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
NewAppDialog dialog = new NewAppDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing(java.awt.event.WindowEvent e)
{
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
d7a25b81-3df9-4de2-b195-819a8087fbf6 | 3 | private boolean isInBounds(int cy, int cx) {
return cx >= 0 && cy >= 0 && cx < BOARD_SIZE && cy < BOARD_SIZE;
} |
eb0c154c-4d16-4f1f-a6c5-5e927e0c1261 | 3 | public boolean containsBadStates() {
for (Entry<Integer, HashSet<HashSet<Integer>>> entryOfTable : FiniteTreesTable.entrySet()) {
for (HashSet<Integer> tree : entryOfTable.getValue()) {
if (!FiniteTreesTable.keySet().containsAll(tree))
return true;
}
}
return false;
} |
4961a672-d6dc-406f-964d-1e3d8e886d13 | 1 | private void addToList(List<Ball>[] array, int i, Ball b) {
if (array[i] == null) {
LinkedList<Ball> t = new LinkedList<Ball>();
t.add(b);
array[i] = t;
} else {
array[i].add(b);
}
} |
7e56d54d-751a-4b5c-84c7-d814a9f69259 | 7 | private void btonrepoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btonrepoActionPerformed
switch (tabla.getSelectedRow()) {
case 0:
setClientView(false);
jDialog1.setSize(220, 184);
jDialog1.setLocationRelativeTo(this);
jDialog1.setVisible(true);
break;
case 1:
setClientView(true);
jComboBox1.removeAllItems();
jDialog1.setSize(230, 200);
jDialog1.setLocationRelativeTo(this);
ClienteController cc = new ClienteController('U');
try {
lc = cc.listCliente();
} catch (SQLException ex) {
Logger.getLogger(reporte.class.getName()).log(Level.SEVERE, null, ex);
}
for (Cliente cliente : lc) {
jComboBox1.addItem(cliente.getCodigo() + " | " + cliente.getCedula());
}
jDialog1.setVisible(true);
break;
case 2:
print(getClass().getResource("/reporte/ListadoEquiposPendientes.jasper"));
break;
case 3:
print(getClass().getResource("/reporte/ListadoEquiposReparados.jasper"));
break;
case 4:
print(getClass().getResource("/reporte/ListadoEquipos.jasper"));
break;
default:
JOptionPane.showMessageDialog(this, " Elija una fila de Lista ", "A T E N C I O N", JOptionPane.PLAIN_MESSAGE);
}
}//GEN-LAST:event_btonrepoActionPerformed |
26a58efa-c791-4cc8-9080-5ac9f3b09eae | 2 | public Deck() {
// generate the 52 cards and shuffle them
for (int i = 0; i < Card.SUITS.length; i++) {
for (int j = 0; j < Card.CARD_TYPES.length; j++) {
Card card = new Card(Card.CARD_TYPES[j], Card.SUITS[i]);
cardDeck.add(card);
}
}
shuffleDeck();
} |
7553a492-12e6-43fa-a599-428ddfa2be80 | 7 | void replaceChild (Node oldChild, Node newChild)
{
if (_occurs_ == oldChild)
{
setOccurs ((TOccurs) newChild);
return;
}
if (_occursTo_ == oldChild)
{
setOccursTo ((POccursTo) newChild);
return;
}
if (_number_ == oldChild)
{
setNumber ((PNumber) newChild);
return;
}
if (_times_ == oldChild)
{
setTimes ((TTimes) newChild);
return;
}
if (_depending_ == oldChild)
{
setDepending ((TDepending) newChild);
return;
}
if (_on_ == oldChild)
{
setOn ((TOn) newChild);
return;
}
if (_dataName_ == oldChild)
{
setDataName ((TDataName) newChild);
return;
}
} |
f4896850-6b2e-42bb-99bf-c25841984aaf | 1 | @Override
public double cumulativeProbability(double x) {
if (x >= this.point) return 1.0;
else return 0.0;
} |
99f565c1-140b-4dac-9f3d-6c6fe7a1e871 | 9 | private String fixBadChars(String s) {
if (s == null || s.length() == 0) return s;
Pattern p = Pattern.compile("[<>\"&]");
Matcher m = p.matcher(s);
StringBuffer b = null;
while (m.find()) {
if (b == null) b = new StringBuffer();
switch (s.charAt(m.start())) {
case '<': m.appendReplacement(b,"<");
break;
case '>': m.appendReplacement(b,">");
break;
case '&': m.appendReplacement(b,"&");
break;
case '"': m.appendReplacement(b,""");
break;
default: m.appendReplacement(b,"&#"+((int)s.charAt(m.start()))+';');
}
}
if (b == null) return s;
m.appendTail(b);
return b.toString();
} |
ebb0dd41-ff96-4aeb-8a5d-1242352e81e3 | 7 | public ChangesStatus withdrawMoney(int account_id, int customer_id_by,
int amount, int pin) throws BelowMinimumBalanceException {
Connection connection = DBConnectionHelper.getConnection();
AccountDAO accountDAO = DAOFactory.getAccountDAO();
try {
Account account = accountDAO.getObject(connection, account_id);
// Checking Security Pin
if (!(account.getPin() == pin)) {
return new ChangesStatus(false,
"Security Pin do not match! Transaction Canceled.");
}
// Checking Permission
if (!(PermissionHelper.isThisAccountOwnByThisCustomer(account_id,
customer_id_by))) {
return new ChangesStatus(false,
"You do not own this account. Transaction Canceled.");
}
double newAmount = account.getAmount() - amount;
if (newAmount < BusinessRules.SAVING_ACCOUNT_MIN_BALANCE_AMOUNT) {
throw new BelowMinimumBalanceException(
"Below Minimum Balance to be left");
}
account.setAmount(newAmount);
accountDAO.save(connection, account);
Transaction transaction = new Transaction();
transaction.setCustomer_id_by(customer_id_by);
transaction.setAccount_id(account_id);
transaction.setTransaction_amount(amount);
transaction.setTransaction_type(2);
Date date = new Date();
transaction.setTransaction_time(new Timestamp(date.getTime()));
TransactionDAO transactionDAO = DAOFactory.getTransactionDAO();
transactionDAO.create(connection, transaction);
// If exception found roll back in catch block
connection.commit();
return new ChangesStatus(true, "Successfully Withdrawed" + amount);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
try {
connection.rollback();
e.printStackTrace();
return new ChangesStatus(false,
"Transaction Rolledbacked. Unsuccessful.");
} catch (SQLException e1) {
e1.printStackTrace();
return new ChangesStatus(false, "Unsuccessful Rolledback.");
}
} finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
} |
7643d69d-f4c9-4212-80d9-aac23b4053cd | 9 | public Agent(InfluenceMatrix inf,
ArrayList<HashSet<Integer>> iterationPlan, int processingPower,
String type, int totalNum, double constraint, boolean isAveraging,
boolean isExhaustive
/*
* , boolean isRefactoringAll
*/) {
// check for valid iteration plan
boolean flagArray[] = new boolean[inf.getN()];
for (HashSet<Integer> iteration : iterationPlan) {
for (int element : iteration) {
// if (!flagArray[element]) {
flagArray[element] = true;
// }
// else {
// System.out
// .println("ERROR invalid iteration plan : duplicated element "
// + element);
// System.exit(1);
// }
}
}
ArrayList<Integer> missingSet = new ArrayList<Integer>();
for (int i = 0; i < flagArray.length; i++) {
if (!flagArray[i]) {
missingSet.add(i);
}
}
if (!missingSet.isEmpty()) {
System.out
.println("ERROR invalid iteration plan : missing element(s) "
+ missingSet.toString());
System.exit(1);
}
// check for valid processing power
if (processingPower <= 0) {
System.out
.println("ERROR processing power should be positive, given "
+ processingPower);
System.exit(1);
}
// check for valid constraint
if (constraint <= 0) {
System.out
.println("ERROR constraint value should be positive, given "
+ constraint);
System.exit(1);
}
if (constraint > 1) {
System.out
.println("ERROR constraint value should be less than 1, given "
+ constraint);
System.exit(1);
}
// assign private fields
this.myType = type;
this.myTotalNum = totalNum;
this.myNum = 0;
this.myInf = inf;
this.myIterationPlan = iterationPlan;
this.myProcessingPower = processingPower;
// set initial location id randomly
this.myLocId = -1;
this.myCurrentIterationNum = 0;
this.myImplementedElements = new HashSet<Integer>();
this.myUnimplementedElements = new HashSet<Integer>();
for (int i = 0; i < myInf.getN(); i++) {
this.myUnimplementedElements.add(i);
}
this.myContraint = constraint;
this.myIsAveraging = isAveraging;
this.myIsExhaustive = isExhaustive;
// this.myIsRefactoringAll = isRefactoringAll;
} |
7c106ce3-01ce-4d79-867b-c2e483fd2549 | 3 | public void setFlowBlock(FlowBlock flowBlock) {
if (this.flowBlock != flowBlock) {
this.flowBlock = flowBlock;
StructuredBlock[] subs = getSubBlocks();
for (int i = 0; i < subs.length; i++) {
if (subs[i] != null)
subs[i].setFlowBlock(flowBlock);
}
}
} |
927d3074-b24b-45d7-a379-bc1099fbf916 | 2 | public static double logNormalThreeParPDF(double alpha, double beta, double gamma, double x) {
if (beta < 0) throw new IllegalArgumentException("The parameter beta, " + beta + ", must be greater than or equal to zero");
if (x <= alpha) {
return 0.0D;
} else {
return Math.exp(-0.5D * Fmath.square(Math.log((x - alpha) / gamma) / beta)) / ((x - gamma) * beta * Math.sqrt(2.0D * Math.PI));
}
} |
b32dec2d-93e4-4261-a9cc-9814da5a705b | 5 | private Map<String, String> parseVariablesForUri(final URI uri, final String[] routePaths) {
Map<String, String> routeParams = null;
Map<String, String> variables = new HashMap<String, String>();
String[] inputPaths = URIUtils.getPathSegments(uri);
boolean isComponentCountEqual = routePaths.length == inputPaths.length;
if (isComponentCountEqual) {
boolean isMatch = true;
int routePathsSize = routePaths.length;
for (int i = 0 ; i < routePathsSize ; i ++) {
if (routePaths[i].startsWith(":")) {
variables.put(routePaths[i].substring(1), inputPaths[i]);
} else if (!routePaths[i].equals(inputPaths[i])) {
isMatch = false;
break;
}
}
if (isMatch) {
routeParams = variables;
}
}
return routeParams;
} |
f83d92b8-aebe-45e2-bb01-4f8a97f21ce0 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof HabitatCategory)) {
return false;
}
HabitatCategory other = (HabitatCategory) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
73a80871-bf16-459a-bc89-241df8d1bcbc | 6 | public static void save() throws IOException {
// Scanner scan = new Scanner(System.in);
File input = new File("src/" + ACC + ".txt");
try {
Scanner scan = new Scanner(input);
String table = "";
while (scan.hasNextLine()) {
String temp = scan.nextLine();
String[] t = temp.split(",");
if (t[0].equals(DATA[0])) {
if (ACC.equalsIgnoreCase("provider")) {
temp = P.toWrite();
} else {
temp = M.write();
}
}
table += temp;
// if(DATA[6].equalsIgnoreCase("p")) table+=",p";
table += "\n";
}
try {
OutputStream output = new FileOutputStream("src/" + ACC
+ ".txt");
PrintStream printOut = new PrintStream(output);
printOut.print(table);
System.setOut(printOut);
System.out.flush();
printOut.close();
output.close();
output = new FileOutputStream("src/transaction.txt");
printOut = new PrintStream(output);
String toWrite = "";
for (String[] a : Atlantic) {
Transaction temp = new Transaction(a);
toWrite+=temp.toWrite() + "\n";
}
printOut.print(toWrite);
printOut.close();
output.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to update Database.");
}
} catch (FileNotFoundException e) {
System.out.println("Failed to read Database.");
}
} |
5a62f872-d576-4eba-ad72-b09892ff6797 | 2 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onEntityTarget(EntityTargetEvent event) {
Entity target = event.getTarget();
if (target instanceof Player) {
xAuthPlayer xp = plyrMngr.getPlayer(((Player) target).getName());
if (plyrMngr.isRestricted(xp, event))
event.setCancelled(true);
}
} |
42d848b6-fd0a-4edd-9025-ac650617fcee | 0 | public void setHeight(Double height) {
this.height = height;
} |
d67043db-e9a4-4bcd-8d1b-d1be6bbc07b3 | 3 | @Override
public void updateUser(User user) throws SQLException {
Session session=null;
try{
session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null && session.isOpen())
session.close();
}
} |
b8ccc406-6958-4035-a6c4-f1829296ce6f | 8 | public void desplazar(Vector3f distancia) {
Transform3D nueva = MiLibreria3D.trasladarDinamico(distancia);
Transform3D actual = new Transform3D();
tgPersonaje.getTransform(actual);
actual.mul(nueva);
tgPersonaje.setTransform(actual);
float diagonal = distancia.getY() * ESCALA;
if (direccion.equals(Direccion.adDer)) {
posicionActual.setX(posicionActual.getX() + MiLibreria3D.pitagorasIsosceles(diagonal));
posicionActual.setZ(posicionActual.getZ() - MiLibreria3D.pitagorasIsosceles(diagonal));
} else if (direccion.equals(Direccion.adIzq)) {
posicionActual.setX(posicionActual.getX() - MiLibreria3D.pitagorasIsosceles(diagonal));
posicionActual.setZ(posicionActual.getZ() - MiLibreria3D.pitagorasIsosceles(diagonal));
} else if (direccion.equals(Direccion.atDer)) {
posicionActual.setX(posicionActual.getX() + MiLibreria3D.pitagorasIsosceles(diagonal));
posicionActual.setZ(posicionActual.getZ() + MiLibreria3D.pitagorasIsosceles(diagonal));
} else if (direccion.equals(Direccion.atIzq)) {
posicionActual.setX(posicionActual.getX() - MiLibreria3D.pitagorasIsosceles(diagonal));
posicionActual.setZ(posicionActual.getZ() + MiLibreria3D.pitagorasIsosceles(diagonal));
} else if (direccion.equals(Direccion.adelante)) {
posicionActual.setZ(posicionActual.getZ() - distancia.getY() * ESCALA);
} else if (direccion.equals(Direccion.atras)) {
posicionActual.setZ(posicionActual.getZ() + distancia.getY() * ESCALA);
} else if (direccion.equals(Direccion.izquierda)) {
posicionActual.setX(posicionActual.getX() - distancia.getY() * ESCALA);
} else if (direccion.equals(Direccion.derecha)) {
posicionActual.setX(posicionActual.getX() + distancia.getY() * ESCALA);
}
actualizarDireccion();
} |
6279bfab-a94a-4e29-88d5-768c31a8f5d8 | 1 | private void checkFromNode()
{
Edge edgeFrom = addressFinder.searchForEdge(from.getText());
if (edgeFrom != null)
{
fromNode = edgeFrom.getFromNode();
from.setText(edgeFrom.getRoadName());
mapComponent.setFrom(true);
mapComponent.setFromNode(fromNode);
mapComponent.repaint();
reset.setEnabled(true);
runRouteCalculation();
} else
{
from.setText(null);
from.setPlaceholder("Street not found");
fromNode = null;
mapComponent.setFrom(false);
mapComponent.setFromNode(null);
printRoute.setEnabled(false);
mapComponent.setRouteNodes(null);
}
mapComponent.repaint();
} |
97ada096-1054-4d9c-8127-e932b31eca53 | 5 | final int method1607(int i, int i_0_, byte i_1_) {
anInt2882++;
int i_2_ = ((i ^ 0xffffffff) > (Class321.windowWidth ^ 0xffffffff)
? Class321.windowWidth : i);
if (Class5_Sub1.aClass221_8344 == this)
return 0;
if (i_1_ >= -103)
aBoolean2881 = true;
if (this == Class223.aClass221_2893)
return i_2_ - i_0_;
if (Class104.aClass221_1620 == this)
return (-i_0_ + i_2_) / 2;
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.