Hide column with Sheets API call - google-sheets

I would like to hide a given column in a google spreadsheet through the API v4, but I struggle to do so.
Does anyone know if it's possible and has managed to do it?
We have in the Apps Script a dedicated method to do so, and I would be surprised if this feature is not available in the REST API.

Yes, there is. It's just not very straightforward.
Here is an example of hiding column 5:
import httplib2
from apiclient.discovery import build
credentials = get_credentials() ## See Google's Sheets Docs
http = credentials.authorize(httplib2.Http())
service = build('sheets', 'v4', http=http)
spreadsheet_id = '#####################'
sheet_id = '#######'
requests = []
requests.append({
'updateDimensionProperties': {
"range": {
"sheetId": sheet_id,
"dimension": 'COLUMNS',
"startIndex": 4,
"endIndex": 5,
},
"properties": {
"hiddenByUser": True,
},
"fields": 'hiddenByUser',
}})
body = {'requests': requests}
response = service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id,
body=body
).execute()

Related

Telegraf splits input data into different outputs

I want to write Telegraf config file which will:
Uses openweathermap input or custom http request result
{
"fields": {
...
"humidity": 97,
"temperature": -11.34,
...
},
"name": "weather",
"tags": {...},
"timestamp": 1675786146
}
Splits result on two similar JSONs:
{
"sensorID": "owm",
"timestamp": 1675786146,
"value": 97,
"type": "humidity"
}
and
{
"sensorID": "owm",
"timestamp": 1675786146,
"value": -11.34,
"type": "temperature"
}
Sends this JSONs into MQTT queue
Is it possible or I must create two different configs and make two api calls?
I found next configuration which solves my problem:
[[outputs.mqtt]]
servers = ["${MQTT_URL}", ]
topic_prefix = "owm/data"
data_format = "json"
json_transformation = '{"sensorID":"owm","type":"temperature","value":fields.main_temp,"timestamp":timestamp}'
[[outputs.mqtt]]
servers = ["${MQTT_URL}", ]
topic_prefix = "owm/data"
data_format = "json"
json_transformation = '{"sensorID":"owm","type":"humidity","value":fields.main_humidity,"timestamp":timestamp}'
[[inputs.http]]
urls = [
"https://api.openweathermap.org/data/2.5/weather?lat={$LAT}&lon={$LON}2&appid=${API_KEY}&units=metric"
]
data_format = "json"
Here we:
Retrieve data from OWM in input plugin.
Transform received data structure in needed structure in two different output plugins. We use this language https://jsonata.org/ for this aim.

Working Google Sheets formula to check the Float

I want a formula to fetch the Float of eg BEKB.BR
https://finance.yahoo.com/quote/BEKB.BR/key-statistics?p=BEKB.BR
it's 36.45M
Formula's like
=index(IMPORTHTML("http://finance.yahoo.com/q/ks?s= BEKB.BR+Key+Statistics","table", 2), 4, 2)
or the ticker in cell A27:
=index(IMPORTHTML("http://finance.yahoo.com/q/ks?s="& $A$27&"+Key+Statistics","table", 2), 4, 2)
don't give a result.
Thanks for your help.
The IMPORTHTML() and IMPORTXML() functions don't fetch this page for some reason I don't know.
You can use URLFetchApp in Google Apps Script instead.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
function fetch() {
//Replace the "A2" with A1 notation of the cell which you'd like to type the keys
const key = sheet.getRange("A2").getValue();
url = `https://finance.yahoo.com/quote/${key}/key-statistics`;
const response = UrlFetchApp.fetch(url).getContentText();
//We will use Cheerio for HTML parsing
const $ = Cheerio.load(response);
const value = $('fin-streamer[data-field="regularMarketPrice"][data-test="qsp-price"]').text();
//Replace the "B2" with A1 notation of your target cell
sheet.getRange('B2').setValue(value || "Not found!");
}
And my apsscript.json manifest file is as follows:
{
"timeZone": "Europe/Istanbul", //or whatever
"dependencies": {
"libraries": [
{
"userSymbol": "Cheerio",
"version": "14",
"libraryId": "1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0"
}
]
},
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/spreadsheets.currentonly"
],
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
Here is a working example. When you click on the button it writes the Float value to A2 cell.

How to maintain data type in respond after connecting with Datastax Astra DB?

I am using Datastax Astra database. I am uploading csv file and I am setting all the columns data type as float, as per column. I connected with my db via python http_method.
res = astra_client.request(
method=http_methods.GET,
path=f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}/rows")
This gives me all the rows, but the data type is not maintained in the respond. All the float converted to string. Why and How can I solve this ?
{'PetalWidthCm': '0.2', 'Id': 23, 'PetalLengthCm': '1.0', 'SepalWidthCm': '3.6', 'Species': 'Iris-setosa', 'SepalLengthCm': '4.6'}
How are you creating your table and adding data? For example, the following works for me.
import http.client
import json
ASTRA_TOKEN = ""
ASTRA_DB_ID = ""
ASTRA_DB_REGION = ""
ASTRA_DB_KEYSPACE = "testks"
ASTRA_DB_COLLECTION = "float_test"
conn = http.client.HTTPSConnection(f"{ASTRA_DB_ID}-{ASTRA_DB_REGION}.apps.astra.datastax.com")
headers = {
'X-Cassandra-Token': ASTRA_TOKEN,
'Content-Type': 'application/json'
}
# Create the table
createTablePayload = json.dumps({
"name": f"{ASTRA_DB_COLLECTION}",
"columnDefinitions": [
{"name": "id", "typeDefinition": "text"},
{"name": "floatval", "typeDefinition": "float"},
{"name": "intval", "typeDefinition": "int"},
{"name": "doubleval", "typeDefinition": "double"}
],
"primaryKey": {"partitionKey": ["id"]},
"ifNotExists": True
})
# Add some data
conn.request("POST", f"/api/rest/v2/schemas/keyspaces/{ASTRA_DB_KEYSPACE}/tables", createTablePayload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
addRowPayload = json.dumps({
"id": "af2603d2-8c03-11eb-a03f-0ada685e0000",
"floatval": 1.1,
"intval": 2,
"doubleval": 3.3
})
conn.request("POST", f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}", addRowPayload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
# Read back the data
conn.request("GET", f"/api/rest/v2/keyspaces/{ASTRA_DB_KEYSPACE}/{ASTRA_DB_COLLECTION}/rows", "", headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
The response from this is
$ python3 get_rows.py
{"name":"float_test"}
{"id":"af2603d2-8c03-11eb-a03f-0ada685e0000"}
{"count":1,"data":[{"id":"af2603d2-8c03-11eb-a03f-0ada685e0000","doubleval":3.3,"intval":2,"floatval":1.1}]}

Is there a way to use OCR to extract specific data from a CAD technical drawing?

I'm trying to use OCR to extract only the base dimensions of a CAD model, but there are other associative dimensions that I don't need (like angles, length from baseline to hole, etc). Here is an example of a technical drawing. (The numbers in red circles are the base dimensions, the rest in purple highlights are the ones to ignore.) How can I tell my program to extract only the base dimensions (the height, length, and width of a block before it goes through the CNC)?
The issue is that the drawings I get are not in a specific format, so I can't tell the OCR where the dimensions are. It has to figure out on its own contextually.
Should I train the program through machine learning by running several iterations and correcting it? If so, what methods are there? The only thing I can think of are Opencv cascade classifiers.
Or are there other methods to solving this problem?
Sorry for the long post. Thanks.
I feel you... it's a very tricky problem, and we spent the last 3 years finding a solution for it. Forgive me for mentioning the own solution, but it will certainly solve your problem: pip install werk24
from werk24 import Hook, W24AskVariantMeasures
from werk24.models.techread import W24TechreadMessage
from werk24.utils import w24_read_sync
from . import get_drawing_bytes # define your own
def recv_measures(message: W24TechreadMessage) -> None:
for cur_measure in message.payload_dict.get('measures'):
print(cur_measure)
if __name__ == "__main__":
# define what information you want to receive from the API
# and what shall be done when the info is available.
hooks = [Hook(ask=W24AskVariantMeasures(), function=recv_measures)]
# submit the request to the Werk24 API
w24_read_sync(get_drawing_bytes(), hooks)
In your example it will return for example the following measure
{
"position": <STRIPPED>
"label": {
"blurb": "ø30 H7 +0.0210/0",
"quantity": 1,
"size": {
"blurb": "30",
"size_type":" "DIAMETER",
"nominal_size": "30.0",
},
"unit": "MILLIMETER",
"size_tolerance": {
"toleration_type": "FIT_SIZE_ISO",
"blurb": "H7",
"deviation_lower": "0.0",
"deviation_upper": "0.0210",
"fundamental_deviation": "H",
"tolerance_grade": {
"grade":7,
"warnings":[]
},
"thread": null,
"chamfer": null,
"depth":null,
"test_dimension": null,
},
"warnings": [],
"confidence": 0.98810
}
or for a GD&T
{
"position": <STRIPPED>,
"frame": {
"blurb": "[⟂|0.05|A]",
"characteristic": "⟂",
"zone_shape": null,
"zone_value": {
"blurb": "0.05",
"width_min": 0.05,
"width_max": null,
"extend_quantity": null,
"extend_shape": null,
"extend": null,
"extend_angle": null
},
"zone_combinations": [],
"zone_offset": null,
"zone_constraint": null,
"feature_filter": null,
"feature_associated": null,
"feature_derived": null,
"reference_association": null,
"reference_parameter": null,
"material_condition": null,
"state": null,
"data": [
{
"blurb": "A"
}
]
}
}
Check the documentation on Werk24 for details.
Although a managed offering, Mixpeek is one free option:
pip install mixpeek
from mixpeek import Mixpeek
mix = Mixpeek(
api_key="my-api-key"
)
mix.upload(file_name="design_spec.dwg", file_path="s3://design_spec_1.dwg")
This /upload endpoint will extract the contents of your DWG file, then when you search for terms it will include the file_path so you can render it in your HTML.
Behind the scenes it uses the open source LibreDWG library to run a number of AutoCAD native commands such as DATAEXTRACTION.
Now you can search for a term and the relevant DWG file (in addition to the context in which it exists) will be returned:
mix.search(query="retainer", include_context=True)
[
{
"file_id": "6377c98b3c4f239f17663d79",
"filename": "design_spec.dwg",
"context": [
{
"texts": [
{
"type": "text",
"value": "DV-34-"
},
{
"type": "hit",
"value": "RETAINER"
},
{
"type": "text",
"value": "."
}
]
}
],
"importance": "100%",
"static_file_url": "s3://design_spec_1.dwg"
}
]
More documentation here: https://docs.mixpeek.com/

Type of data received from SQLAlchemy database to plot chart

I am trying to plot a graph using highcharts in Flask. I have no problems when I give the data in the code itself. But when I retrieve the data from the database, it returns with a , in the end like
[(72,),(70.5,),(78.8,),(73,),(76,),(75,),]
So, this is not passing the data to the graph and I have an empty space on the webpage.
This is the code I have used:
views.py
#control.route("/")
def index(chartID = 'chart_ID', chart_type = 'line', chart_height = 350):
chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,}
series = [{"data": [tempg()]}]
title = {"text": 'My Title'}
xAxis = {"title": {"text": 'xAxis Label'}}
yAxis = {"title": {"text": 'yAxis Label'}}
return render_template('control/index.html', uptime=GetUptime(), chartID=chartID, chart=chart, series=series, title=title, xAxis=xAxis, yAxis=yAxis)
def tempg():
tempgrs = [tempg for tempg in Temperature.query.with_entities(Temperature.tempft).all()]
return tempgrs
Is it because of the extra comma at the end, that i'm not able to get the chart or is it any other coding fault.
Thanks in Advance.

Resources