Regex TypeError: Cannot read property '1' of null - angular-ui-bootstrap

My datepicker regular expression is trying matches on a null aray. How do I fix it? Not sure what clazz should equal if the array is null. I'm thinking a simple if (matches[1]) { etc } but I'm not sure what to do if matches is null. Clazz is used elsewhere twice in the code. Do I just set clazz to null or zero?
var matches = exp.match(IS_REGEXP);
var clazz = scope.$eval(matches[1]);
Edit: Here's where they use clazz
if (data.lastActivated !== newActivated) {
if (data.lastActivated) {
$animate.removeClass(data.lastActivated.element, clazz);
}
if (newActivated) {
$animate.addClass(newActivated.element, clazz);
}
data.lastActivated = newActivated;
}
Here's IS_REGEXP
11111111 22222222
var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;
Double Edit:
Here's the whole function
function addForExp(exp, scope) {
var matches = exp.match(IS_REGEXP);
var clazz = scope.$eval(matches[1]);
var compareWithExp = matches[2];
var data = expToData[exp];
if (!data) {
var watchFn = function(compareWithVal) {
var newActivated = null;
instances.some(function(instance) {
var thisVal = instance.scope.$eval(onExp);
if (thisVal === compareWithVal) {
newActivated = instance;
return true;
}
});
if (data.lastActivated !== newActivated) {
if (data.lastActivated) {
$animate.removeClass(data.lastActivated.element, clazz);
}
if (newActivated) {
$animate.addClass(newActivated.element, clazz);
}
data.lastActivated = newActivated;
}
};
expToData[exp] = data = {
lastActivated: null,
scope: scope,
watchFn: watchFn,
compareWithExp: compareWithExp,
watcher: scope.$watch(compareWithExp, watchFn)
};
}
data.watchFn(scope.$eval(compareWithExp));
}

Setting clazz to null or empty string shall do, if clazz is all your concern.
var clazz = matches ? scope.$eval(matches[1]) : '';
But with compareWithExp, it might be better to exit from the whole logic when there is no match:
if ( ! matches ) return;

Related

Getting same Current and Original value of change tracker modified state

Below is my override saveChanges Methed which calls SetChanges Method
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
SetChanges();
OnBeforeSaving();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
Right now, Sometimes code works completely fine but in some scenario It gives same value of both property.OriginalValue and property.CurrentValue for Modification so I am not able find what is the issue in my code
private void SetChanges()
{
Guid SystemLogId = Guid.NewGuid();
var currentDate = DateTime.Now;
var entitiesTracker = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified || p.State == EntityState.Added).ToList();
foreach (var entry in entitiesTracker)
{
var pagename = entry.Entity.GetType().Name;
if (pagename != "ExceptionLog")
{
var rowid = 0;
try
{
rowid = int.Parse(entry.OriginalValues["Id"].ToString());
}
catch (Exception)
{ }
SystemLog sysLog = new SystemLog();
List<SystemChangeLog> changeLog = new List<SystemChangeLog>();
foreach (PropertyEntry property in entry.Properties)
{
string propertyName = property.Metadata.Name;
switch (entry.State)
{
case EntityState.Added:
sysLog.Event = "Created";
break;
case EntityState.Modified:
{
sysLog.Event = "Updated";
if (propertyName != "ModifiedDate" && propertyName != "CreatedDate" && propertyName != "ModifiedBy" && propertyName != "CreatedBy" && propertyName != "RowVersion")
{
var original = Convert.ToString(property.OriginalValue);
var current = Convert.ToString(property.CurrentValue);
if (property.IsModified && !original.Equals(current))
{
SystemChangeLog log = new SystemChangeLog()
{
Property = propertyName,
OldValue = original,
NewValue = current,
DateOfChange = currentDate,
rowid = rowid,
SystemLogId = SystemLogId.ToString(),
};
changeLog.Add(log);
}
}
}
break;
}
}
base.Set<SystemChangeLog>().AddRange(changeLog);
if(changeLog.Count() >0 || entry.State == EntityState.Added)
{
sysLog.UserId = UserId;
sysLog.Date = currentDate;
sysLog.Page = pagename;
sysLog.Location = ExceptionHandler(entry, "Location");
sysLog.IPAddress = ExceptionHandler(entry, "IPAddress");
sysLog.MACAddress = ExceptionHandler(entry, "MACAddress");
sysLog.SystemLogId = SystemLogId.ToString();
base.Set<SystemLog>().Add(sysLog);
}
}
}
}
And also Is there any way to make it fast for more than thousand entry
hope below code can help:
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
setChanges(); // to get new value and old value
var result = base.SaveChanges(acceptAllChangesOnSuccess);
OnAfterSaveChanges();// to get auto added id
return result;
}

how to save list of data in memory?

I have an ajax function which is called by the jquery-datatable and ve two responsibility.
To get data from the database.
To serve the search, sort, pagination like functional work.
Now all I need is I just wanna get data once and save it in memory so that when user type something in the search box it performs the search from stored data directly.
Here the code.
public ActionResult AjaxOil(JQueryDataTableParamModel param)
{
//To get data and should be run only once.
IEnumerable<Oil> allOils = _context.Oils.ToList();
//All others function.
IEnumerable<Oil> filteredOils;
if (!string.IsNullOrEmpty(param.sSearch))
{
filteredOils = allOils
.Where(c => c.CommonName.Contains(param.sSearch)
||
c.BotanicalName.Contains(param.sSearch)
||
c.PlantParts.Contains(param.sSearch)
||
c.Distillation.Contains(param.sSearch));
}
else
{
filteredOils = allOils;
}
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<Oil, string> orderingFunction = (c => sortColumnIndex == 1 ? c.CommonName :
sortColumnIndex == 2 ? c.BotanicalName :
c.PlantParts);
var distillationFilter = Convert.ToString(Request["sSearch_4"]);
var commonFilter = Convert.ToString(Request["sSearch_1"]);
var botanicalFilter = Convert.ToString(Request["sSearch_2"]);
var plantFilter = Convert.ToString(Request["sSearch_3"]);
if (!string.IsNullOrEmpty(commonFilter))
{
filteredOils = filteredOils.Where(c => c.CommonName.Contains(commonFilter));
}
if (!string.IsNullOrEmpty(botanicalFilter))
{
filteredOils = filteredOils.Where(c => c.BotanicalName.Contains(botanicalFilter));
}
if (!string.IsNullOrEmpty(plantFilter))
{
filteredOils = filteredOils.Where(c => c.PlantParts.Contains(plantFilter));
}
if (!string.IsNullOrEmpty(distillationFilter))
{
filteredOils = filteredOils.Where(c => c.Distillation.Contains(distillationFilter));
}
var sortDirection = Request["sSortDir_0"];
if (sortDirection == "asc")
filteredOils = filteredOils.OrderBy(orderingFunction);
else
filteredOils = filteredOils.OrderByDescending(orderingFunction);
var displayedOils = filteredOils
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength);
var result = from c in displayedOils
select new[] { Convert.ToString(c.OilId), c.CommonName, c.BotanicalName, c.PlantParts, c.Distillation };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allOils.Count(),
iTotalDisplayRecords = filteredOils.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
On first load save the data in cache/session/static field. On next search check if the cache/session/static field is not null and read from there, not from db, else take again from db..
Example:
private static ObjectCache _cache = new MemoryCache("MemoryCache");
public List<Oils> GetDataFromCache(string keyName)
{
//private static ObjectCache _cache = new MemoryCache("keyName");
var data = _cache.Get(keyName);
if (data != null) return data as List<Oils>;
data = _context.Oils.ToList();
//keep the cache for 2h
_cache.Add(keyName, data, DateTimeOffset.Now.AddHours(2));
return data;
}
(didn't test the code, but that's the logic) or you can use Session if you prefer
Session example:
if(Session["Data_Oils"] != null) { return Session["Data_Oils"] as List<Oils; } else { var temp = _context.Oils.ToList(); Session["Data_Oils"] = temp; return temp; }

What will be the time complexity of reversing the linked list in a different way using below code?

Given a linked List $link1, with elements (a->b->c->d->e->f->g->h->i->j), we need to reverse the linked list provided that the reversing will be done in a manner like -
Reverse 1st element (a)
Reverse next 2 elements (a->c->b)
Reverse next 3 elements (a->c->b->f->e->d)
Reverse next 4 elements (a->c->b->f->e->d->j->i->h->g)
....
....
I have created below code in PHP to solve this problem
Things I need -
I need to calculate the time complexity of reverseLinkedList function below.
Need to know if we can optimize reverseLinkedList function to reduce time complexity.
-
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function read_node()
{
return $this->data;
}
}
class LinkList
{
private $first_node;
private $last_node;
private $count;
function __construct()
{
$this->first_node = NULL;
$this->last_node = NULL;
$this->count = 0;
}
function size()
{
return $this->count;
}
public function read_list()
{
$listData = array();
$current = $this->first_node;
while($current != NULL)
{
echo $current->read_node().' ';
$current = $current->next;
}
}
public function reverse_list()
{
if(($this->first_node != NULL)&&($this->first_node->next != NULL))
{
$current = $this->first_node;
$new = NULL;
while ($current != NULL)
{
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->first_node = $new;
}
}
public function read_node($position)
{
if($position <= $this->count)
{
$current = $this->first_node;
$pos = 1;
while($pos != $position)
{
if($current->next == NULL)
return null;
else
$current = $current->next;
$pos++;
}
return $current->data;
}
else
return NULL;
}
public function insert($data)
{
$new_node = new ListNode($data);
if($this->first_node != NULL)
{
$this->last_node->next = $new_node;
$new_node->next = NULL;
$this->last_node = &$new_node;
$this->count++;
}
else
{
$new_node->next = $this->first_node;
$this->first_node = &$new_node;
if($this->last_node == NULL)
$this->last_node = &$new_node;
$this->count++;
}
}
}
//Create linked list
$link1 = new LinkList();
//Insert elements
$link1->insert('a');
$link1->insert('b');
$link1->insert('c');
$link1->insert('d');
$link1->insert('e');
$link1->insert('f');
$link1->insert('g');
$link1->insert('h');
$link1->insert('i');
$link1->insert('j');
echo "<b>Input :</b><br>";
$link1->read_list();
//function to reverse linked list in specified manner
function reverseLinkedList(&$link1)
{
$size= $link1->size();
if($size>2)
{
$link2=new LinkList();
$link2->insert($link1->read_node(1));
$elements_covered=1;
//reverse
$rev_size=2;
while($elements_covered<$size)
{
$start=$elements_covered+1;
$temp_link = new LinkList();
$temp_link->insert($link1->read_node($start));
for($i=1;$i<$rev_size;$i++)
{
$temp_link->insert($link1->read_node(++$start));
}
$temp_link->reverse_list();
$temp_size=$temp_link->size();
$link2_size=$link2->size();
for($i=1;$i<=$temp_size;$i++)
{
$link2->insert($temp_link->read_node($i));
++$elements_covered;
++$link2_size;
}
++$rev_size;
}
///reverse
//Flip the linkedlist
$link1=$link2;
}
}
///function to reverse linked list in specified manner
//Reverse current linked list $link1
reverseLinkedList($link1);
echo "<br><br><b>Output :</b><br>";
$link1->read_list();
It's O(n)...just one traversal.
And secondly, here tagging it in language is not necessary.
I have provided a Pseudocode here for your reference:
current => head_ref
prev => NULL;
current => head_ref;
next => null;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;

WrongExpectedVersionException on EventStore Getting started project

I have re-written the getting-started-with-event-store project to learn what's going on and now for the test CanSaveExistingAggregate() I am getting a WrongExpectedVersionException. The thing is, in order to try and work out what's going on I would like to know what the expected version should be, how can I find this out? In the test, the line repository.Save(firstSaved, Guid.NewGuid(), d => { }); calculates the expected version as 101 and this is where it fails:
[Test]
public void CanSaveExistingAggregate()
{
var savedId = SaveTestAggregateWithoutCustomHeaders(repository, 100 /* excludes TestAggregateCreated */);
var firstSaved = repository.GetById<TestAggregate>(savedId);
Console.WriteLine("version:" + firstSaved.Id);
firstSaved.ProduceEvents(50);
repository.Save(firstSaved, Guid.NewGuid(), d => { });
var secondSaved = repository.GetById<TestAggregate>(savedId);
Assert.AreEqual(150, secondSaved.AppliedEventCount);
}
And the code where the exception is thrown:
public void Save(CommonDomain.IAggregate aggregate, Guid commitId, Action<IDictionary<string, object>> updateHeaders)
{
var commitHeaders = new Dictionary<string, object>
{
{CommitIdHeader, commitId},
{AggregateClrTypeHeader, aggregate.GetType().AssemblyQualifiedName}
};
updateHeaders(commitHeaders);
var streamName = aggregateIdToStreamName(aggregate.GetType(), aggregate.Id);
var newEvents = aggregate.GetUncommittedEvents().Cast<object>().ToList();
var originalVersion = aggregate.Version - newEvents.Count;
var expectedVersion = originalVersion == 0 ? ExpectedVersion.NoStream : originalVersion;
var eventsToSave = newEvents.Select(e => ToEventData(Guid.NewGuid(), e, commitHeaders)).ToList();
if (eventsToSave.Count < WritePageSize)
{
eventStoreConnection.AppendToStream(streamName, expectedVersion, eventsToSave);
}
else
{
var transaction = eventStoreConnection.StartTransaction(streamName, expectedVersion);
var position = 0;
while (position < eventsToSave.Count)
{
var pageEvents = eventsToSave.Skip(position).Take(WritePageSize);
transaction.Write(pageEvents);
position += WritePageSize;
}
transaction.Commit();
}
aggregate.ClearUncommittedEvents();
}
All the other tests pass (except ThrowsOnGetDeletedAggregate() but I'll ask about that later) but I think this is the only test that has expectedVersion != ThrowsOnGetDeletedAggregate()
Well it turns out it was just a mistake when writing the code, rather than
var expectedVersion = originalVersion == 0 ? ExpectedVersion.NoStream : originalVersion;
it should be
var expectedVersion = originalVersion == 0 ? ExpectedVersion.NoStream : originalVersion - 1;

calling a trim method in actionscript 2.0

Hi I Got a notnull function for a text field as below
private function valStringNotNull( val:String ) :Boolean
{
if ( String(val).length <= 0 )
{
_errorCode = "StringNull";
return false;
}
_errorCode = "NoError";
return true;
}
and this function is being called here
var pCnt:Number = 0;
_validateParams[pCnt++] = { type: "notNull", input: win.firstNameInput , isSendData:true, dataName:"firstName"};
_validateParams[pCnt++] = { type: "notNull", input: win.lastNameInput, isSendData:true, dataName:"lastName"};
_validateParams[pCnt++] = { type: "noValidation", input: roleCombo, isSendData:true, dataName:"role" };
Selection.setFocus(win.firstNameInput);
and for the not null I defined this way
private function validateCases ( param:Object ) :Boolean
{
_errorObj = param.input || param.input1;
switch( param.type )
{
case "notNull":
return valStringNotNull( param.input.text );
break;
}
}
but as you see as I defined the length should be greater than zero its taking even a space as an input and displaying blank white space in my text field so I got a trim function as below
public function ltrim(input:String):String
{
var size:Number = input.length;
for(var i:Number = 0; i < size; i++)
{
if(input.charCodeAt(i) > 32)
{
return input.substring(i);
}
}
return "";
}
and I need to call this trim function before my not null function so that it trims off all the leftside white space but as I am very new to flash can some one help me how to keep this trim function before the notnull function.Can some one please help me with this please
A function to replace any string as you wish, just combine them!
String.prototype.replace = function(searchStr, replaceStr):String
{
return this.split(searchStr).join(replaceStr);
};
Example:
// initial string with a placeholder
var str:String = '$person is welcome';
// replace $person with 'Flash developer' and trace it
var replacedStr:String = str.replace('$person','Flash developer');
trace(replacedStr);
Why not just change valStringNotNull() as follows?
private function valStringNotNull( val:String ) :Boolean
{
if ( String(ltrim(val)).length <= 0 )
{
_errorCode = "StringNull";
return false;
}
_errorCode = "NoError";
return true;
}

Resources