CPU getting choked when below code is executed - performance

public bool CheckIfValidSignedPdfExists(string fileServerPath, int memberagreementId)
{
var filePaths = Directory.GetFiles(fileServerPath);
if (filePaths.Length < 2)
{
return false;
}
var fileInfo = new List<FileInfo>();
foreach (var path in filePaths)
{
if (File.Exists(path))
fileInfo.Add(new FileInfo(path));
}
if (fileInfo.Count < 2)
return false;
else
{
fileInfo = fileInfo.OrderByDescending(x => x.LastWriteTimeUtc).Take(2).ToList();
//Rules: 1. Name 2.size 3. Last write time 4. Extension
var firstPdf = fileInfo.FirstOrDefault();
var lastPdf = fileInfo.LastOrDefault();
var firstFileNameCheck = string.Concat(Convert.ToString(memberagreementId), ".pdf");
var lastFileNameCheck = lastPdf.Name.StartsWith(Convert.ToString(memberagreementId) + "-")
&& lastPdf.Name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase);
if ((firstPdf.Name.Equals(firstFileNameCheck, StringComparison.OrdinalIgnoreCase)) &&
(lastFileNameCheck) && (firstPdf.Length > lastPdf.Length) && (firstPdf.LastWriteTimeUtc >= lastPdf.LastWriteTimeUtc))
return true;
else
return false;
}
}
When this piece of code is running, we can see the cpu spike and the thread always relate to the above code.
HIGH CPU Thread Code
CPU Spike
We are not sure what wrong we are doing in this code which is causing this issue.

Related

Spring GCP - Datastore performance: Batch processing, iteration through all entity list is very slow

Following code is work really slow, almost 30 second to process 400 entities:
int page = 0;
org.springframework.data.domain.Page<MyEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAll(PageRequest.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAll(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp(SApplication.NAME_XXX));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
I use following instead, 4-6 sec per 400 entities (gcp lib to work with datastore)
Datastore service = DatastoreOptions.getDefaultInstance().getService();
StructuredQuery.Builder<?> query = Query.newEntityQueryBuilder();
int limit = 400;
query.setKind("ENTITY_KIND").setLimit(limit);
int count = 0;
Cursor cursor = null;
while (true) {
if (cursor != null) {
query.setStartCursor(cursor);
}
QueryResults<?> queryResult = service.run(query.build());
List<Entity> entityList = new ArrayList<>();
while (queryResult.hasNext()) {
Entity loadEntity = (Entity) queryResult.next();
Entity.Builder newEntity = Entity.newBuilder(loadEntity).set("app", SApplication.NAME_XXX.name());
entityList.add(newEntity.build());
}
service.put(entityList.toArray(new Entity[0]));
count += entityList.size();
if (entityList.size() == limit) {
cursor = queryResult.getCursorAfter();
} else {
break;
}
LOGGER.info("Processed: {}", count);
}
Why I can't use spring to do that batch processing?
Full discussion here: https://github.com/spring-cloud/spring-cloud-gcp/issues/1824
First:
you need to use correct lib version: at least 1.2.0.M2
Second:
you need to implement new method in repository interface:
#Query("select * from your_kind")
Slice<TestEntity> findAllSlice(Pageable pageable);
Final code looks like:
LOGGER.info("start");
int page = 0;
Slice<TestEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAllSlice(DatastorePageable.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAllSlice(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp("xx"));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
LOGGER.info("end");

In Boomla, how can I easily find the next sibling of a file

I'm quite used to nextSiblingand nextElementSibling in the DOM. Is there an easy way of doing a similar thing with Boomla files?
I would need the next sibling within the same placeholder (and null if this is the last), but I'd be interested about finding the next sibling in any placeholder (and null if this is the last file in the last placeholder).
Currently, there is no built-in method for this.
Here are 2 methods for the sjs-4 engine for getting the next in the placeholder or parent:
var nextInBucket = function(f) {
var bucket = f.bucketId();
var bucketSiblings = f.query("../:" + bucket);
var path = f.path();
var index = 0;
var found = false;
bucketSiblings.each(function(t) {
if (t.path() == path) {
found = true;
return false;
}
index++;
});
if ( ! found) {
return null;
}
return bucketSiblings.eq(index + 1);
}
var nextInParent = function(f) {
var parentChildren = f.query("../*");
var path = f.path();
var index = 0;
var found = false;
parentChildren.each(function(t) {
if (t.path() == path) {
found = true;
return false;
}
index++;
});
if ( ! found) {
return null;
}
return parentChildren.eq(index + 1);
}

My program runs out of memory (Stack overflow) 9 out of 10 times. But where is the issue in my algorithm?

I've made the following program to simulate the classic card game "War". But when I try to run it, it experiences stack overflow. Why? I thought my algorithm was as effective as it could be. Another weird thing that happens is that 1 out of 10 times the program will finish, returning a VERY low vale for the round count (around 26). The code is as follows:
Firstly, I have a class named Card.
package {
public class Card {
public var cardName:String;
public var suit:String;
public var number:int;
public function Card() {
}
}
}
Then I have the following code:
import flash.utils.getDefinitionByName;
var cardDeck:Array = new Array();
var suits:Array = new Array();
suits = ["Hearts", "Clubs", "Spades", "Diamonds"];
for each (var suit in suits)
{
for (var a = 1; a <= 13; a++)
{
var card:Card = new Card();
card.cardName = suit + a;
card.number = a;
card.suit = suit;
cardDeck.push(card);
}
}
var shuffledCardDeck:Array = new Array();
var randomPos:int = 0;
for (var b = 0; b < 52; b++) {
randomPos = Math.random()*cardDeck.length;
shuffledCardDeck[b] = cardDeck[randomPos];
cardDeck.splice(randomPos, 1);
}
var handOne:Array = new Array();
var handTwo:Array = new Array();
for (var c = 0; c < 26; c++) {
handOne.push(shuffledCardDeck[c]);
}
for (var d = 26; d < 52; d++) {
handTwo.push(shuffledCardDeck[d]);
}
var roundCount:int;
round();
function round() {
roundCount+=1;
var cardOne:Card = handOne[0];
var cardTwo:Card = handTwo[0];
if (cardOne.number < cardTwo.number) {
// Player two wins
handTwo.push(cardOne);
handOne.splice(0, 1);
} else if (cardOne.number > cardTwo.number) {
// Player one wins
handOne.push(cardTwo);
handTwo.splice(0, 1);
} else {
// Draw
handOne.splice(0,1)
handOne.push(cardOne);
handTwo.splice(0,1)
handTwo.push(cardTwo);
}
if (handOne.length == 0 || handTwo.length == 0) {
trace("Good game")
} else {
round();
}
}
trace(roundCount);
Flash runtime’s maximum recursion limit is default 1000, but can be set via the compiler argument default-script-limits. Instead of just recursion, call the function in an interval to prevent such stack overflow. It will be helpful even when you decide to show visually the process to the gamers.
setTimeout(round,50); //in place of round();
Source: http://www.designswan.com/archives/as3-recursive-functions-vs-loop-functions.html

Process gets stuck in oSession.Logoff()

Pstcreation works properly with outlook installed.
Now, I am trying to create a pst file with standalone version of MAPI . But my process is stuck in oSession.LogOff(). Further if a comment that oSession.LogOff() line and subsequently call the CreatePstWithRedemption function to create an other pst, the process gets stuck in oSession.LogonPstStore
private bool CreatePstWithRedemption(EmailJTableArgs objJTablArgs, EmailFilterArgs objFilterArgs,
EmailExportRequestParams emailExportRequestParams)
{
RDOSession oSession = null;
IRDOStore store = null;
RDOFolder fFOlder = null;
RDOFolder childFolder = null;
IRDOItems folderItems = null;
var pstCreationStatus = false;
try
{
oSession = new RDOSession();
store = oSession.LogonPstStore(_fileName, 1, "PST");
var folderName = Path.GetFileNameWithoutExtension(_fileName);
if (store != null)
{
fFOlder = store.IPMRootFolder;
foreach (RDOFolder folder in fFOlder.Folders)
{
folder.Delete();
}
childFolder = fFOlder.Folders.Add(folderName, Type.Missing);
folderItems = childFolder.Items;
var resultOfGetEmails = new ResultGetEmails();
resultOfGetEmails.TotalCount = -1;
do
{
var journalEmails = GetEmailList(objFilterArgs, objJTablArgs, emailExportRequestParams,
resultOfGetEmails);
for (var i = 0; i < journalEmails.Count; i++)
{
IRDOMail mail = null;
try
{
mail = folderItems.Add(rdoItemType.olMailItem);
// populate mail fields
mail.Sent = true;
mail.Save();
}
finally
{
if (mail != null)
Marshal.ReleaseComObject(mail);
}
}
resultOfGetEmails.TotalCount -= BatchSize;
objJTablArgs.PageStartIndex += BatchSize;
} while (resultOfGetEmails.TotalCount > 0);
pstCreationStatus = true;
}
}
finally
{
// Do cleanup
if (oSession != null && oSession.LoggedOn)
{
try
{
oSession.Logoff();
Marshal.ReleaseComObject(oSession);
}
catch
{
}
}
}
return pstCreationStatus;
}
Note: The same thing works well when run in an environment where outlook is installed.

Ace Editor: Lock or Readonly Code Segment

Using the Ace Code Editor can I lock or make readonly a segment of code but still allow other lines of code to be written or edited during a session?
Here is the start of a solution:
$(function() {
var editor = ace.edit("editor1")
, session = editor.getSession()
, Range = require("ace/range").Range
, range = new Range(1, 4, 1, 10)
, markerId = session.addMarker(range, "readonly-highlight");
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
if (intersects(range)) {
return {command:"null", passEvent:false};
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
range.start = session.doc.createAnchor(range.start);
range.end = session.doc.createAnchor(range.end);
range.end.$insertRight = true;
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
if (intersects(range)) return;
next();
}
});
see it working in this fiddle: http://jsfiddle.net/bzwheeler/btsxgena/
The major working pieces are:
create start and end ace anchors which track the location of a 'readonly' portion as the document around it changes.
create a range to encapsulate the anchors
add a custom keyhandler to check if the current impending keypress will affect the readonly range and cancel it if so.
add custom paste/cut handlers to protect against right-click menu and browser menu cut/paste actions
You can do it by listening to the exec events:
// Prevent editing first and last line of editor
editor.commands.on("exec", function(e) {
var rowCol = editor.selection.getCursor();
if ((rowCol.row === 0) || ((rowCol.row + 1) === editor.session.getLength())) {
e.preventDefault();
e.stopPropagation();
}
});
Source: https://jsfiddle.net/tripflex/y0huvc1b/
I suggest something else easier and more reliable to prevent range to be modified (check it!)
var old$tryReplace = editor.$tryReplace;
editor.$tryReplace = function(range, replacement) {
return intersects(range)?null:old$tryReplace.apply(this, arguments);
}
var session = editor.getSession();
var oldInsert = session.insert;
session.insert = function(position, text) {
return oldInsert.apply(this, [position, outsideRange(position)?text:""]);
}
var oldRemove = session.remove;
session.remove = function(range) {
return intersects(range)?false:oldRemove.apply(this, arguments);
}
var oldMoveText = session.moveText;
session.moveText = function(fromRange, toPosition, copy) {
if (intersects(fromRange) || !outsideRange(toPosition)) return fromRange;
return oldMoveText.apply(this, arguments)
}
outsideRange = function (position) {
var s0 = range.start;
if (position.row < s0.row || (position.row == s0.row && position.column <= s0.column)) return true; // position must be before range.start
var e0 = range.end;
if (position.row > e0.row || (position.row == e0.row && position.column >= e0.column)) return true; // or after range.end
return false;
}
intersects = function(withRange) {
var e = withRange.end, s0 = range.start, s = withRange.start, e0 = range.end;
if (e.row < s0.row || (e.row == s0.row && e.column <= s0.column)) return false; // withRange.end must be before range.start
if (s.row > e0.row || (s.row == e0.row && s.column >= e0.column)) return false; // or withRange.start must be after range.end
return true;
}

Resources