Google Sheets API adding single qoute to text - google-api

Hi I am running a Google APi script to enter data into a sheet but for some text (number,dates, booleans) it's adding a ' before e.g 05/01/2021 = '05/01/2021
I am using batch update:
def turn_into_range(data, SheetId, row,cols):
rows = [{'values': [{'userEnteredValue': {'stringValue': f}} for f in e]} for e in data]
rng = {'sheetId': SheetId, 'startRowIndex': 0, 'startColumnIndex': 0}
fields = 'userEnteredValue'
body = {'requests': [{'updateCells': {'rows': rows, 'range': rng, 'fields': fields}},{
"updateSheetProperties": {
"properties": {
"gridProperties": {
"rowCount": row + 1,
"columnCount": cols
},
"sheetId": SheetId
},
"fields": "gridProperties"
},
}
]}
clean_dict = simplejson.loads(simplejson.dumps(body, ignore_nan=True))
return clean_dict
def post_sheet(service_sheets, spreadsheet_id, body):
request = service_sheets.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body)
response = request.execute()
return response
any ideas?

For this issue, it is because your data is treated as string in stringValue.
You need to use other types of values for different data types,
stringValue:
"A String", # Represents a string value.
Leading single quotes are not included. For example, if the user typed '123 into the UI, this would be represented as a stringValue of "123".
boolValue:
True or False, # Represents a boolean value.
numberValue:
3.14, # Represents a double value.
Note: Dates, Times and DateTimes are represented as doubles in "serial number" format.
formulaValue:
"A String", # Represents a formula.
errorValue:
An error in a cell. Represents an error.
This field is read-only.
Try adding this in your code.
from dateutil.parser import parse
def checkData(data):
if (isinstance(data, bool)):
return 'boolValue'
try:
if (isinstance(data, (int, float)) or parse(data)):
return 'numberValue'
except ValueError:
return 'stringValue'
Behaviour:
Now, use it in your code:
rows = [{'values': [{'userEnteredValue': {checkData(f): f}} for f in e]} for e in data]
For more details, documentation can be found here

Related

LINQ: select rows where any word of string start with a certain character

I want extract from a table all rows where in a column (string) there is at least one word that starts with a specified character.
Example:
Row 1: 'this is the first row'
Row 2: 'this is th second row'
Row 3: 'this is the third row'
If the specified character is T -> I would extract all 3 rows
If the specified character is S -> I would extract only the second column
...
Please help me
Assuming you mean "space delimited sequence of characters, or begin to space or space to end" by "word", then you can split on the delimiter and test them for matches:
var src = new[] {
"this is the first row",
"this is th second row",
"this is the third row"
};
var findChar = 'S';
var lowerFindChar = findChar.ToLower();
var matches = src.Where(s => s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Any(w => w.ToLower()[0] == lowerFindChar));
The LINQ Enumerable.Any method tests a sequence to see if any element matches, so you can split each string into a sequence of words and see if any word begins with the desired letter, compensating for case.
Try this:
rows.Where(r => Regex.IsMatch(r, " [Tt]"))
You can replace the Tt with Ss (both assuming you want either upper case or lower case).
The problem of course is, what is a "word"?
Is the character sequence 'word' in the sentence above a word according to your definition? It doesn't start with a space, not even a white-space.
A definition of a word could be:
Define wordCharacter: something like A-Z, a-z.
Define word:
- the non-empty sequence of wordCharacters at the beginning of a string followed by a non-wordcharacter
- or the non-empty sequence of wordCharacters at the end of a string preceded by a non-wordcharacter
- any non-empty sequence of wordCharacters in the string preceded and followed by a non-wordcharacter
Define start of word: the first character of a word.
String: "Some strange characters: 'A', 9, äll, B9 C$ X?
- Words: Some, strange characters, A
- Not Words: 9, äll, B9, C$ X?
So you first have to specify precisely what you mean by word, then you can define functions.
I'll write it as an extension method of IEnumerable<string>. Usage will look similar to LINQ. See Extension Methods Demystified
bool IsWordCharacter(char c) {... TODO: implement your definition of word character}
static IEnumerable<string> SplitIntoWords(this string text)
{
// TODO: exception if text null
if (text.Length == 0) return
int startIndex = 0;
while (startIndex != text.Length)
{ // not at end of string. Find the beginning of the next word:
while (startIndex < text.Length && !IsWordCharacter(text[startIndex]))
{
++startIndex;
}
// now startIndex points to the first character of the next word
// or to the end of the text
if (startIndex != text.Length)
{ // found the beginning of a word.
// the first character after the word is either the first non-word character,
// or the end of the string
int indexAfterWord = startWordIndex + 1;
while (indexAfterWord < text.Length && IsWordCharacter(text[indexAfterWord]))
{
++indexAfterWord;
}
// all characters from startIndex to indexAfterWord-1 are word characters
// so all characters between startIndexWord and indexAfterWord-1 are a word
int wordLength = indexAfterWord - startIndexWord;
yield return text.SubString(startIndexWord, wordLength);
}
}
}
Now that you've got a procedure to split any string into your definition of words, your query will be simple:
IEnumerabl<string> texts = ...
char specifiedChar = 'T';
// keep only those texts that have at least one word that starts with specifiedChar:
var textsWithWordThatStartsWithSpecifiedChar = texts
// split the text into words
// keep only the words that start with specifiedChar
// if there is such a word: keep the text
.Where(text => text.SplitIntoWords()
.Where(word => word.Length > 0 && word[0] == specifiedChar)
.Any());
var yourChar = "s";
var texts = new List<string> {
"this is the first row",
"this is th second row",
"this is the third row"
};
var result = texts.Where(p => p.StartsWith(yourChar) || p.Contains(" " + yourChar));
EDITED:
Alternative way (I'm not sure it works in linq query)
var result = texts.Where(p => (" " + p).Contains(" " + yourChar));
you can use .ToLower() if you want Case-insensitive check.

Formatting large numbers using numeral.js

In my app, I want to format various numbers using a library, and I have a couple of related questions (which I don't submit separately because I think they might represent a very common set of problems)
Format a number using a format string constant to achieve compressed literals such as 1.2k or 1.23M
Format a number using a format string constant to have a thousand delimiter applied, ragardless of client's locale settings.
I tried to achieve a formatting result, where the language thousand delimiter is actually taken into consideration
http://jsfiddle.net/erbronni/19mLmekt/
// load a language
numeral.language('fr', {
delimiters: {
thousands: ' ',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'M',
billion: '',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});
numeral.language('fr');
document.getElementById('f1').innerHTML = numeral(12345678).format('0 000') // intended output: '12 345 678' -- does not seem to work
Numeral.js has this built in. It can be easily achieved using a such as .format('0.00a').
Some full examples:
numeral(1000000).format('0a') will return 1m
numeral(250500).format('0.0a') will return 250.5k
numeral(10500).format('0.00a') will return 10.50k

No matching signature for operator IN for argument types STRING and {ARRAY<STRING>} (Google BigQuery)

I'm using Google BigQuery Ruby Client v0.23 and trying to use parameterized queries. I'm following API docs for reference.
When I run queries without the params, all is fine. However to make them dynamic, when I use an array params I get error. E.g. When I run this query
bigquery.query("SELECT COUNT(*) FROM oven.sensor_counts WHERE _PARTITIONTIME = TIMESTAMP('2016-04-04') AND sensor_id IN (#sensor_ids)", params: { sensor_ids: ['48-6', '48-2'] })
I get this
#<Harley::Response POST https://www.googleapis.com/bigquery/v2/projects/sensors-160421/queries == 400 (413 bytes) 3458ms>
Caught error invalidQuery: No matching signature for operator IN for argument types STRING and {ARRAY<STRING>} at [1:116]
Error - #<Google::Apis::ClientError: invalidQuery: No matching signature for operator IN for argument types STRING and {ARRAY<STRING>} at [1:116]>
Google::Cloud::InvalidArgumentError: invalidQuery: No matching signature for operator IN for argument types STRING and {ARRAY<STRING>} at [1:116]
from /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-cloud-bigquery-0.23.0/lib/google/cloud/bigquery/service.rb:662:in `rescue in execute'
Any insights would be greatly appreciated.
I believe the array is simply an incorrect argument. According to Functions & Operators, the syntax is:
x IN (y, z, ...)
Notice that there is no array.
And replacing the array with a single string works:
require "google/cloud/bigquery"
bigquery = Google::Cloud::Bigquery.new
sql = "SELECT word, SUM(word_count) AS word_count " \
"FROM `bigquery-public-data.samples.shakespeare`" \
"WHERE word IN (#words) GROUP BY word"
data = bigquery.query sql, params: { words: 'you' }
#=> [{"word"=>"you", "word_count"=>12527}]
The array argument works with the addition of UNNEST, per the syntax guide linked above:
The UNNEST form treats an array scan like UNNEST in the FROM clause:
x [NOT] IN UNNEST(<array expression>)
This form is often used with ARRAY parameters. For example:
x IN UNNEST(#array_parameter)
So the solution is:
require "google/cloud/bigquery"
bigquery = Google::Cloud::Bigquery.new
sql = "SELECT word, SUM(word_count) AS word_count " \
"FROM `bigquery-public-data.samples.shakespeare`" \
"WHERE word IN UNNEST(#words) GROUP BY word"
data = bigquery.query sql, params: { words: ['me', 'I', 'you'] }
#=> [{"word"=>"I", "word_count"=>21028}, {"word"=>"me", "word_count"=>8030}, {"word"=>"you", "word_count"=>12527}]
There is a better way to do this using arrays, using parameterized approach
from google.cloud import bigquery
client = bigquery.Client()
sql = "SELECT COUNT(*) FROM oven.sensor_counts WHERE _PARTITIONTIME =
TIMESTAMP('2016-04-04') AND sensor_id IN UNNEST(#sensor_ids)"
query_params = [
bigquery.ArrayQueryParameter("sensor_ids", "STRING", ['48-6', '48-2']), ]
job_config = bigquery.QueryJobConfig() job_config.query_parameters =
query_params query_job = client.query(
query,
job_config=job_config, ) client.query(sql,job_config=query_config)

Compare arrays together with different array types

I want to compare if 2 arrays are equal, here is my code:
var letteronloc = [String]();
letteronloc.append("test")
let characters = Array("test")
if(letteronloc == characters) {
}
but i have an error: could not find an overload for == that accepts the supplied arguments
I think its because the arrays are not equal, because the second array is not an string array. But how can i fix this?
let characters = Array("test") treats the string as a sequence
(of characters) and creates an array by enumerating the elements of the sequence.
Therefore characters is an array of four Characters,
the same that you would get with
let characters : [Character] = ["t", "e", "s", "t"]
So you have two arrays of different element types and that's why
you cannot compare them with ==.
If you want an array with a single string "test" then write it as
let characters = ["test"]
and you can compare both arrays without problem.
You just need to specify the type of the second array:
var letteronloc = [String]();
letteronloc.append("test")
let characters: [String] = Array(arrayLiteral: "test")
if (letteronloc == characters) {
}

Dictionary Optional? Confusion in swift

I know there are a lot of posts on this, but I can't seem to figure out what's going on. The dictionary prints fine. It has a list of words with the number of letters for that word as the value. I want to check if another string is in the list. I read a bunch on optionals, but apparently I'm missing something. I think it has to do with that of course.
let path = NSBundle.mainBundle().pathForResource("wordlist", ofType: "txt")
var content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)?.componentsSeparatedByString("\n")
var myDict = [String : Int]()
let compareWord : String? = "TEST"
if let content = content {
for word in 100 ..< 105
{
myDict[content[word]] = countElements(content[word])
}
}
println("\(myDict)")
var num : Int? = 0
println("Num: \(myDict[compareWord!])")
if let num : Int = myDict[compareWord!] {
println("\(compareWord) is a word with \(num) letters")
}
else
{
println("Wasn't a word")
}
**** Updated with a bit more detail of the code.
Here is what I get when I print a section of the dictionary.
[ABBOTSHIPS
: 11, ABBREVIATED
: 12, ABBOTS
: 7, ABBOTSHIP
: 10, ABBREVIATE
: 11]
If I set the test word to one of them I always get nil when checking for it. It seems to work fine when I manually type things in under the playground.
Ensure that componentsSeparatedByString("\n") doesn't leave any other character, such as \r, at the beginning or end of each extracted strings.

Resources