CoffeeScript set property in Class during callback - coffeescript

Here is my CoffeeScript class
class HotsauceQS
err: null
constructor: (#obj, #qUrl) ->
sendMsg: ->
sqs.sendMessage
MessageBody: JSON.stringify(#obj)
QueueUrl: #qURL
, #handleResponse
handleResponse: (err, data) =>
#err = err if err?
module.exports = HotsauceQS
I can't get the #err property to set:
h = require('./hotsaucesqs')
m = new h obj, url
m.sendMsg()
console.log m.err # this is undefined :(

Related

Linq EF --> Contains condition does not work

I have a problem: I have this table
ID
Title
GenreID
Genre
Duration
1
Movie1
1,2
Cartoon, Family
80
2
Movie2
3,4
Horror, Drama
76
3
Movie3
4
Drama
110
4
Movie4
1,2
Cartoon, Family
200
I need to filter by Genre, I make my query in this way, For example if I want all movies with Genre Cartoon (2), I make:
request.genre = 2
var query1 = from q in Movies
select new Response.MovieResponse
{
MovieId = q.MovieId,
Name = q.Title,
Genres = q.Genre,
GenreIds = q.GenreID
};
if (request != null)
{
if (!string.IsNullOrEmpty(request.Title))
query1 = query1.Where(co => co.Name.StartsWith(request.name));
if (!string.IsNullOrEmpty(request.genre))
if (int.Parse(request.genre) > 0)
{
query1.AsEnumerable().Where(ca =>
request.genre .Any(x => ca.GenreIds.Contains(x)));
}
}
List<Response.StoreResponse> stores = new List<Response.StoreResponse>();
stores = await query1.ToListAsync();
I expected 2 records inside but the filter on genre does not work. I always have back all movies. The filter by title run
I tried
if (!string.IsNullOrEmpty(request.category))
if (int.Parse(request.category) > 0)
{
string[] cat = { request.category };
var q1 = query1.Where(ca => ca.CategoriesIds.Contains(cat.ToString()));
l = q1.ToList();
}
but I have error:
The LINQ expression 'DbSet<Store>()
.Join(
inner: DbSet<Country>(),
outerKeySelector: s => s.CountryId,
innerKeySelector: c => (Nullable<int>)c.CountryId,
resultSelector: (s, c) => new TransparentIdentifier<Store, Country>(
Outer = s,
Inner = c
))
.Join(
inner: DbSet<City>(),
outerKeySelector: ti => ti.Outer.CityId,
innerKeySelector: c0 => (Nullable<long>)c0.CityId,
resultSelector: (ti, c0) => new TransparentIdentifier<TransparentIdentifier<Store, Country>, City>(
Outer = ti,
Inner = c0
))
.Where(ti0 => ti0.Outer.Outer.StatusId == (Nullable<int>)2)
.Where(ti0 => DbSet<Operator>()
.Where(o => EF.Property<Nullable<Guid>>(ti0.Outer.Outer, "StoreId") != null && object.Equals(
objA: (object)EF.Property<Nullable<Guid>>(ti0.Outer.Outer, "StoreId"),
objB: (object)EF.Property<Nullable<Guid>>(o, "StoreId")))
.Count() > 0)
.Where(ti0 => string.Join<long>(
separator: ",",
values: DbSet<StoresCategory>()
.Where(s0 => EF.Property<Nullable<Guid>>(ti0.Outer.Outer, "StoreId") != null && object.Equals(
objA: (object)EF.Property<Nullable<Guid>>(ti0.Outer.Outer, "StoreId"),
objB: (object)EF.Property<Nullable<Guid>>(s0, "StoreId")))
.Select(s0 => s0.CategoryId)
.ToList()).Contains(__ToString_0))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Entity Framework Core: combining multiple result objects into one collection

I am facing this linq query for entity framework core (2.0).
var result = await dbContext.Table1DbSet
.Where(t1e => t1e.Id == id && t1e.Id2 == id2)
.Select
(
t1e =>
t1e.Table2NavPropICollection.Select
(
t2e => new
{
singleObject = t2e.Table3NavPropObject.TargetObject,
enumerable1 = t2e.Table3NavPropObject.Table4NavPropObject.Table5NavPropICollection.Select(t5e => t5e.TargetObject),
enumerable2 = t2e.Table3NavPropObject.Table6NavPropObject.Table7NavPropICollection.Select(t7e => t7e.TargetObject),
enumerable3 = t2e.Table3NavPropObject.Table8NavPropICollection.SelectMany(t8e => t8e.Table9NavPropICollection.Select(t9e => t9e.TargetObject))
}
)
)
.ToListAsync();
The goal is to query all the referenced instances of TargetObject which is referenced accros ~ 10 different tables.
Currently it returns an IEnumerable where the anonymous object contains the properties singleObject, enumerable1, enumerable2, enumerable3. All those properties are of type TargetObject or IEnumerable.
Can I, and how, rewrite the query to not return anonymous objects but just an IEnumerable containing all the values?
For some reason the compiler won't let me iterate over the anonymous collection and flatten it manually.
This should do the trick if you want one array per t1e row.
var result = await dbContext.Table1DbSet
.Where(t1e => t1e.Id == id && t1e.Id2 == id2)
.Select
(
t1e =>
t1e.Table2NavPropICollection.Select
(
t2e => new[] {t2e.Table3NavPropObject.TargetObject}.Concat(
t2e.Table3NavPropObject.Table4NavPropObject.Table5NavPropICollection.Select(t5e => t5e.TargetObject)).Concat(
t2e.Table3NavPropObject.Table6NavPropObject.Table7NavPropICollection.Select(t7e => t7e.TargetObject)).Concat(
t2e.Table3NavPropObject.Table8NavPropICollection.SelectMany(t8e => t8e.Table9NavPropICollection.Select(t9e => t9e.TargetObject)))
)
)
.ToListAsync();
If you want it completely flat, you'll want to switch that Select to a SelectMany().
var result = await dbContext.Table1DbSet
.Where(t1e => t1e.Id == id && t1e.Id2 == id2)
.SelectMany
(
t1e =>
t1e.Table2NavPropICollection.Select
(
t2e => new[] {t2e.Table3NavPropObject.TargetObject}.Concat(
t2e.Table3NavPropObject.Table4NavPropObject.Table5NavPropICollection.Select(t5e => t5e.TargetObject)).Concat(
t2e.Table3NavPropObject.Table6NavPropObject.Table7NavPropICollection.Select(t7e => t7e.TargetObject)).Concat(
t2e.Table3NavPropObject.Table8NavPropICollection.SelectMany(t8e => t8e.Table9NavPropICollection.Select(t9e => t9e.TargetObject)))
)
)
.ToListAsync();
Is Add and/or Concat a possible solution?
PoC:
var a = new [] { 1,2,3 };
var result = new {
firstA = a.First(),
otherAs = a,
backwards = a.Reverse()
};
var final = new List<int>();
final.Add(result.firstA);
final.Concat(result.otherAs.Concat(result.backwards))
.Dump();

ionic 2 global variable

I have a function, and in this function I have:
this.geolocation.getCurrentPosition(posOptions).then((localisation,err) => {
this.storage.get('param1').then((param1) => {
this.storage.get('param2').then((param2) => {
// Do some stuff with localisation, param1 & param2
alert(localisation);
alert(param1);
alert(param2);
})
})
})
That's the only way i found to use "localisation", "param1" & "param2" in the same time, if i do something like:
this.geolocation.getCurrentPosition(posOptions).then((localisation,err) => {
})
this.storage.get('param1').then((param1) => {
})
this.storage.get('param2').then((param2) => {
// Do some stuff with localisation, param1 & param2
alert(localisation);
alert(param1);
alert(param2);
})
It will not find localisation and param1
You can use promise.all here since the params are not interdependant. Promise.all takes in an array of promises and waits till all the promises return before executing the then.
let lPromise =this.geolocation.getCurrentPosition(posOptions);
let p1Promise = this.storage.get('param1');
let p2Promise = this.storage.get('param2');
Promise.all([lPromise,p1Promise,p2Promise])
.then((values) => {
// Do some stuff with localisation, param1 & param2
alert(values[0]);//localization
alert(values[1]);//param1
alert(values[2]);//param2
})

Anonymous function works as callback but defined function does not

I have a module that looks like this:
module.exports = AtomMarkdownLabels =
# other stuff here
file_changed_added: (file_path) =>
fs.readFile file_path, 'utf-8', #process_yaml
console.log 'file changed'
process_yaml: (err, data) =>
console.log "process_yaml is called"
I know file_changed_added is being called from some other function and I'm seeing the "file changed" output in the console, but process_yaml isn't if I change file_changed_added to
file_changed_added: (file_path) =>
fs.readFile file_path, 'utf-8', (err, data) =>
console.log "test"
console.log 'file changed'
I see both "test" and "file changed" being called properly. What could be going on?
=> has two slightly different purposes:
When defining a named function (f = => ...) or anonymous function f(x, => ...)), => simply ensures that # inside the function is that same as # in the surrounding context.
When defining a method in a class:
class C
m: => ...
=> ensures that # inside m will be the instance of C.
Both uses are creating a bound function but they're binding to different things.
You're using this structure:
obj =
func: =>
# ...
That's equivalent to this:
f = =>
# ...
obj =
func: f
because you're using a plain old object rather than a class. So what is # outside your AtomMarkdownLabels definition? # won't be anything useful and in particular, it won't be your AtomMarkdownLabels object and it won't have a process_yaml property so #process_yaml inside file_changed_added is going to be undefined or an error.
I'm not sure what specifically Atom wants you to return but a class should work, something like this:
# Use a class so that => does what you're expecting it to do
class AtomMarkdownLabels
# other stuff here
file_changed_added: (file_path) =>
fs.readFile file_path, 'utf-8', #process_yaml
console.log 'file changed'
# you may or may not need => here
process_yaml: (err, data) =>
console.log "process_yaml is called"
# Export an instance of your class
module.exports = new AtomMarkdownLabels
If you want to or must use a plain object then you could bypass # completely and do it like this:
# Just plain old functions so define them that way
process_yaml = (err, data) ->
console.log "process_yaml is called"
file_changed_added = (file_path) ->
fs.readFile file_path, 'utf-8', process_yaml
console.log 'file changed'
module.exports = AtomMarkdownLabels =
# other stuff here
file_changed_added: file_changed_added
or like this:
# Explicitly name your object rather than using #
module.exports = AtomMarkdownLabels =
# other stuff here
file_changed_added: (file_path) ->
fs.readFile file_path, 'utf-8', AtomMarkdownLabels.process_yaml
console.log 'file changed'
process_yaml: (err, data) ->
console.log "process_yaml is called"
This should solve your other CoffeeScript problem from a few days ago too.

How to dynamically change property in lambda expression

I have written a function below. In second line of code I have written "Where(t => t.PickTicket == EmployeeId)". I want to change (t.PickTicket) property dynamically. How can I achieve this??? And how can I make below code more better and shorter?
Thanks in advance.
public List<TicketJoin> GetTicketJoin(string EmployeeId)
{
var query = _context.tickets.Where(t => t.PickTicket == EmployeeId).Join
(
_context.employees, t => t.CreatedBy, e => e.EmployeeId, (t, e) => new
{
t.Id,
e.Employee_Name,
e.Department,
e.Location,
t.Subject,
t.MainCatId,
t.SubCatId,
t.PickTicket,
t.Status,
t.CreateDate
}).Join
(
_context.MainCategory, t => t.MainCatId, m => m.MainCatId, (t, m) => new
{
t.Id,
t.Employee_Name,
t.Department,
t.Location,
t.Subject,
t.MainCatId,
m.MainCatName,
t.SubCatId,
t.PickTicket,
t.Status,
t.CreateDate
}).Join
(
_context.SubCategory, t => t.SubCatId, s => s.SubCatId, (t, s) => new
{
t.Id,
t.Employee_Name,
t.Department,
t.Location,
t.Subject,
t.MainCatId,
t.MainCatName,
t.SubCatId,
s.SubCatName,
t.PickTicket,
t.Status,
t.CreateDate
}).ToList();
var TicketJoin = query.ToList().Select(r => new TicketJoin
{
EmployeeName = r.Employee_Name,
Subject = r.Subject,
Location = r.Location,
MainCatName = r.MainCatName,
SubCatName = r.SubCatName,
CreateDate = r.CreateDate
}).ToList();
return TicketJoin;
}
}
How can I make it shorter?
By using database view to hide all those joins. In such case you will have have only simple query with single condition.
How can I make it dynamic?
Do you really need it dynamic? You can just do this:
public List<TicketJoin> GetTicketJoin(Expression<Func<Ticket, bool>> condition)
{
var query = _context.Tickets.Where(condition)...
}
and call it
var result = this.GetTicketJoin(t => t.PickTicket == employeeId);
It is not fully dynamic but it allows calling code specifying the condition.
Fully dynamic solution where you would be able to pass the property name as string requires using Expression trees to build query. There also used to be Dynamic-Linq library for this purpose.