Determine number of commit ahead and behind using JGit - jgit

On a GitHub project, when we go to any branches page, we can see graphs which describes commit ahead/behind numbers of a branch w.r.t. master.
How can we determine those ahead behind numbers using JGit?
I used BranchTrackingStatus class for this, but I'm getting BranchTrackingStatus object always null.
Here is the code which I used
private static Lis<Integer> getCounts(Repository repository, String branchName) throws IOException{
BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName);
List<Integer> counts = new ArrayList<Integer>();
if (trackingStatus != null){
counts.add(trackingStatus.getAheadCount());
counts.add(trackingStatus.getBehindCount());
} else {
counts.add(0);
counts.add(0);
}
return counts;
}
public void show(String repoName, String baseBranchName) throws IOException, GitAPIException{
Repository repository = repoManager.openRepository(new Project.NameKey(repoName));
List<Ref> call = new Git(repository).branchList().call();
for (Ref ref : call) {
List<Integer> counts = getCounts(repository, ref.getName());
System.out.println("Commits ahead : "+counts.get(0));
System.out.println("Commits behind : "+counts.get(1));
}
}

BranchTrackingStatus.of() assumes that branchName denotes a local branch, either by its full name (e.g. refs/heads/master) or its short name (e.g. master). It returns null if the given branchName cannot be found or the tracking branch is not configured or does not exist.
To compare two arbitrary branches, you could adopt the BranchTrackingStatus code like so:
void calculateDivergence(Ref local, Ref tracking) throws IOException {
try (RevWalk walk = new RevWalk(repository)) {
RevCommit localCommit = walk.parseCommit(local.getObjectId());
RevCommit trackingCommit = walk.parseCommit(tracking.getObjectId());
walk.setRevFilter(RevFilter.MERGE_BASE);
walk.markStart(localCommit);
walk.markStart(trackingCommit);
RevCommit mergeBase = walk.next();
walk.reset();
walk.setRevFilter(RevFilter.ALL);
aheadCount = RevWalkUtils.count(walk, localCommit, mergeBase);
behindCount = RevWalkUtils.count(walk, trackingCommit, mergeBase);
}
}

Your code looks fine to me, I took some of it and added it as a sample in the jgit-cookbook to see if it works. Locally I see counts when there are actual differences to the remote repostory.
Please note how BranchTrackingStatus works: It will not do a remote request and fetch the latest commits from the remote side, but it will only show what the local git repository has on the remote-tracking branches compared to the local branches.
I.e. you probably need to do a git fetch first on a repository that has updates on the remote side in order to get the status of the remote repository updated and only then BranchTrackingStatus will show values.

Related

AWS Textract - GetDocumentAnalysisRequest only returns correct results for first page of document

I have written code to extract tables and name value pairs from pdf using Amazon Textract. I followed this example:
https://docs.aws.amazon.com/textract/latest/dg/async-analyzing-with-sqs.html
which was in sdk for java version 1.1.
I have refactored it for version 2.
This is an async process that only applies to multi page documents. When i get back the results it is pretty accurate for first page. But the consecutive pages are mostly empty rows. The documents i parse are scanned so the quality is not great. However if i take a jpg of individual pages and use the one page operation, i.e. AnalyzeDocumentRequest, each page comes out good. Also Amazon Textract tryit service renders the pages correctly.
So the error must be in my code but can't see where.
As you see it all happens in here :
GetDocumentAnalysisRequest documentAnalysisRequest = GetDocumentAnalysisRequest.builder().jobId(jobId)
.maxResults(maxResults).nextToken(paginationToken).build();
response = textractClient.getDocumentAnalysis(documentAnalysisRequest);
and i can't really do any intervention.
The most likely place I could make a mistake would be in the util file that gathers the page and table blocks i.e. here:
PageModel pageModel = tableUtil.getTableResults(blocks);
But that works perfectly for the first page, and i could also see in the response object above, that the number of blocks returned are much less.
Here is the full code:
private DocumentModel getDocumentAnalysisResults(String jobId) throws Exception {
int maxResults = 1000;
String paginationToken = null;
GetDocumentAnalysisResponse response = null;
Boolean finished = false;
int pageCount = 0;
DocumentModel documentModel = new DocumentModel();
// loops until pagination token is null
while (finished == false) {
GetDocumentAnalysisRequest documentAnalysisRequest = GetDocumentAnalysisRequest.builder().jobId(jobId)
.maxResults(maxResults).nextToken(paginationToken).build();
response = textractClient.getDocumentAnalysis(documentAnalysisRequest);
// Show blocks, confidence and detection times
List<Block> blocks = response.blocks();
PageModel pageModel = tableUtil.getTableResults(blocks);
pageModel.setPageNumber(pageCount++);
Map<String,String> keyValues = formUtil.getFormResults(blocks);
pageModel.setKeyValues(keyValues);
documentModel.getPages().add(pageModel);
paginationToken = response.nextToken();
if (paginationToken == null)
finished = true;
}
return documentModel;
}
Has anyone else encountered this issue?
Many thanks
if the response has NextToken, then you need to recall textract and pass in the NextToken to get the next batch of Blocks.
I am not sure how to do this in Java but here is the python example from AWS repo
https://github.com/aws-samples/amazon-textract-serverless-large-scale-document-processing/blob/master/src/jobresultsproc.py
For my solution, I did a simple if response['NextToken'] then recall method and concat the response['Blocks'] to my current list.

Batch Export Forms from AX 2009

I'm currently working on a system that will export all the nodes from my AX 2009 AOT to individual XPO files, for the purpose of tracking changes in a central version control repository. I'm having a fair amount of luck, but for some reason I cannot get the Forms or Data Sets node to export at all.
This is my current code set:
private void export(str parentNode)
{
TreeNode node, parent;
str folderName;
Set permissions = new Set(Types::Class);
;
folderName = exportBaseDir + parentNode;
permissions.add(new FileIoPermission(folderName, "r"));
permissions.add(new InteropPermission(InteropKind::ClrInterop));
CodeAccessPermission::assertMultiple(permissions);
//Create Filesystem Folder if needed
if (!WinApiServer::pathExists(folderName))
System.IO.Directory::CreateDirectory(folderName);
CodeAccessPermission::revertAssert();
parent = TreeNode::findNode(parentNode);
if (parent)
node = parent.AOTfirstChild();
else
warning(strfmt("Could not parse node: %1", parentNode));
while (node)
{
this.exportNode(node);
node = node.AOTnextSibling();
}
}
When I call export(#"\Forms"); or export(#"\Data Sets"); I get a "Could not parse node" message, meaning the TreeNode::findNode() didn't resolve correctly. Running it on any other node (such as Classes) does not have this issue. This also only happens when it is run in a Batch -- running it with the client (with the CodeAccessPermission parts removed) will export all nodes as expected.
Is there something that would prohibit Forms and Data Sets from being accessed from within a Batch? If so, what can I do to access those nodes?
As far as I can tell it's a server/client issue/bug. The easy solution would be to create this method on your class:
client static TreeNode clientTreeNode(str _path)
{
return TreeNode::findNode(_path);
}
Then in your code, below the parent = TreeNode::findNode(parentNode); line, put:
parent = parent ? parent : YourClassHere::clientTreeNode(parentNode);
And that should solve your issue. You'll have a bit of digging to do in order to find out why it doesn't work on the server tier if you just must know.

Blackberry - Cannot create SQLite database

I am making an app that runs in the background, and starts on device boot.
I have read the docs, and have the SQLiteDemo files from RIM, and I am using them to try create a database on my SD Card in the simulator.
Unfortunately, I am getting this error:
DatabasePathException:Invalid path name. Path does not contains a proper root list. See FileSystemRegistry class for details.
Here's my code:
public static Database storeDB;
public static final String DATABASE_NAME = "testDB";
private String DATABASE_LOCATION = "file:///SDCard/Databases/MyDBFolder/";
public static URI dbURI;
dbURI = URI.create(DATABASE_LOCATION+DATABASE_NAME);
storeDB = DatabaseFactory.openOrCreate(dbURI);
I took out a try/catch for URI.create and DatabaseFactory.openOrCreate for the purposes of this post.
So, can anyone tell me why I can't create a database on my simulator?
If I load it up and go into media, I can create a folder manually. The SD card is pointing to a folder on my hard drive, and if I create a folder in there, it is shown on the simulator too, so I can create folders, just not programatically.
Also, I have tried this from the developer docs:
// Determine if an SDCard is present
boolean sdCardPresent = false;
String root = null;
Enumeration enum = FileSystemRegistry.listRoots();
while (enum.hasMoreElements())
{
root = (String)enum.nextElement();
System.err.println("root="+root);
if(root.equalsIgnoreCase("sdcard/"))
{
sdCardPresent = true;
}
}
But it only picks up store/ and never sdcard/.
Can anyone help?
Thanks.
FYI,
I think I resolved this.
The problem was I was trying to write to storage during boot-up, but the storage wasn't ready. Once the device/simulator was loaded, and a few of my listeners were triggered, the DB was created.
See here:
http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/832062/How_To_-_Write_safe_initialization_code.html?nodeid=1487426&vernum=0

Random failures using CMISQL queries on Alfresco 3.3.0

[Solved, it seems that there was some bug affecting Alfresco 3.3.0, which is no longer present on Alfresco 3.3.0g]
Hi,
I'm using OpenCMIS to retrieve data from Alfresco 3.3, but it's having a very weird behaviour on CMISQL queries. I've googled somebody else with the same problems, but it seems I'm the first one all over the world :), so I guess it's my fault, not OpenCMIS'.
This is how I'm querying Alfresco:
public Class CmisTest {
private static Session sesion;
private static final String QUERY = "select cmis:objectid, cmis:name from cmis:folder where cmis:name='MyFolder'";
public static void main(String[] args) {
// Open a CMIS session with Alfresco
Map<String, String> params = new HashMap<String, String>();
params.put(SessionParameter.USER, "admin");
params.put(SessionParameter.PASSWORD, "admin");
params.put(SessionParameter.ATOMPUB_URL, "http://localhost:8080/alfresco/s/api/cmis");
params.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
params.put(SessionParameter.REPOSITORY_ID, "fa9d2553-1e4d-491b-87fd-3de894dc7ca9");
sesion = SessionFactoryImpl.newInstance().createSession(params);
// Ugly bug in Alfresco which raises an exception if we request more data than it's available
// See https://issues.alfresco.com/jira/browse/ALF-2859
sesion.getDefaultContext().setMaxItemsPerPage(1);
// We repeat the same query 20 times and count the number of elements retrieved each time
for (int i = 0; i < 20; i++) {
List<QueryResult> result = doQuery();
System.out.println(result.size() + " folders retrieved");
}
}
public static List<QueryResult> doQuery() {
List<QueryResult> result = new LinkedList<QueryResult>();
try {
int page = 0;
while (true) {
ItemIterable<QueryResult> iterable = sesion.query(QUERY, false).skipTo(page);
page++;
for (QueryResult qr : iterable) {
result.add(qr);
}
}
} catch (Exception e) {
// We will always get an exception when Alfresco has no more data to retrieve... :(
// See https://issues.alfresco.com/jira/browse/ALF-2859
}
return result;
}
}
As you can see, we just execute the same query, up to 20 times in a row. You would expect the same result each time, wouldn't you? Unfortunately, this is a sample of what we get:
1 folders retrieved
1 folders retrieved
1 folders retrieved
0 folders retrieved
0 folders retrieved
0 folders retrieved
0 folders retrieved
0 folders retrieved
1 folders retrieved
1 folders retrieved
Sometimes we get 20 1 in a row, sometimes it's all 0. We have never get a "mix" of 1 and 0, though; we always get "a run" of them.
It does not matter if we create the session before each query, we still have the random issue. We have tried against two different Alfresco servers (both of them 3.3 Community), clean installation, and they both fail randomly. We also tried to measure the time for each query, but it doesn't seem to have any relation with the result being wrong (0 folders retrieved) or right (1 folders retrieved).
Alfresco seems to be working fine: if we go to "Administration --> Node browser" and launch the CMISQL query from there, it always retrieves one folder, which is right. So, it must be our code, or an OpenCMIS bug...
Any ideas?
I can't reproduce this behavior. It's running fine against http://cmis.alfresco.com . The issue https://issues.alfresco.com/jira/browse/ALF-2859 states that there have been bug fixes. Are you running the latest Alfresco version?
Florian

How do I create a unit test that updates a record into database in asp.net

How do I create a unit test that updates a record into database in asp.net
While technically we don't call this a 'unit test', but an 'integration test' (as Oded explained), you can do this by using a unit testing framework such as MSTest (part of Visual Studio 2008/2010 professional) or one of the free available unit testing frameworks, such as NUnit.
However, testing an ASP.NET web project is usually pretty hard, especially when you've put all you logic inside web pages. Best thing to do is to extract all your business logic to a separate layer (usually a separate project within your solution) and call that logic from within your web pages. But perhaps you’ve already got this separation, which would be great.
This way you can also call this logic from within your tests. For integration tests, it is best to have a separate test database. A test database must contain a known (and stable) set of data (or be completely empty). Do not use a copy of your production database, because when data changes, your tests might suddenly fail. Also you should make sure that all changes in the database, made by an integration test, should be rolled back. Otherwise, the data in your test database is constantly changing, which could cause your tests to suddenly fail.
I always use the TransactionScope in my integration tests (and never in my production code). This ensures that all data will be rolled back. Here is an example of what such an integration test might look like, while using MSTest:
[TestClass]
public class CustomerMovedCommandTests
{
// This test test whether the Execute method of the
// CustomerMovedCommand class in the business layer
// does the expected changes in the database.
[TestMethod]
public void Execute_WithValidAddress_Succeeds()
{
using (new TransactionScope())
{
// Arrange
int custId = 100;
using (var db = new ContextFactory.CreateContext())
{
// Insert customer 100 into test database.
db.Customers.InsertOnSubmit(new Customer()
{
Id = custId, City = "London", Country = "UK"
});
db.SubmitChanges();
}
string expectedCity = "New York";
string expectedCountry = "USA";
var command = new CustomerMovedCommand();
command.CustomerId = custId;
command.NewAddress = new Address()
{
City = expectedCity, Country = expectedCountry
};
// Act
command.Execute();
// Assert
using (var db = new ContextFactory.CreateContext())
{
var c = db.Customers.Single(c => c.Id == custId);
Assert.AreEqual(expectedCity, c.City);
Assert.AreEqual(expectedCountry, c.Country);
}
} // Dispose rolls back everything.
}
}
I hope this helps, but next time, please be a little more specific in your question.

Resources