To retrieve price for CVE-WT by GOOGLEFINANCE - google-finance

The price of CVE on TSX can be retrived by =GOOGLEFINANCE("TSE:CVE", "price") in Google Sheets. How does one get the price of CVE-WT using GOOGLEFINANCE?

I can't find it on googlefinance. You can retrieve by yahoo :
function marketPrice(code) {
var url='https://finance.yahoo.com/quote/'+code
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
var regularMarketPrice = data.context.dispatcher.stores.StreamDataStore.quoteData[code].regularMarketPrice.raw
return regularMarketPrice
}
function test() {Logger.log(marketPrice('CVE-WT'))}

Related

Making a list using api in google sheets

I am attempting to pull faction information from torns api but it puts all data into a single cell rather than listing. heres what ive got so far.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Faction members')
.addItem('Pulls faction member info','callNumbers')
.addToUi();
}
function callNumbers() {
var response = UrlFetchApp.fetch("https://api.torn.com/faction/42911?selections=basic&key=xFtPCG2ygjbhmKWI");
Logger.log(response.getContentText());
var fact = response.getContentText();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,2).setValue([fact]);
}```
You could try to parse the information using JSON.parse. Something like:
function callNumbers() {
var response = UrlFetchApp.fetch("https://api.torn.com/faction/42911?selections=basic&key=xFtPCG2ygjbhmKWI");
Logger.log(response.getContentText());
var fact = response.getContentText();
var myObject = JSON.parse(fact);
// define an array of all the object keys
var headerRow = Object.keys(myObject);
// define an array of all the object values
var row = headerRow.map(function(key){ return myObject[key]});
// define the contents of the range
var contents = [
headerRow,
row
];
// select the range and set its values
var ss = SpreadsheetApp.getActive();
var rng = ss.getActiveSheet().getRange(1, 1, contents.length, headerRow.length )
rng.setValues(contents)
}

Issues with textfinder and IF

I have a piece of code that was scrounged together from another code that is known working. What it does is searches a column using textfinder for a value, in this case, yesterday's date, if nothing is found, it should send an email.
function findAndSendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponses');
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('AlertDate');
var search = ss2.getRange("B2").getValue(); //cell has yesterday's date
var lastRow = ss.getLastRow();
var range = ss.getRange(1,4,lastRow); //define range for column D, column D contains dates
//find all occurrences of search key in column D and push range to array
var ranges = range.createTextFinder(search).findAll();
if (ranges!==null) {
var message = '';
}else {
var message = 'Test';
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EmailGroup").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Subject';
var link = "blahblahblah"
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
}
}
As you see, it should search column D, then, if it finds something, the message variable will be blank, else if it finds nothing, it will send an email to the email addresses chosen. I'm not sure how the results from a textfinder work with this and I think the way it is written is incorrect. Any help is appreciated, unfortunately, I cannot share the document in question as my company doesn't allow sharing outside of the domain. Thank you!
Try this:
You will need to update the sheet names I moved them to end of the line comments
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}
This version sends an email if yesterday is not found.
In answer to you last question:
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
if(isDate(d1)) {
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}else{
SpreadsheetApp.getUi().alert('Data is sheet2!B2 is not a date')
return;
}
}
function isDate(date){
return(Object.prototype.toString.call(date) === '[object Date]');
}

How I can use predicate buider for Sitecore Lucene Search

I am working on Sitecore 8.1 and I am implementing filter functionality for one of the page by Sitecore lucene. Fot filtering I am using predicate builder. I have 3 multi-lists field on detail items
Product
Category
Services
Now on listing page I have all three group filters as checkboxes as given in below image -
My Requirement is I want to apply Or between inside the group like between products condition should be Or and between two groups condition should be And. For example products and Category should be And.
I followed http://getfishtank.ca/blog/building-dynamic-content-search-linq-queries-in-sitecore-7 blog post to implement this
To achieve this what I am trying -
var builder = PredicateBuilder.True<TestResultItem>();
var Categorybuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(Categorys))
{
var CategoryItems = Categorys.Split('|');
foreach (var Category in CategoryItems)
{
var ct = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(Categorys, true);
Categorybuilder = Categorybuilder.Or(i => i.Category.Contains(ct));
}
}
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(Service))
{
var ServiceItems = Service.Split('|');
foreach (var ser in ServiceItems)
{
var si = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(ser, true);
Servicebuilder = Servicebuilder.Or(i => i.Service.Contains(si));
}
}
var productsbuilder = PredicateBuilder.False<TestResultItem>();
if (!string.IsNullOrEmpty(products))
{
var productItems = products.Split('|');
foreach (var product in productItems)
{
var pd = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(product, true);
productsbuilder = productsbuilder.Or(i => i.Category.Contains(pd));
}
}
Servicebuilder = Servicebuilder.Or(Categorybuilder);
productsbuilder = productsbuilder.Or(Servicebuilder);
builder = builder.And(productsbuilder);
The above given code is not working for me. I know I am doing something wrong as I am not good with Predicate builder, Or condition is not working between check boxes group.
Can anyone please tell me where I am wrong in given code or any best way to achieve this.
Any help would be appreciated
I did something similar recently and it works like this:
Create your "or" predicates:
var tagPredicate = PredicateBuilder.False<BlogItem>();
tagPredicate = tagValues.Aggregate(tagPredicate, (current, tag) => current.Or(p => p.Tags.Contains(tag)))
where tagValues is an IEnumerable containing the normalized guids.
I do this for several guid lists. In the end I wrap them together like this:
var predicate = PredicateBuilder.True<BlogItem>();
predicate = predicate.And(tagPredicate);
predicate = predicate.And(...);
Looking at your code: first of all change
Servicebuilder = Servicebuilder.Or(Categorybuilder);
productsbuilder = productsbuilder.Or(Servicebuilder);
builder = builder.And(productsbuilder);
into
builder = builder.And(Categorybuilder);
builder = builder.And(Servicebuilder);
builder = builder.And(productsbuilder);
You need to have one main predicate to join filters with AND condition & other predicates (e.g. for categories or services or products) to join filters internally with OR condition.
// This is your main predicate builder
var builder = PredicateBuilder.True<TestResultItem>();
var Categorybuilder = PredicateBuilder.False<TestResultItem>();
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
var productsbuilder = PredicateBuilder.False<TestResultItem>();
builder = builder.And(Categorybuilder);
builder = builder.And(Servicebuilder);
builder = builder.And(productsbuilder);
Hope this will help you.
Thanks all for providing your inputs -
I updated the code as per your inputs and now it's working.
There was two changes in my old code one was builder for multilist should be inside the if statement and also adding newly created builder to main builder on same location (inside the if statement) -
I am sharing the code below so that if anyone want to use it he can easily copy from here -
var builder = PredicateBuilder.True<TestResultItem>();
if (!string.IsNullOrEmpty(Categorys))
{ var Categorybuilder = PredicateBuilder.False<TestResultItem>();
var CategoryItems = Categorys.Split('|');
foreach (var Category in CategoryItems)
{
var ct = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(Categorys, true);
Categorybuilder = Categorybuilder.Or(i => i.Category.Contains(ct));
}
builder = builder.And(Categorybuilder);
}
if (!string.IsNullOrEmpty(Service))
{
var Servicebuilder = PredicateBuilder.False<TestResultItem>();
var ServiceItems = Service.Split('|');
foreach (var ser in ServiceItems)
{
var si = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(ser, true);
Servicebuilder = Servicebuilder.Or(i => i.Service.Contains(si));
}
builder = builder.And(Servicebuilder);
}
if (!string.IsNullOrEmpty(products))
{
var productsbuilder = PredicateBuilder.False<TestResultItem>();
var productItems = products.Split('|');
foreach (var product in productItems)
{
var pd = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(product, true);
productsbuilder = productsbuilder.Or(i => i.Category.Contains(pd));
}
builder = builder.And(productsbuilder);
}
In the above code Categorys, Service and products are pipe separated values which are coming from Sitecore Multi-list field.
Thanks again everyone for help!!

The query could not be run because the criteria for field '<?>' contained an invalid arithmetic expression

The query could not be run because the criteria for field '' contained an invalid arithmetic expression
Hi,
I faced some issue when i try to pass a value in Server Script and it keep come out with this error " doesnt support operator sbl-dat-00479". When i try to remove one of my value which is PRS Account No and it successfully come out. My value for PRS Account No = P-35971. Below is my server script.
function Print()
{
try
{
TheApplication().TraceOn("C:\\spool\\PRS SOA.txt", "Allocation", "All");
var Account = "";
var Year = "";
var Period = "";
var LPeriod = "";
var ContactID = "";
var Bookmark = "";
var ReportId = "";
var ReportName = "Customer Portal PRS Statement of Account";
//Active Field
this.BusComp().ActivateField("PRSAccountNo");
this.BusComp().ActivateField("Year2");
this.BusComp().ActivateField("Period2");
this.BusComp().ActivateField("LPeriod");
this.BusComp().ActivateField("CONTACT_ID");
//Get Account Row Id
Account = this.BusComp().GetFieldValue("PRSAccountNo");
Year = this.BusComp().GetFieldValue("Year2");
Period = this.BusComp().GetFieldValue("Period2");
LPeriod = this.BusComp().GetFieldValue("LPeriod");
ContactID = this.BusComp().GetFieldValue("CONTACT_ID");
//Construct Bookmark Query
Bookmark = "'cwa CustPortal PRS SOA Account'.Search = \"([PRS Account No] = '"+ Account +"') AND ([Year] = '"+ Year +"') AND ([Period] = '"+ LPeriod +"') AND ([CONTACT_ID] = '"+ ContactID +"')\"";
TheApplication().Trace("Bookmark: " + Bookmark);
//Retrieve Report Row Id
var boReport = TheApplication().GetBusObject("cwa CustPortal Report Administration");
var bcReport = boReport.GetBusComp("Report Standard Templates");
with(bcReport)
{
ActivateField("Report Name");
SetViewMode(AllView);
ClearToQuery();
SetSearchSpec("Report Name", ReportName);
ExecuteQuery(ForwardOnly);
if(FirstRecord())
{
ReportId = GetFieldValue("Id");
}
}
//Generate BIP Report
var GenReport = TheApplication().GetService("Workflow Process Manager");
var GenInput = TheApplication().NewPropertySet();
var GenOutput = TheApplication().NewPropertySet();
GenInput.SetProperty("ProcessName", "cwa CustPortal Generate BIP Report Workflow");
GenInput.SetProperty("Report Id", ReportId);
GenInput.SetProperty("Bookmark", Bookmark);
GenReport.InvokeMethod("RunProcess", GenInput, GenOutput);
var ErrMsg = GenOutput.GetProperty("Error Message");
if(ErrMsg == "")
{
//BIP Report successful generated, redirect to view report page
TheApplication().GotoView("cwa CustPortal PRS SOA Report View");
}
else
{
Popup(ErrMsg);
return(CancelOperation);
}
TheApplication().TraceOff();
}
catch(e)
{
Popup(e);
}
finally
{
}
}
Code looks ok, would be data issue or calc field logic error.
I think "Year2", "Period2" are Calculated fields & could be returning the special character ("/") leading to render the searchspec incorrectly.

How to retrieve a total result count from the Sitecore 7 LINQ ContentSearch API?

In Lucene.Net, it is possible to retrieve the total number of matched documents using the TopDocs.TotalHits property.
This functionality was exposed in the Advanced Database Crawler API using an out parameter in the QueryRunner class.
What is the recommended way to retrieve the total result count using Sitecore 7's new LINQ API? It does not seem possible without enumerating the entire result set. Here is what I have so far:
var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(item => item.Content == "banana");
var totalResults = query.Count(); // Enumeration
var topTenResults = query.Take(10); // Enumeration again? this can't be right?
...
}
Try this:
using Sitecore.ContentSearch.Linq; // GetResults on IQueryable
var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(item => item.Content == "banana");
var results = query.GetResults();
var totalResults = results.TotalSearchResults;
var topTenResults = results.Hits.Take(10);
...
}
To get more info about sitecore and linq you can watch this session and look at this repo.