id
stringlengths
36
36
text
stringlengths
1
1.25M
eaad39fb-b219-45b4-bc67-74bbb8a53ff9
@POST @Path("/item") @Consumes(MediaType.APPLICATION_JSON) public Integer takeItem(TodoItem tdi);
d231a201-d170-497b-aa1e-6e31b59ad46b
@GET @Path("/item/{id}") @Produces(MediaType.APPLICATION_JSON) public TodoItem getItem(@PathParam("id") int id) throws SomeApplicationException;
49fd4835-e33e-4d0a-9174-1fe555c4d898
protected abstract T produces();
7282960d-033c-43c4-ac5a-2a7da18ba558
protected T getService (Class<T> clazz){ System.out.print("Factory for: " + clazz.getCanonicalName()); URI uri = getUri(clazz.getCanonicalName()); ClientRequestFactory crf = new ClientRequestFactory(UriBuilder.fromUri(uri).build()); registerClientInterceptor(crf); ResteasyProviderFactory pf = ResteasyProviderFactory.getInstance(); registerClientExceptionMapper(pf); return crf.createProxy(clazz); }
a59e6c18-8ff4-4346-98ee-eafe5ae9ed9b
private URI getUri(String callingInterface){ URI result=null; String key = callingInterface+".url"; // Is URL in system properties defined? result = getUriFromSystem(key); if (result == null) // Is URL in properties file defined? result = getUriFromProperties(key); if (result != null) System.out.println("Looking for Service at: "+result); else System.out.println("No url found"); return result; }
9f38b8bc-c773-4f8f-957c-af8f87231e7b
private URI getUriFromProperties(String key) { URI result=null; InputStream urls = this.getClass().getClassLoader().getResourceAsStream("META-INF/urls.properties"); Properties props = new Properties(); try { props.load(urls); String prop = props.getProperty(key); if (prop != null) result = UriBuilder.fromUri(prop).build(); } catch (IOException ioe) { ioe.printStackTrace(); } return result; }
50ec22b2-4a7e-46a0-a9f5-9761e47bae7c
private URI getUriFromSystem(String key) { URI result=null; String prop = System.getProperty(key); if (prop != null) result = UriBuilder.fromUri(prop).build(); return result; }
87a1aeb7-c8db-474b-a4e9-bd79d3538757
protected void registerClientInterceptor(ClientRequestFactory crf){ }
38c522e7-dea5-4c4e-8f63-5d2e66eed11a
protected void registerClientExceptionMapper(ResteasyProviderFactory pf){ }
a5bae8f5-5ac5-4951-9ae0-41cdc8ee38a3
@Override @Produces protected Service produces() { // TODO Auto-generated method stub return getService(Service.class); }
30c24b55-5ef6-4df2-8f2e-7e0fe08ea5b7
@Override protected void registerClientExceptionMapper(ResteasyProviderFactory pf){ ClientExceptionMapper clientExeptionMapper = new ClientExceptionMapper(); pf.addClientErrorInterceptor(clientExeptionMapper); }
9f3cd46a-5380-43e0-b7c5-6e9ba1581303
public void postProcess(ServerResponse response) { Integer id = (Integer) response.getEntity(); response.setStatus(201); MultivaluedMap<String, Object> headers = response.getMetadata(); String ru = servletRequest.getRequestURL().toString(); if (ru.endsWith("/")) ru += id; else ru += "/"+id; headers.add("Location", ru ); System.out.println("Server PostProcess, created: "+ ru); }
65f5f116-6b34-49f7-b716-b86581708e6b
@SuppressWarnings("rawtypes") public boolean accept(Class declaring, Method method) { return method.isAnnotationPresent(POST.class); }
1c31c1e2-129f-4287-b9c7-c798cdeb801c
public Response toResponse(SomeApplicationException e) { System.out.println("Server ExceptionMapper: Mapped SomeApplicationException to Statuscode 523"); return Response.status(523).build(); }
121920ca-6d0a-4fee-aadb-172bda7415c9
@SuppressWarnings("rawtypes") public void handle(ClientResponse response) throws RuntimeException{ try { BaseClientResponse r = (BaseClientResponse) response; String message = "SomeApplikationException. Status Code: " + response.getStatus(); InputStream stream = r.getStreamFactory().getInputStream(); stream.reset(); if (response.getStatus() == 523){ System.out.println("ClientExceptionmapper: Mapped Stauscode 523 to SomeApplicationException"); throw new SomeApplicationException(message); } } catch (IOException e){ e.printStackTrace(); } }
1e75c9da-7daa-4328-bc6d-24562a310b86
@Deployment public static WebArchive createDeployment(){ WebArchive war = ShrinkWrap.create(WebArchive.class, "local.war") .addAsLibraries(Maven.resolver().resolve("cdr:example-service-impl:1.0-SNAPSHOT").withTransitivity().asFile()) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; }
df32ed58-2a7a-4c7f-85d2-8a3b5e6edcf7
@Test @InSequence(1) public void create (Service service) throws Exception{ TodoItem t = new TodoItem(); t.setDescription("Testitem"); id = service.takeItem(t); Assert.assertNotNull(id); System.out.println("Create item with id: " + id); }
37722323-e0b7-4cbb-95f6-91f1bac6e802
@Test @InSequence(2) public void get () throws Exception{ TodoItem r = service.getItem(id); Assert.assertNotNull(r); System.out.println("Get created item. Has description: " + r.getDescription()); }
7f5744a2-e4f5-4d5d-b639-1e2927c3b965
@Test @InSequence(3) public void exception () throws Exception{ try { TodoItem r = service.getItem(33); System.out.println(r); } catch (SomeApplicationException e) { Assert.assertNotNull(e); System.out.println("Catched Exception: " + e.getMessage()); } }
6ad88124-4836-4b66-948f-aa25353c4626
@Deployment(order=1, name="Server", testable = false) @OverProtocol("Servlet 3.0") public static WebArchive createRemoteDeployment(){ WebArchive war = ShrinkWrap.create(WebArchive.class, "Server.war") .addAsLibraries(Maven.resolver().resolve("cdr:example-service-impl:1.0-SNAPSHOT").withTransitivity().asFile()) .addClasses(Server_Activator.class, ServerPostProcessInterceptor.class, ServerExceptionMapper.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; }
3fac007d-7242-4a96-ba64-b7099b967929
@Deployment(order=2 , name="Client", testable = true) public static WebArchive createLocalDeployment(){ WebArchive war = ShrinkWrap.create(WebArchive.class, "Client.war") .addAsLibraries(Maven.resolver().resolve("cdr:example-service-api:1.0-SNAPSHOT").withTransitivity().asFile()) .addAsLibraries(Maven.resolver().resolve("cdr:cdr-lib:1.0-SNAPSHOT").withTransitivity().asFile()) .addClasses(ClientExceptionMapper.class, ServiceProducer.class,IEndpoint.class, Endpoint.class, Client_Activator.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsResource("META-INF/urls.properties"); return war; }
ed3e9aa2-414e-43a3-a891-79b7ed809475
@BeforeClass @OperateOnDeployment("Client") public static void initResteasyClient() throws MalformedURLException { RegisterBuiltin.register(ResteasyProviderFactory.getInstance()); }
0d67de9c-2d80-4503-9303-b44f16f8e0fd
@Test @OperateOnDeployment("Client") @RunAsClient @InSequence(1) public void create (@ArquillianResource URL url) throws Exception{ client = ProxyFactory.create(IEndpoint.class,url.toString()); id = client.put(); Assert.assertNotNull(id); System.out.println("Create item with id: " + id); }
c551cf69-3739-44f4-b848-275d210b614f
@Test @OperateOnDeployment("Client") @RunAsClient @InSequence(2) public void get () throws Exception { String r = client.get(id); Assert.assertNotNull(r); System.out.println("Get created item. Has description: " + r); }
9bb70ce7-11f0-4a5e-aea8-b5d6195b0d37
@Test @OperateOnDeployment("Client") @RunAsClient @InSequence(3) public void exception () throws Exception{ String r = client.get(42); Assert.assertNotNull(r); System.out.println("Catched Exception: " + r); }
56426fed-77cf-40e5-bd51-59f6be744ab9
@Override public Set<Class<?>> getClasses() { final Set<Class<?>> rootResources = new HashSet<Class<?>>(); rootResources.add(ServiceImplementation.class); rootResources.add(ServerPostProcessInterceptor.class); rootResources.add(ServerExceptionMapper.class); return rootResources; }
7e55bef0-e65d-434e-a1b2-7c2192aebf43
public Endpoint(){ }
bf263e70-711b-42f9-9c32-399d8205536b
public String get(int id) throws SomeApplicationException { String result = null; try { TodoItem i = service.getItem(id); result = i.getDescription(); } catch (SomeApplicationException e) { result = e.getMessage(); } return result; }
b0dcab59-ab53-427c-8bea-9fd9e2e66030
public Integer put() { Integer result = null; try { TodoItem t = new TodoItem(); t.setDescription("Testitem"); result = service.takeItem(t); } catch (SomeApplicationException e) { result = -1; } return result; }
3be224a5-a6a1-46f0-bbb6-12c24eae4c9c
@GET @Path("get/{id}") @Produces(MediaType.TEXT_PLAIN) public String get(@PathParam("id") int id) throws SomeApplicationException;
ddf7792a-dab9-4f9e-b68c-a7bb2a0dc7f6
@GET @Path("create/") @Produces(MediaType.TEXT_PLAIN) public Integer put();
af04dd5c-c26c-49ae-8653-31805fdffdca
@Override public Set<Class<?>> getClasses() { final Set<Class<?>> rootResources = new HashSet<Class<?>>(); rootResources.add(Endpoint.class); return rootResources; }
7e232f3f-0abb-48ff-804e-c20ab65165ce
public Game(){ builder = new StringBuilder(); }
c4b66e86-c02e-4842-97b2-6c938cc02f98
public String getResult() { return result; }
6300b445-c3e7-4321-86c8-257b9e2b5130
public void setResult(String result) { this.result = result; }
4355a0b2-6f4e-4234-983c-cf900a3276f9
public String getMoves() { return moves; }
8c5420c7-6bd2-4147-9e9e-bf6349a3151f
public void setMoves(String moves) { this.moves = moves; }
8eaa5ac9-a575-47c5-a1dc-ea7e54413e8e
public StringBuilder getBuilder() { return builder; }
b94b1ffc-bcdb-4de3-ad53-f29d4e695fcf
public void setOutputLine(String outputLine) { this.outputLine = outputLine; }
c7e8bb65-f3a4-4fb8-8279-92690b56de88
@Override public String toString(){ return outputLine; }
f312c008-9e36-4063-ac2c-ef1c8440065f
public static void main(String[] args) { PGNReader reader = new PGNReader(); reader.run(); }
5d6d4191-4672-4b99-b872-54480b8d229c
public void run() { games = new ArrayList<Game>(); try { Scanner scanner = new Scanner(new FileReader("BDG2.PGN")); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (!line.startsWith("[Result") && line.startsWith("[")) { // System.out.println("do nothing"); } if (line.startsWith("[Result")) { // new Game game = new Game(); // System.out.println("new game!"); games.add(game); String result = ""; if (line.equals("[Result \"1-0\"]")) { result = "white"; } else if (line.equals("[Result \"0-1\"]")) { result = "black"; } else { result = "draw"; } // System.out.println("set result!"); game.setResult(result); // System.out.println(result); } if (!line.startsWith("[")) { game.getBuilder().append(line + " "); } } } catch (FileNotFoundException e) { e.printStackTrace(); } int white = 0; int black = 0; int draw = 0; try { output = new BufferedWriter(new FileWriter("chessGames.csv", true)); } catch (Exception e) { e.printStackTrace(); } for (Game game : games) { // System.out.println(game.builder.toString().trim()); // remove variations and annotations purgeAnnotations(game); purgeVariations(game); // System.out.println(game.builder.toString().trim()); // add commas commaTime(game); game.setOutputLine(game.getResult() + "," + game.getMoves().trim()); // write file System.out.println(game); try { //change literal parameter for diff file if (game.getResult().equals("draw")) { output.append(game.toString()); output.newLine(); } // output.close(); } catch (Exception e) { e.printStackTrace(); } if (game.getResult().equals("white")) { ++white; } if (game.getResult().equals("black")) { ++black; } if (game.getResult().equals("draw")) { ++draw; } // end } try { output.close(); } catch (Exception e) { e.printStackTrace(); } // alpha analysis System.out.println("white: " + white + "black: " + black + "draw: " + draw); }
9e519f53-8e0e-41d4-b08b-fdb10d2bf1f1
public void purgeAnnotations(Game game) { int start = 0; int end = 0; boolean clean = false; boolean removedOne = false; while (!clean) { for (int i = 0; i < game.builder.toString().trim().length(); ++i) { removedOne = false; if (game.builder.toString().trim().charAt(i) == '{') { start = i; // System.out.println("set start to: " + start); } if (game.builder.toString().trim().charAt(i) == '}') { if (game.builder.toString().trim().charAt(i + 5) == '.') { end = i + 8; } else { end = i + 2; } // System.out.println("set end to: " + end); // System.out.println(start + " " + end); game.builder.delete(start, end); removedOne = true; break; } } if (!removedOne) { clean = true; } } }
4a4325b2-fe9a-4584-bae4-4b0848b4fd29
public void purgeVariations(Game gqme) { int start = 0; int end = 0; boolean clean = false; boolean removedOne = false; while (!clean) { for (int i = 0; i < game.builder.toString().trim().length(); ++i) { removedOne = false; if (game.builder.toString().trim().charAt(i) == '(') { start = i; // System.out.println("set start to: " + start); } if (game.builder.toString().trim().charAt(i) == ')') { end = i + 7; // System.out.println("set end to: " + end); // System.out.println(start + " " + end); game.builder.delete(start, end); removedOne = true; break; } } if (!removedOne) { clean = true; } } }
98a2ae37-7885-45e7-ace5-869eeb4fbbca
public void commaTime(Game game) { for (int i = 0; i < game.builder.toString().trim().length() - 3; ++i) { if (game.builder.toString().trim().charAt(i) == ' ') { if (game.builder.toString().trim().charAt(i + 2) == '.') { game.builder.setCharAt(i + 1, ','); } if (game.builder.toString().trim().charAt(i + 3) == '.') { game.builder.setCharAt(i + 1, ','); } } } // System.out.println("set moves!"); game.setMoves(game.builder.toString()); }
9b30cfc6-ec1b-4aac-956d-9c765c417f76
public String[] getItems() { return itemset; }
1d9adfb6-ac13-4116-a825-c4276c3458c0
public Itemset() { itemset = new String[] {}; }
a80495b6-6b34-4c2c-ab5f-887bbdd59e32
public Itemset(String string) { itemset = new String[] { string }; }
9d41651c-c1c7-46b7-af99-8add030f4354
public Itemset(String[] items) { this.itemset = items; }
a6f08d15-23d4-49d4-8873-b7e7bc80e1ae
public int getAbsoluteSupport() { return support; }
34db955a-ad77-4c41-bf89-7ad57f3c995f
public int size() { return itemset.length; }
cf16edc6-4729-4edc-98a9-6d5c128db512
public String get(int position) { return itemset[position]; }
dbc8dcfb-33b6-4123-922d-5546f874d773
public void setAbsoluteSupport(Integer support) { this.support = support; }
f517f815-b8f7-4fa0-9a03-ac4eee3ca5ef
public void increaseTransactionCount() { this.support++; }
61e7db4e-51c8-4678-8a0f-6bdfde673732
public Itemset cloneItemSetMinusOneItem(String itemsetToRemove) { // create the new itemset String[] newItemset = new String[itemset.length - 1]; int i = 0; // for each item in this itemset for (int j = 0; j < itemset.length; j++) { // copy the item except if it is the item that should be excluded if (itemset[j] != itemsetToRemove) { newItemset[i++] = itemset[j]; } } return new Itemset(newItemset); // return the copy }
0cecaa31-566d-4a5b-8009-aca01296338c
public Itemset cloneItemSetMinusAnItemset(Itemset itemsetToNotKeep) { // create a new itemset String[] newItemset = new String[itemset.length - itemsetToNotKeep.size()]; int i = 0; // for each item of this itemset for (int j = 0; j < itemset.length; j++) { // copy the item except if it is not an item that should be excluded if (itemsetToNotKeep.contains(itemset[j]) == false) { newItemset[i++] = itemset[j]; } } return new Itemset(newItemset); // return the copy }
663fc227-86c1-42b2-9810-64260028b2fe
public AbstractMutableOrderedItemset() { super(); }
27b68d95-5d35-412e-b8a4-7f61128ef36a
public abstract void addItem(Integer value);
39e68d58-f5cf-4670-bb2f-6d89de3f9674
protected abstract AbstractMutableOrderedItemset createNewEmptyItemset();
56c08334-b56b-49ab-b9fe-0177da3f3ff9
public AbstractMutableOrderedItemset cloneItemSetMinusAnItemset(AbstractMutableOrderedItemset itemsetToNotKeep){ // create a new itemset AbstractMutableOrderedItemset itemset = createNewEmptyItemset(); // Make a loop to copy each item for(int i=0; i< size(); i++){ String item = this.get(i); // If the current item should be included, we add it. if(!itemsetToNotKeep.contains(item)){ itemset.addItem(item); } } return itemset; // return the new itemset }
e4b9b2d1-0d53-43fc-b177-fa5ef8861444
private void addItem(String item) { // TODO Auto-generated method stub }
b6beeb64-0159-4cc4-b69e-2ce50b1a3779
public AbstractMutableOrderedItemset cloneItemSetMinusOneItem(Integer itemToNotInclude){ // create a new itemset AbstractMutableOrderedItemset itemset = createNewEmptyItemset(); // Make a loop to copy each item for(int i=0; i< size(); i++){ String item = this.get(i); // If the current item should be included, we add it. if(!itemToNotInclude.equals(item)){ itemset.addItem(item); } } return itemset; // return the new itemset }
d1f4e1c4-dba9-4a31-a401-abeec22b929b
public AbstractMutableOrderedItemset intersection(AbstractMutableOrderedItemset itemset2) { AbstractMutableOrderedItemset intersection = createNewEmptyItemset(); for(int i=0; i< size(); i++){ String item = this.get(i); if (itemset2.contains(item)) { intersection.addItem(item); } } return intersection; }
8aabeb4f-d5f8-43bb-a4b6-b2ee478166d5
public AlgoApriori() { }
5b499f67-a365-4209-931f-413e4427795e
public Itemsets runAlgorithm(double minsup, String fileInput, String fileOutput) throws IOException { // if the user want to keep the result into memory if (fileOutput == null) { writer = null; patterns = new Itemsets("FREQUENT ITEMSETS"); } else { // if the user want to save the result to a file patterns = null; writer = new BufferedWriter(new FileWriter(fileOutput)); } // record the start time startTimestamp = System.currentTimeMillis(); // set the number of itemset found to zero itemsetCount = 0; // set the number of candidate found to zero totalCandidateCount = 0; // reset the utility for checking the memory usage MemoryLogger.getInstance().reset(); // READ THE INPUT FILE // variable to count the number of transactions databaseSize = 0; // Map to count the support of each item // Key: item Value : support // cfd: again, changed type to String - of the item in the map Map<String, Integer> mapItemCount = new HashMap<String, Integer>(); // to // count // the // support // of // each // item database = new ArrayList<String[]>(); // the database in memory // (intially empty) // scan the database to load it into memory and count the support of // each single item at the same time BufferedReader reader = new BufferedReader(new FileReader(fileInput)); String line; // for each line (transactions) until the end of the file while (((line = reader.readLine()) != null)) { // if the line is a comment, is empty or is a // kind of metadata if (line.isEmpty() == true || line.charAt(0) == '#' || line.charAt(0) == '%' || line.charAt(0) == '@') { continue; } // split the line according to spaces // So1: // String[] lineSplited = line.split(","); // So2: String[] chunks = line.split(","); String[] lineSplited = new String[chunks.length]; for(int i = 0; i < chunks.length-1; ++i){ lineSplited[i] = chunks[i] + " " + chunks[i+1]; } // create an array of int to store the items in this transaction // cfd: Changed data types to String String transaction[] = new String[lineSplited.length]; // for each item in this line (transaction) for (int i = 0; i < lineSplited.length; i++) { // transform this item from a string to an integer // cfd: REPLACED THIS LINE AS WE NEED TO WORK WITH STRINGS // PROBABLY NEED TO PUT .equals() IN A LOT OF PLACES :( // Integer item = Integer.parseInt(lineSplited[i]); String item = lineSplited[i]; // store the item in the memory representation of the database transaction[i] = item; // increase the support count Integer count = mapItemCount.get(item); if (count == null) { mapItemCount.put(item, 1); } else { mapItemCount.put(item, ++count); } } // add the transaction to the database database.add(transaction); // increase the number of transaction databaseSize++; } // close the input file reader.close(); // conver the minimum support as a percentage to a // relative minimum support as an integer this.minsupRelative = (int) Math.ceil(minsup * databaseSize); // we start looking for itemset of size 1 k = 1; // We add all frequent items to the set of candidate of size 1 List<String> frequent1 = new ArrayList<String>(); for (Entry<String, Integer> entry : mapItemCount.entrySet()) { if (entry.getValue() >= minsupRelative) { frequent1.add(entry.getKey()); saveItemsetToFile(entry.getKey(), entry.getValue()); } } mapItemCount = null; // We sort the list of candidates by lexical order // (Apriori need to use a total order otherwise it does not work) // cfd: apparently it wont work ^^^, but we dont want to sort our moves. // Collections.sort(frequent1, new Comparator<Integer>() { // public int compare(Integer o1, Integer o2) { // return o1 - o2; // } // }); // If no frequent item, the algorithm stops! if (frequent1.size() == 0) { // close the output file if we used it if (writer != null) { writer.close(); } return patterns; } // add the frequent items of size 1 to the total number of candidates totalCandidateCount += frequent1.size(); // Now we will perform a loop to find all frequent itemsets of size > 1 // starting from size k = 2. // The loop will stop when no candidates can be generated. List<Itemset> level = null; k = 2; do { // we check the memory usage MemoryLogger.getInstance().checkMemory(); // Generate candidates of size K List<Itemset> candidatesK; // if we are at level k=2, we use an optimization to generate // candidates if (k == 2) { candidatesK = generateCandidate2(frequent1); } else { // otherwise we use the regular way to generate candidates candidatesK = generateCandidateSizeK(level); } // we add the number of candidates generated to the total totalCandidateCount += candidatesK.size(); // We scan the database one time to calculate the support // of each candidates and keep those with higher suport. // For each transaction: for (String[] transaction : database) { // for each candidate: loopCand: for (Itemset candidate : candidatesK) { // a variable that will be use to check if // all items of candidate are in this transaction int pos = 0; // for each item in this transaction for (String item : transaction) { // if the item correspond to the current item of // candidate if (item.equals(candidate.itemset[pos])) { // we will try to find the next item of candidate // next pos++; // if we found all items of candidate in this // transaction if (pos == candidate.itemset.length) { // we increase the support of this candidate candidate.support++; continue loopCand; } // Because of lexical order, we don't need to // continue scanning the transaction if the current // item // is larger than the one that we search in // candidate. } else /* cdf:if(item > candidate.itemset[pos]) */{ continue loopCand; } } } } // We build the level k+1 with all the candidates that have // a support higher than the minsup threshold. level = new ArrayList<Itemset>(); for (Itemset candidate : candidatesK) { // if the support is > minsup if (candidate.getAbsoluteSupport() >= minsupRelative) { // add the candidate level.add(candidate); // the itemset is frequent so save it into results saveItemset(candidate); } } // we will generate larger itemsets next. k++; } while (level.isEmpty() == false); // record end time endTimestamp = System.currentTimeMillis(); // check the memory usage MemoryLogger.getInstance().checkMemory(); // close the output file if the result was saved to a file. if (writer != null) { writer.close(); } return patterns; }
d1054f8f-8e0d-4b69-a688-4879787d5720
public int getDatabaseSize() { return databaseSize; }
57b74f9f-026e-4c2b-a1b2-a2a03d29e349
private List<Itemset> generateCandidate2(List<String> frequent1) { List<Itemset> candidates = new ArrayList<Itemset>(); // For each itemset I1 and I2 of level k-1 for (int i = 0; i < frequent1.size(); i++) { String item1 = frequent1.get(i); for (int j = i + 1; j < frequent1.size(); j++) { String item2 = frequent1.get(j); // Create a new candidate by combining itemset1 and itemset2 candidates.add(new Itemset(new String[] { item1, item2 })); } } return candidates; }
52dfd74b-91d6-43d6-a377-6511f6ddfbca
protected List<Itemset> generateCandidateSizeK(List<Itemset> levelK_1) { // create a variable to store candidates List<Itemset> candidates = new ArrayList<Itemset>(); // For each itemset I1 and I2 of level k-1 loop1: for (int i = 0; i < levelK_1.size(); i++) { String[] itemset1 = levelK_1.get(i).itemset; loop2: for (int j = i + 1; j < levelK_1.size(); j++) { String[] itemset2 = levelK_1.get(j).itemset; // we compare items of itemset1 and itemset2. // If they have all the same k-1 items and the last item of // itemset1 is smaller than // the last item of itemset2, we will combine them to generate a // candidate for (int k = 0; k < itemset1.length; k++) { // if they are the last items if (k == itemset1.length - 1) { // the one from itemset1 should be smaller (lexical // order) // and different from the one of itemset2 // cfd: order... // if (itemset1[k] >= itemset2[k]) { // continue loop1; // } } // if they are not the last items, and // else if (itemset1[k] < itemset2[k]) { // continue loop2; // we continue searching // } else if (itemset1[k] > itemset2[k]) { // continue loop1; // we stop searching: because of lexical // order // } } // Create a new candidate by combining itemset1 and itemset2 String newItemset[] = new String[itemset1.length + 1]; System.arraycopy(itemset1, 0, newItemset, 0, itemset1.length); newItemset[itemset1.length] = itemset2[itemset2.length - 1]; // The candidate is tested to see if its subsets of size k-1 are // included in // level k-1 (they are frequent). if (allSubsetsOfSizeK_1AreFrequent(newItemset, levelK_1)) { candidates.add(new Itemset(newItemset)); } } } return candidates; // return the set of candidates }
3ac19e3d-09ca-46f5-99b9-7494b125c3ca
protected boolean allSubsetsOfSizeK_1AreFrequent(String[] newItemset, List<Itemset> levelK_1) { // generate all subsets by always each item from the candidate, one by // one for (int posRemoved = 0; posRemoved < newItemset.length; posRemoved++) { // perform a binary search to check if the subset appears in level // k-1. int first = 0; int last = levelK_1.size() - 1; // variable to remember if we found the subset boolean found = false; // the binary search while (first <= last) { int middle = (first + last) / 2; if (sameAs(levelK_1.get(middle), newItemset, posRemoved) < 0) { first = middle + 1; // the itemset compared is larger than // the subset according to the lexical // order } else if (sameAs(levelK_1.get(middle), newItemset, posRemoved) > 0) { last = middle - 1; // the itemset compared is smaller than // the subset is smaller according to // the lexical order } else { found = true; // we have found it so we stop break; } } if (found == false) { // if we did not find it, that means that // candidate is not a frequent itemset // because // at least one of its subsets does not appear in level k-1. return false; } } return true; }
93e23b3d-7648-4526-92ab-356d0fd7a96c
private int sameAs(Itemset itemset, String[] newItemset, int posRemoved) { // a variable to know which item from candidate we are currently // searching int j = 0; // loop on items from "itemset" for (int i = 0; i < itemset.itemset.length; i++) { // if it is the item that we should ignore, we skip it if (j == posRemoved) { j++; } // if we found the item j, we will search the next one if (itemset.itemset[i] == newItemset[j]) { j++; // if the current item from i is larger than j, // it means that "itemset" is larger according to lexical order // so we return 1 // cfd: ORDER! // }else if (itemset.itemset[i] > newItemset[j]){ // return 1; // }else{ // otherwise "itemset" is smaller so we return -1. // return -1; } } return 0; }
54a8dd79-7628-4f3c-99dd-1b9b33762f31
void saveItemset(Itemset itemset) throws IOException { itemsetCount++; // if the result should be saved to a file if (writer != null) { writer.write(itemset.toString() + " #SUP: " + itemset.getAbsoluteSupport()); writer.newLine(); }// otherwise the result is kept into memory else { patterns.addItemset(itemset, itemset.size()); } }
1537f68c-6060-4504-a587-7f9bd0304858
void saveItemsetToFile(String string, Integer support) throws IOException { itemsetCount++; // if the result should be saved to a file if (writer != null) { writer.write(string + "," + support); writer.newLine(); }// otherwise the result is kept into memory else { Itemset itemset = new Itemset(string); itemset.setAbsoluteSupport(support); patterns.addItemset(itemset, 1); } }
b113f9d0-6ac6-445f-8938-ecf5d8e3977a
public void printStats() { System.out.println("============= APRIORI - STATS ============="); System.out.println(" Candidates count : " + totalCandidateCount); System.out.println(" The algorithm stopped at size " + (k - 1) + ", because there is no candidate"); System.out.println(" Frequent itemsets count : " + itemsetCount); System.out.println(" Maximum memory usage : " + MemoryLogger.getInstance().getMaxMemory() + " mb"); System.out.println(" Total time ~ " + (endTimestamp - startTimestamp) + " ms"); System.out .println("==================================================="); }
e5f5d082-378d-474a-b171-2874c9bed7bf
public AbstractItemset() { super(); }
db0e522d-53d5-42c0-95f3-fbbec5341f11
public abstract int size();
bcc09dab-cf50-4fdd-90fe-22848bae9724
public abstract String toString();
75921bd9-d5b0-4119-a2f2-7bea14575403
public void print() { System.out.print(toString()); }
83839238-9b84-45f3-8315-caf6bf2bd075
public abstract int getAbsoluteSupport();
fd935cf2-d015-4aa4-b729-4c476d28ec14
public abstract double getRelativeSupport(int nbObject);
87cb8848-859e-48d6-94ac-6d0211c1e401
public String getRelativeSupportAsString(int nbObject) { // get the relative support double frequence = getRelativeSupport(nbObject); // convert it to a string with two decimals DecimalFormat format = new DecimalFormat(); format.setMinimumFractionDigits(0); format.setMaximumFractionDigits(5); return format.format(frequence); }
122897d3-1198-40a4-a33b-89bd552f46bc
public abstract boolean contains(String item);
99601567-4782-41bd-9339-2f3c5d1dd2b5
public AbstractOrderedItemset() { super(); }
cd604d9b-cffe-4468-9d68-e95d00d850c0
public abstract int getAbsoluteSupport();
12c0f1ee-e738-4470-84fb-4c791a4c638e
public abstract int size();
53ca6dff-98d9-49de-b2be-7b1de76ab358
public abstract String get(int position);
f491e39d-6a07-4bc7-9612-698ae014f2c1
public String getLastItem() { return get(size() - 1); }
47f604fd-8364-494a-b387-8a063fd73271
public String toString(){ // use a string buffer for more efficiency StringBuffer r = new StringBuffer (); // for each item, append it to the stringbuffer for(int i=0; i< size(); i++){ r.append(get(i)); r.append(' '); } return r.toString(); // return the tring }
f7fe3673-6d04-47cf-bab6-9d50af97429e
public double getRelativeSupport(int nbObject) { // Divide the absolute support by the number of transactions to get the relative support return ((double)getAbsoluteSupport()) / ((double) nbObject); }
7f456225-08d8-47b4-9c1d-fd26cbe1047f
public boolean contains(String item) { for (int i=0; i< size(); i++) { if (get(i).equals(item)) { return true; } else /*if (get(i) > item)*/ { return false; } } return false; }
4c83c142-3f0f-426d-840a-4b6361cf9f8b
public boolean containsAll(AbstractOrderedItemset itemset2){ // first we check the size if(size() < itemset2.size()){ return false; } // we will use this variable to remember where we are in this itemset int i = 0; // for each item in itemset2, we will try to find it in this itemset for(int j =0; j < itemset2.size(); j++){ boolean found = false; // flag to remember if we have find the item at position j // we search in this itemset starting from the current position i while(found == false && i< size()){ // if we found the current item from itemset2, we stop searching if(get(i).equals(itemset2.get(j))){ found = true; }// if the current item in this itemset is larger than // the current item from itemset2, we return false // because the itemsets are assumed to be lexically ordered. //cfd: 'else if' lines commented due to no numerical order in chess moves //else if(get(i) > itemset2.get(j)){ //return false; //} i++; // continue searching from position i++ } // if the item was not found in the previous loop, return false if(!found){ return false; } } return true; // if all items were found, return true }
6772389c-b27a-4409-bd45-d9e781e2fa09
public boolean isEqualTo(AbstractOrderedItemset itemset2) { // If they don't contain the same number of items, we return false if (this.size() != itemset2.size()) { return false; } // We compare each item one by one from i to size - 1. for (int i = 0; i < itemset2.size(); i++) { // if different, return false if (!itemset2.get(i).equals(this.get(i))) { return false; } } // All the items are the same, we return true. return true; }
d6a6adb4-84b4-455f-8bfd-33a9c4c13b11
public boolean allTheSameExceptLastItemV2(AbstractOrderedItemset itemset2) { // if they don't contain the same number of item, return false if (itemset2.size() != this.size()) { return false; } // Otherwise, we have to compare item by item for (int i = 0; i < this.size() - 1; i++) { // if they are not the last items, they should be the same // otherwise return false if (!this.get(i).equals(itemset2.get(i))) { return false; } } // All items are the same. We return true. return true; }
f7a7bf53-7c30-4b4a-97e9-43c398ca11cb
public String allTheSameExceptLastItem(AbstractOrderedItemset itemset2) { // if these itemsets do not have the same size, return null if(itemset2.size() != this.size()){ return null; } // We will compare all items one by one starting from position i =0 to size -1 for(int i=0; i< this.size(); i++){ // if this is the last position if(i == this.size()-1){ // We check if the item from this itemset is be smaller (lexical order) // and different from the one of itemset2. // If not, return null. //cfd: 'if' commented - no order //if(this.get(i) >= itemset2.get(i)){ // return null; //} } // If this is not the last position, we check if items are the same else if(!this.get(i).equals(itemset2.get(i))){ // if not, return null return null; } } // otherwise, we return the position of the last item return itemset2.get(itemset2.size()-1); }
076da0c2-caab-4a00-8275-20b10a8c2dc6
public static MemoryLogger getInstance(){ return instance; }
3c72c884-871b-41d0-80be-84b6097c2eff
public double getMaxMemory() { return maxMemory; }
1a8bb715-ddfa-41cd-8a21-e9e825e7cf28
public void reset(){ maxMemory = 0; }
df82c841-c280-48d5-8cc6-093eaeb268f4
public void checkMemory() { double currentMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024d / 1024d; if (currentMemory > maxMemory) { maxMemory = currentMemory; } }
7300006e-e046-45e7-8b22-7d3cb416f674
public Itemsets(String name) { this.name = name; levels.add(new ArrayList<Itemset>()); // We create an empty level 0 by // default. }
27d19680-f5b8-41e8-9fb3-4616ec111455
public void printItemsets(int nbObject) { System.out.println(" ------- " + name + " -------"); int patternCount = 0; int levelCount = 0; // for each level (a level is a set of itemsets having the same number of items) for (List<Itemset> level : levels) { // print how many items are contained in this level System.out.println(" L" + levelCount + " "); // for each itemset for (Itemset itemset : level) { // print the itemset System.out.print(" pattern " + patternCount + ": "); itemset.print(); // print the support of this itemset System.out.print("support : " + itemset.getRelativeSupportAsString(nbObject)); patternCount++; System.out.println(""); } levelCount++; } System.out.println(" --------------------------------"); }
0078cc0a-5127-4db4-a087-f7d21f1c45e8
public void addItemset(Itemset itemset, int k) { while (levels.size() <= k) { levels.add(new ArrayList<Itemset>()); } levels.get(k).add(itemset); itemsetsCount++; }