It seem to me that this was hard...
var MostRated = (from p in db.Posts
let AverageRating = CalculateAverageRatingFromPost(p)
where p.PostStatus == Convert.ToInt32(PostStatusEnum.Published.Value) && p.IsDeleted == false
orderby p.PublishedDate descending
select new
{
PostUrl = Common.PostUrl(p.Section.Name, p.Permalink),
Title = Common.TrimString(p.Title, 50),
Excerpt = Common.TrimString(p.Excerpt, 80),
AverageRate = CalculateAverageRating((from pr in db.Ratings
where pr.ObjectType == Convert.ToInt32(ObjectTypeEnum.Post.Value) && pr.ObjectID == p.ID
select pr).SingleOrDefault()),
PublishedDate = new DateHelper().DateTimeInWords(p.PublishedDate.Value)
}).OrderByDescending(o => o.AverageRate).Take(5).ToList();
and the other method is
private Decimal CalculateAverageRating(Rating pr)
{
if (pr != null)
{
Decimal Average = ((1 * (Decimal)pr.Star1) + (2 * (Decimal)pr.Star2) + (3 * (Decimal)pr.Star3) + (4 * (Decimal)pr.Star4) + (5 * (Decimal)pr.Star5)) / ((Decimal)pr.Star1 + (Decimal)pr.Star2 + (Decimal)pr.Star3 + (Decimal)pr.Star4 + (Decimal)pr.Star5);
return Average;
}
else
{
return 0;
}
}
I get this run time error "no supported translation to SQL".
What i want is to get lists of the posts, and do a small quick calculations of the rating and then sort those from highest to low and take 5 posts only.
Thanks
I haven't tested this, but try defining the function as an Expression object.
Expression<Rating, Decimal> CalculateAverageRating =
pr => (Decimal)(
pr == null ? 0 :
(pr.Star1 + 2*pr.Star2 + 3*pr.Star3 + 4*pr.Star4 + 5*pr.Star5)
/(pr.Star1 + pr.Star2 + pr.Star3 + pr.Star4 + pr.Star5));
Related
I used to be able to pull traffic source data by reading the __utmz cookie, by doing so I can post the data to an internal conversion tracking database. but now GA doesn't use this cookie and it appears that the other cookies don't have any client-side data we can use.
Are there any other ways we can pull the traffic source data into our own internal db?
You can simulating the Google Analytics Processing Flow and determine the values of traffic sources parameters like source, medium, campaign, ... using a custom JavaScript in page or through Google Tag Manager.
This can be a solution:
function crumbleCookie(a) {
for (var d = document.cookie.split(";"), c = {}, b = 0; b < d.length; b++) {
var e = d[b].substring(0, d[b].indexOf("=")).trim(),
i = d[b].substring(d[b].indexOf("=") + 1, d[b].length).trim();
c[e] = i
}
if (a) return c[a] ? c[a] : null;
return c
}
function bakeCookie(a, d, c, b, e, i) {
var j = new Date;
j.setTime(j.getTime());
c && (c *= 864E5);
j = new Date(j.getTime() + c);
document.cookie = a + "=" + escape(d) + (c ? ";expires=" + j.toGMTString() : "") + (b ? ";path=" + b : "") + (e ? ";domain=" + e : "") + (i ? ";secure" : "")
}
function writeLogic(n) {
var a = getTrafficSource(n, '.example.com'); //Insert your domain here
a = a.replace(/\|{2,}/g, "|");
a = a.replace(/^\|/, "");
a = unescape(a);
bakeCookie(n, a, 182, "/", "", "") // Cookie expiration sets to 182 days
};
function getParam(s, q) {
try{
var match = s.match('[?&]' + q + '=([^&]+)');
return match ? match[1] : '';
} catch(e){
return '';
}
}
function calculateTrafficSource() {
var source='', medium='', campaign='', term='', content='';
var search_engines = [['bing', 'q'], ['google', 'q'], ['yahoo', 'q'], ['baidu', 'q'], ['yandex', 'q'], ['ask', 'q']]; //List of search engines
var ref = document.referrer;
ref = ref.substr(ref.indexOf('//')+2);
ref_domain = ref;
ref_path = '/';
ref_search = '';
// Checks for campaign parameters
var url_search = document.location.search;
if(url_search.indexOf('utm_source') > -1) {
source = getParam(url_search, 'utm_source');
medium = getParam(url_search, 'utm_medium');
campaign = getParam(url_search, 'utm_campaign');
term = getParam(url_search, 'utm_term');
content = getParam(url_search, 'utm_content');
}
else if (getParam(url_search, 'gclid')) {
source = 'google';
medium = 'cpc';
campaign = '(not set)';
}
else if(ref) {
// separate domain, path and query parameters
if (ref.indexOf('/') > -1) {
ref_domain = ref.substr(0,ref.indexOf('/'));
ref_path = ref.substr(ref.indexOf('/'));
if (ref_path.indexOf('?') > -1) {
ref_search = ref_path.substr(ref_path.indexOf('?')+1);
ref_path = ref_path.substr(0, ref_path.indexOf('?'));
}
}
medium = 'referral';
source = ref_domain;
// Extract term for organic source
for (var i=0; i<search_engines.length; i++){
if(ref_domain.indexOf(search_engines[i][0]) > -1){
medium = 'organic';
source = search_engines[i][0];
term = getParam(ref_search, search_engines[i][1]) || '(not provided)';
break;
}
}
}
return {
'source' : source,
'medium' : medium,
'campaign': campaign,
'term' : term,
'content' : content
};
}
function getTrafficSource(cookieName, hostname) {
var trafficSources = calculateTrafficSource();
var source = trafficSources.source.length === 0 ? 'direct' : trafficSources.source;
var medium = trafficSources.medium.length === 0 ? 'none' : trafficSources.medium;
var campaign = trafficSources.campaign.length === 0 ? 'direct' : trafficSources.campaign;
// exception
if(medium === 'referral') {
campaign = '';
}
var rightNow = new Date();
var value = 'source=' + source +
'&medium=' + medium +
'&campaign='+ campaign +
'&term=' + trafficSources.term +
'&content=' + trafficSources.content +
'&date=' + rightNow.toISOString().slice(0,10).replace(/-/g,"");
return value;
}
// Self-invoking function
(function(){
var date = new Date();
var fr_date = date.getUTCFullYear().toString() + ((date.getUTCMonth() < 9) ? '0' + (date.getUTCMonth()+1).toString() : (date.getUTCMonth()+1).toString()) + ((date.getUTCDate() < 10) ? '0' + date.getUTCDate().toString() : date.getUTCDate().toString());
var session = crumbleCookie()['FirstSession'];
if (typeof session == 'undefined') {
writeLogic('FirstSession');
}
else {
writeLogic('ReturningSession');
}
})();
Code here: http://clients.first-rate.com/firstrate/NewSession%20and%20ReturningSession%20cookies.txt
I have 2 date fields issued date and due date.When I choose issued date,due date should be auto populated by adding 10days with selected date. I have written on-change method for this
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
//var issuedDate=new GlideDateTime(g_form.getValue('u_issued_date'))
//var issuedDate=g_form.getValue('u_issued_date')
alert(issuedDate)
var gdt = new GlideDateTime(issuedDate);
gdt.addDays(10)
g_form.setValue('u_due_date',gdt);
}
I am getting an error GlideDateTime is not defined function ().How can I achieve this? Is there any other way?
GlideDateTime is not available on client side. For simple operation like the one you are having you can use javascript Date object. Which is pain to format, but doable, example:
var date = new Date(g_form.getValue('u_issued_date'));
date.setDate(date.getDate() + 10); //add 10 days
g_form.setValue('u_due_date', formatDate(date));
function formatDate (date) {
return date.getFullYear() + '-' +
leadingZero(date.getMonth() + 1) + '-' +
leadingZero(date.getDate()) + ' ' +
date.getHours() + ':' +
date.getMinutes() + ':' +
date.getSeconds();
}
function leadingZero (value) {
return ("0" + value).slice(-2);
}
For more complicated operation you would wish GlideDateTime you will have to use GlideAjax, that will do operations on server side, and provide result.
I'm trying to use firebase function transaction, but as I see there is no official way to handle the first cached null value...
I'm trying to do the following:
var team = event.data.child('team').val();
var tip = event.data.child('tip').val();
console.log('tip: ' + tip + ' | team: ' +team)
const pathToValue = admin.database().ref('users/' + event.params.userId + '/coins');
const pathToTeamBetsValue = admin.database().ref('matches/' + event.params.matchId + '/opponents/' + team + "/bets");
return pathToValue.transaction(function (coins) {
if (coins) {
if (coins >= tip) {
pathToTeamBetsValue.transaction(function (teamBets) {
if (teamBets) {
teamBets = teamBets + tips;
return teamBets;
}
});
admin.database().ref('bets/' + event.params.matchId + '/' + event.params.userId + '/status').set('inProgress');
coins = coins - tip;
}
else {
console.warn(event.params.userId + " new bet on match " + event.params.matchId + " was not successfull! (not enough coin)")
//return coins;
}
}
return coins;
})
so far as you can see I get some value which what should be decreased from the user's coins... unfortunately till now I could only get the behaviour which sets null in the user's coin value.. please help
selectStmt=(select +
('*' |delimitedList(functionbody|column)).setResultsName("Columns") + Optional((_as+table.setResultsName("Aliases"))|table.setResultsName("**Aliases1**"),'')+
Optional(_into+('*' |columns).setResultsName("Columns"),'')+
_from +
table.setResultsName("Tables",listAllMatches=True)+Optional((_as+table.setResultsName("Aliases"))|table.setResultsName(**Aliases2**),'')+
Optional(where + Group(whereExpr), '').setResultsName("where") +
Each([Optional(groupby + columns("groupby")+Optional(_asc|_desc,''),'').setDebug(False),
Optional(orderby + columns("orderby"),'').setDebug(False),Optional(_limit+columnVal,'')
])).setResultsName("Select",listAllMatches=True)+Optional((_union_all|_union)+selectStmt,'').setResultsName("Union")
so if i am matching query like
select count(id) sellercount
into v_photocount
from carphotos photos
where inquiryid = v_inquiryid
and isdealer = (
case
when v_sellertype = 1 then 1
else 0
end
)
and isactive = 1
and isapproved = 1;
Then sellercount is matching with _into and photos with where.
How can I avoid This
i have to fetch those records where cityname like'zipcode' where zipcode is variable and apply conditions
var zipcd = (from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select u).ToList().Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 1)
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else if (locations == "")
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName + "," + locations;
}
if (zipcd.Count() > 3) is greater than 3
{
locations = locations.Replace(locations, "," + "<br>");
}
The problem is that you're casting an iterator to the type of a single element on the line
ViewSearch vs = (ViewSearch)zipcd.
If you want vs to be a single object, you must call First() or FirstOrDefault() on your collection:
ViewSearch vs = zipcd.First(); // Throws if there are no elements
ViewSearch vs = zipcd.FirstOrDefault(); // null if there are no elements
First of all I would suggest that you download and use the lovely LINQPad not only to run your LINQ queries first but also to learn from it (has a lot of samples that you can run right form there, no more config needed)
for your question:
var zipcd = (
from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct().ToList();
As you can see the query works:
Distinct at the end of your query uses IEqualityComparer, and I'm guessing you haven't defined one for Viewsearch. It would look something like this:
public class ViewsearchComparer : IEqualityComparer<Viewsearch>
{
public bool Equals(Viewsearch vs1, Viewsearch vs2)
{
// Implementation
}
public int GetHashCode(Viewsearch vs)
{
// Implementation
}
}
After you have that defined, you pass it into your distinct call:
.Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
Stateabbr = u.StateAbbr
})
.Distinct(new ViewsearchComparer());