You are not allowed to call openByUrl. OAuth 2.0? - oauth

You are not allowed to call openByUrl. OAuth 2.0
You are not allowed to call openByUrl. OAuth 2.0
I executes a script "A" in google text document "document" to retrieve the text of the document "Name Surname" I sent in a paper google spreadsheet "Spreadsheet"
with: SpreadsheetApp.openByUrl ("")
The Script "A" is in a Library
This works well with documents whose script A "board" is OAuth 1.0, for against it does not work with the script A "board" is OAuth 2.0.
Error message referring me: You are not allowed to call openByUrl.
What should I do to run my new script OAuth 2.0
What should replace it by calling the SpreadsheetApp SpreadsheetApp.openByUrl ("")?
var ss =SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gJHFDBHJj6peX1kjfdhlkskjFt2gFkU/edit#gid=3950BSV3");
here is the complete script up in the Library that runs perfectly if the document was created with OAuth 1.0 but do not work if the document was created with OAuth 2.0 .
///// Facturer Acte ////
function FacturerActe() {
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var PrenomNom = new RegExp(result,"gm");
Logger.log(PrenomNom.getText);
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
ss.setActiveSheet(sheet);
var cell = sheet.getRange("A40");
cell.setNote("Aujourd'hui est un nouveau jour ! Nous sommes le :"+date);
selectFirstEmptyRow (); // Place le curseur sur la premiere ligne Vide de la Colonne "B"
}
//* Placez le curseur de l'utilisateur actuel dans la première cellule de la première ligne vide.
//*
function selectFirstEmptyRow () {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var regexp = /\s[A-Z a-z]+/g ;// extrait les espaces devant et derriere Nom Prenom
//* Extrait les blancs
var result = regexp.exec(result);
/// var result = result.replace(/^[\r\n]+|\.|[\r\n]+$/g, "");// extrait les espaces devant et derriere Nom Prenom GAS D'ONT WORK
sheet . setActiveSelection ( sheet . getRange ( "B" + getFirstEmptyRowWholeRow ())).setValue(result) ;
Logger.log(result.getText);
}
/**
* " Trouve la première ligne vide la Colonne "B" " de checker de Mogsdad.
*/
function getFirstEmptyRowWholeRow () {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var range = sheet . getDataRange ();
var values = range . getValues ();
var row = 1 ;
for ( var row = 1 ; row < values . length ; row ++) {
if (! values [ row ]. join ( "" )) break ;
}
return ( row + 1 );
}
///// Fin Facturer Acte ////

Related

Google sheets script multiple range and multiple conditional

I have a spreadsheet, in which I need the script to fetch, over two columns, two pieces of information. And when that's true, I add a formula that adds "1 day" into a third column.
I can make the conditionals run individually. But when I put both, they don't work.
function fillColADia() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Afazeres');
var dataA = s.getRange("H1:H").getValues();
var dataB = s.getRange("A1:A").getValues();
for(var i=0; i<dataA.length; i++) {
for(var j=0; j<dataB.lenght; j++) {
if (dataB[j][0] == false) {
if (dataA[i][0] == 'Zenon') {
s.getRange(i+1,3).setValue("+1");
}
}
}
}
}
And I also don't know how to add the "add 1 day" formula to the end.
Thanks a lot for the help.
COPY FILE with dummy data
Faaala! Something along these lines as food for thought!
...although I'm certain there are more performant ways to accomplish it:
function fillColADia() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Page1');
var data = s.getRange("A1:H").getValues();
for (var a = 0; a < data.length; a++) {//Percorre cada linha do intervalo
if (data[a][0] == false && data[a][7] == 'Zenon') {//Aplica critérios
let date = data[a][2];//Pega a data daquela linha
date1 = Utilities.formatDate(addDays(new Date(date), 1), Session.getTimeZone(), "dd/MM/yyyy");//Formata o objeto data, usando a função abaixo para incrementar o dia
date2 = Utilities.formatDate(addDays(new Date(date), 1), Session.getTimeZone(), "dd/MM/yyyy HH:mmss");
s.getRange(a + 1, 3).setValue(date1);//Põe a data de volta
s.getRange(a + 1, 4).setValue(date2);//Põe a data de volta
}
}
}
//GERA DATAS INCREMENTANDO OS DIAS
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}

Google Sheet merged cells create space

I got a sheet with merged cells and in those merged cells, a script write its results.
When I copy this result in the merged cells, it gave me multiple spaces at the end.
Like : Result #1________ (« _ » represent invisible space)
When I put the same result in a normal cell (not merged), it doesn’t put any space at the end.
Result #1
I tried multiple cell format (Center aligned, left aligned, etc.) but nothing changed.
Do you have any idea why ?
Thanks !
EDIT : add script
Script
function Devise() {
const sheetName = "Missions";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var Devise = "";
var NombreMission = "";
var NomOperateurs = "";
if(sheet.getRange("H2").getValue()=="") { // Si la mission 7 est vide
NombreMission = 6; // On compte seulement 6 missions
} else {
NombreMission = 7; // Sinon on compte 7 missions
}
for (i = 1; i < NombreMission+1; i++) { // Boucle FOR pour NombreMission missions
if(sheet.getRange(2,i+1).getValue()=="") { continue; } // Si la mission est vide, on la passe
Devise = Devise + i + "/";
l = 0; // Variable pour indiquer "Rien" si personne à placer dans la mission
NomOperateurs = ""; // Reset les noms pour la mission d'après
for (j = 1; j < 27+1; j++) { // Boucle FOR pour tous les opérateurs
if(sheet.getRange(j+2,i+1).getFontWeight() == 'bold') { // Vérifie si la case est en gras
/*if(i!=NombreMission) { // Tant qu'il ne s'agit pas de la dernière mission ...
Devise = Devise + sheet.getRange(j+2,1).getValue() + " "; // ... on affiche les opérateurs
}*/
NomOperateurs = NomOperateurs + sheet.getRange(j+2,1).getValue() + " ";
l = l + 1; // On compte les opérateurs
}
} // Fin Boucle FOR opérateurs
if (l==24) { // S'il y a tous les operateurs sur une mission...
Devise = Devise + "ALL OPs! " // ... On affiche "All Op!"
} else if (i==NombreMission && l!=0) { // Sinon s'il s'agit de la dernière mission et qu'il reste des opérateurs à placer...
Devise = Devise + "Autres + Epic "; // ... On indique qu'il s'agit du reste et des épiques
} else if (l==0) { // Sinon s'il n'y a aucun opérateurs à placer...
Devise = Devise + "RIEN " // ... On indique "RIEN"
} else { // Sinon ...
Devise = Devise + NomOperateurs; // ... On affiche les opérateurs
}
} // FIN BOUCLE FOR NombreMission
if(NombreMission==6 && Devise!="") { Devise = Devise + "7/!NOTHING!";}
sheet.getRange("K13").setValue(Devise);
}
Your problem is related to the data you copied and the way that you copied it as pasting text in merged cells doesn't create any new lines.
Also, an important thing to keep in mind is that CTRL+ENTER creates the mentioned space also known as a line break.
So, for example, if this cell contains the text Text + line break:
And the text from the above cell is copied and pasted into a merged cell it will look like this - which is the same outcome as the one that you have mentioned:
But if you paste the same text to a simple cell, it will look like this:
This is essentially because the line break will signify the start of a new cell.
For example, this cell contains this text with line breaks:
After the text is copied and pasted into a different cell, this is how it will actually be pasted as:
In order to solve your issue, I suggest you to copy only the text needed and if possible to avoid using any line breaks.
Reference
Edit and Format a Spreadsheet.
Encountering the same issue.
I have a merged cell with text. If I select the cell and paste it into notepad, It includes quite a lot of white space.
I've checked and if the merged cell spans two rows, the white space includes a line break.
If the merged cell spans one row but two columns, the white space does not include a line break.
If I have a single cell and have it take its value from the mered cell "=A1", the text does not include the white space.
So the addition of the whitespace is definitely the result of having a merged cell.

AdWords Script With Divergent Data from Webview

I have the following code on an AdWords script:
var campanha = 'xyz';
function main() {
campanhas = AdWordsApp.campaigns().withCondition("CampaignName = '" + campanha + "'").withCondition('Status = ENABLED').get();
while(campanhas.hasNext()) {
campanha = campanhas.next();
if(campanha.getBiddingStrategyType() != 'ENHANCED_CPC') {
Logger.log('Ajuste de lance da campanha inválido: ' +campanha.getBiddingStrategyType());
continue;
}
palavras = campanha.keywords().withCondition('Status = ENABLED').forDateRange("YESTERDAY").get();
while(palavras.hasNext()) {
palavra = palavras.next();
estatisticas = palavra.getStatsFor('YESTERDAY');
lances = palavra.bidding();
estimativa_primeira = Math.max(palavra.getTopOfPageCpc(), palavra.getFirstPageCpc());
posicao = estatisticas.getAveragePosition();
if (posicao > 1) {
Logger.log(palavra.getText() +" = " +" "+palavra.getTopOfPageCpc()+" "+palavra.getFirstPageCpc());
}
//Logger.log(palavra.getText() + ' = '+lances.getCpc()+" = "+estatisticas.getAveragePosition());
}
}
I expected to retrieve the estimated first page CPC and estimated first position CPC. But the values that I received are diferente from the AdWords webinterface. For exemple, for a given keyword the script returned +xxx +yyyy = 0.12 0.05, when I look those keywords on webinterface I have the following values for 0.12 for estimated first page CPC and 0.41 for estimated first position CPC.

Python splitting text returns a str and a list of str

I wonder whether someone can help me with the syntax to split my text file into key, value pairs.
Abbasso: termine con cui si indicano gli ambienti situati sotto il ponte di coperta.
Abbattuta: manovra che consiste nel puggiare sino a fare prendere il vento alle vele sulle mure opposte.
Abbisciare: (fr.: prendre la biture; ingl.: to coil) stendere un cavo o una catena come fosse una biscia in modo da evitare che si imbrogli successivamente, quando sarà posto in opera.
Abbordo: (fr.: abordage; ingl.: collision) collisione in mare. Sinonimo, poco usato, di accosto e di abbordaggio.
Abbrivo: (fr.: erre; ingl.: way-on) inerzia dell'imbarcazione a continuare nel suo movimento anche quando è cessata la spinta propulsiva, sia essa a vela che a motore.
Abbuono: (fr.: bonification, rating; ingl.: rating) compenso: (o vantaggio) dato ad una imbarcazione per permetterle di gareggiare più equamente: (ad esempio abbuono per anzianità di costruzione dello scafo).
My function at the minute gives me a key str, but a value type(list). Instead I want the value also to be a str. I get what my problem is that what should a be the value is splitting on every colon instead of only on the leftmost colon.
def create_dict():
eng_fr_it_dict={}
f_name = "dizionario_della_vela.txt"
handle = open(f_name, encoding = 'utf8')
for line in handle:
#print(line)
if line.startswith(" ") : continue
line.lstrip()
terms = line.split(": ")
#print(terms[1:])
term = terms[0].lstrip()
expan = terms[1:]
print(type(term), type(expan))
eng_fr_it_dict[term] = eng_fr_it_dict.get(term, expan)
with open("eng_fr_it_dict.txt", "wb") as infile:
pickle.dump(eng_fr_it_dict,infile)
print(eng_fr_it_dict)
Can you suggest a cleverer way to do this or will I have to work out how to covert the list of str to a single str? I thought that there was a split in-built function, but obviously not
file = open("dizionario_della_vela.txt", "r")
data = file.read()
file.close()
data = data.split("\n") # getting every line as seperate list
myDict = {}
for line in data:
line = line.split(":")
key = line[0] # getting first element as key
value = ":".join(line[1:]) # joins elements (starting with second) with
# ":". We need this because previous line
# was splitted by ":" to get your key. This
# is where "string" value is produced.
myDict[key] = value
for key in myDict.keys():
print(myDict[key])

Plone/Dexterity schema.Choice not allowing Spanish characters

In Plone 4.1.2 I created a myContentType with Dexterity. It has 3 zope.schema.Choice fields. Two of them take their values from a hardcoded vocabulary and the other one from a dynamic vocabulary. In both cases, if I choose a value that has Spanish accents, when I save the add form the selection is gone and doesn't show up in the view form (without showing any error message). But if I choose a non accented value everything works fine.
Any advise on how to solve this problem?
(David; I hope this is what you asked me for)
# -*- coding: utf-8 -*-
from five import grok
from zope import schema
from plone.directives import form, dexterity
from zope.component import getMultiAdapter
from plone.namedfile.interfaces import IImageScaleTraversable
from plone.namedfile.field import NamedBlobFile, NamedBlobImage
from plone.formwidget.contenttree import ObjPathSourceBinder
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.schema.interfaces import IVocabularyFactory
from z3c.formwidget.query.interfaces import IQuerySource
from zope.component import queryUtility
from plone.formwidget.masterselect import (
_,
MasterSelectField,
MasterSelectBoolField,
)
from plone.app.textfield.interfaces import ITransformer
from plone.indexer import indexer
from oaxaca.newcontent import ContentMessageFactory as _
from oaxaca.newcontent.config import OAXACA
from types import UnicodeType
_default_encoding = 'utf-8'
def _encode(s, encoding=_default_encoding):
try:
return s.encode(encoding)
except (TypeError, UnicodeDecodeError, ValueError):
return s
def _decode(s, encoding=_default_encoding):
try:
return unicode(s, encoding)
except (TypeError, UnicodeDecodeError, ValueError):
return s
view = view.encode('utf-8')
def getSlaveVocab(master):
results = []
if master in OAXACA:
results = sorted(OAXACA[master])
return SimpleVocabulary.fromValues(results)
class IFicha(form.Schema, IImageScaleTraversable):
"""Describes a ficha
"""
tipoMenu = schema.Choice(
title=_(u"Tipo de evento"),
description=_(u"Marque la opción que aplique o "
"seleccione otro si ninguna aplica"),
values=(
u'Manifestación en lugar público',
u'Toma de instalaciones municipales',
u'Toma de instalaciones estatales',
u'Toma de instalaciones federales',
u'Bloqueo de carretera municipal',
u'Bloqueo de carretera estatal',
u'Bloqueo de carretera federal',
u'Secuestro de funcionario',
u'Otro',),
required=False,
)
tipoAdicional = schema.TextLine(
title=_(u"Registre un nuevo tipo de evento"),
description=_(u"Use este campo solo si marcó otro en el menú de arriba"),
required=False
)
fecha = schema.Date(
title=_(u"Fecha"),
description=_(u"Seleccione el día en que ocurrió el evento"),
required=False
)
municipio = MasterSelectField(
title=_(u"Municipio"),
description=_(u"Seleccione el municipio donde ocurrió el evento"),
required=False,
vocabulary="oaxaca.newcontent.municipios",
slave_fields=(
{'name': 'localidad',
'action': 'vocabulary',
'vocab_method': getSlaveVocab,
'control_param': 'master',
},
)
)
localidad = schema.Choice(
title=_(u"Localidad"),
description=_(u"Seleccione la localidad donde ocurrió el evento."),
values=[u'',],
required=False,
)
actores = schema.Text(
title=_(u"Actores"),
description=_(u"Liste las agrupaciones y los individuos que participaron en el evento"),
required=False,
)
demandas = schema.Text(
title=_(u"Demandas"),
description=_(u"Liste las demandas o exigencias de los participantes"),
required=False
)
depResponsable = schema.Text(
title=_(u"Dependencias"),
description=_(u"Liste las dependencias gubernamentales responsables de atender las demandas"),
required=False
)
seguimiento = schema.Text(
title=_(u"Acciones de seguimiento"),
description=_(u"Anote cualquier accion de seguimiento que se haya realizado"),
required=False
)
modulo = schema.Choice(
title=_(u"Informa"),
description=_(u"Seleccione el módulo que llena esta ficha"),
values=(
u'M1',
u'M2',
u'M3',
u'M4',
u'M5',
u'M6',
u'M7',
u'M8',
u'M9',
u'M10',
u'M11',
u'M12',
u'M13',
u'M14',
u'M15',
u'M16',
u'M17',
u'M18',
u'M19',
u'M20',
u'M21',
u'M22',
u'M23',
u'M24',
u'M25',
u'M26',
u'M27',
u'M28',
u'M29',
u'M30',),
required=False
)
imagen1 = NamedBlobImage(
title=_(u"Imagen 1"),
description=_(u"Subir imagen 1"),
required=False
)
imagen2 = NamedBlobImage(
title=_(u"Imagen 2"),
description=_(u"Subir imagen 2"),
required=False
)
anexo1 = NamedBlobFile(
title=_(u"Anexo 1"),
description=_(u"Subir archivo 1"),
required=False
)
anexo2 = NamedBlobFile(
title=_(u"Anexo 2"),
description=_(u"Subir archivo 2"),
required=False
)
#indexer(IFicha)
def textIndexer(obj):
"""SearchableText contains fechaFicha, actores, demandas, municipio and localidad as plain text.
"""
transformer = ITransformer(obj)
text = transformer(obj.text, 'text/plain')
return '%s %s %s %s %s' % (obj.fecha,
obj.actores,
obj.demandas,
obj.municipio,
obj.localidad)
grok.global_adapter(textIndexer, name='SearchableText')
class View(grok.View):
"""Default view (called "##view"") for a ficha.
The associated template is found in ficha_templates/view.pt.
"""
grok.context(IFicha)
grok.require('zope2.View')
grok.name('view')
I found the same problem some months ago on early development of collective.nitf.
The tokens on a vocabulary must be normalized; this is how I solved it:
# -*- coding: utf-8 -*-
import unicodedata
…
class SectionsVocabulary(object):
"""Creates a vocabulary with the sections stored in the registry; the
vocabulary is normalized to allow the use of non-ascii characters.
"""
grok.implements(IVocabularyFactory)
def __call__(self, context):
registry = getUtility(IRegistry)
settings = registry.forInterface(INITFSettings)
items = []
for section in settings.sections:
token = unicodedata.normalize('NFKD', section).encode('ascii', 'ignore').lower()
items.append(SimpleVocabulary.createTerm(section, token, section))
return SimpleVocabulary(items)
grok.global_utility(SectionsVocabulary, name=u'collective.nitf.Sections')
Plone uses gettext for internationalization. The bulletproof approach would be to implement your custom functionality in English and use locales for your specific language. Look at the relevant parts of the community manual on how this is done. Since you already setup a MessageFactory you could even use a tool like e.g. zettwerk.i18nduder for quick extraction of message strings.
I found a partial explanation/solution here. I can get the Spanish characters in the view form if i do:
-- coding: utf-8 --
from plone.directives import form
from five import grok
from zope import schema
from plone.directives import form, dexterity
from zope.schema.vocabulary import SimpleVocabulary
myVocabulary = SimpleVocabulary.fromItems((
(u"Foo", "id_foó"),
(u"Baroo", "id_baroó")))
class IPrueba(form.Schema):
tipoMenu = schema.Choice(
title=_(u"Tipo de evento"),
description=_(u"Marque la opción que aplique o "
"seleccione otro si ninguna aplica"),
vocabulary=myVocabulary,
required=False,
)

Resources