Syntax error : unexpected token: identifier - gnome-shell-extensions

I wish to display a mail icon with a counter
With my gnome-shell extension I get an error:
I don't know what the error means.
Keep in mind I do not have much knowledge about gnome..
Syntax error : unexpected token : identifier
const INDICATOR_ICON = 'mail-unread-symbolic';
const PanelMenu = imports.ui.panelMenu;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
class Extension extends PanelMenu.Button {
_init() {
super._init(0.0, null, false);
this._icon = new St.Icon({
icon_name: INDICATOR_ICON,
style_class: 'system-status-icon'});
this._iconBin = new St.Bin({ child: this._icon, x_fill: false, y_fill: false });
this._counterLabel = new St.Label({ text: "0",
x_align: Clutter.ActorAlign.CENTER,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
y_expand: true });
this._counterBin = new St.Bin({ style_class: 'mailnag-counter',
child: this._counterLabel,
layout_manager: new Clutter.BinLayout() });
this.add_actor(this._iconBin);
this.add_actor(this._counterBin);
}
}
function enable() {
return New Extension();
}
function disable() {
}

Related

Devexpress file manager using asp.net file system provider

I implemented devextreme to my react project.I'm using file manager system and I'm using devexpress for create system provider with my asp.net project.
I have an issue.
When i try to upload any file I'm getting and error.Download,move,copy is working very well.But i cant upload any file.
File uploaded succesfully my temp folder but then doesnt move to my real path.How can i fix this.Devexpress version 20.1
public object FileSystem(long id, FileSystemCommand command, string arguments, HttpRequest Request)
{
var path = Path.Combine(HostingEnvironment.ContentRootPath, "../files/Images/", id.ToString());
var config = new FileSystemConfiguration
{
Request = Request,
FileSystemProvider = new PhysicalFileSystemProvider(
path,
(fileSystemItem, clientItem) =>
{
if (!clientItem.IsDirectory)
clientItem.CustomFields["url"] = GetFileItemUrl(fileSystemItem, Request);
}
),
//uncomment the code below to enable file/folder management
AllowCopy = true,
AllowCreate = true,
AllowMove = true,
AllowDelete = true,
AllowRename = true,
AllowUpload = true,
AllowDownload = true,
AllowedFileExtensions = new[] { ".txt", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".png", ".jpg", ".jpeg", ".gif", ".csv" }
};
var processor = new FileSystemCommandProcessor(config);
var result = processor.Execute(command, arguments);
return result.GetClientCommandResult();
}
Here is the front end code
import React from "react";
import FileManager, { Permissions } from "devextreme-react/file-manager";
import RemoteFileSystemProvider from "devextreme/file_management/remote_provider";
import { Popup } from "devextreme-react/popup";
let remoteProvider = new RemoteFileSystemProvider({
endpointUrl: "https://myapiurl.com.tr/api/FileManager/FileSystem/121",
});
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
currentPath: "Widescreen",
popupVisible: false,
imageItemToDisplay: {},
remoteProvider: new RemoteFileSystemProvider({
endpointUrl: "https://myapiurl.com.tr/api/FileManager/FileSystem/121",
}),
};
this.displayImagePopup = this.displayImagePopup.bind(this);
this.hideImagePopup = this.hideImagePopup.bind(this);
this.onCurrentDirectoryChanged = this.onCurrentDirectoryChanged.bind(this);
}
displayImagePopup(e) {
this.setState({
popupVisible: true,
imageItemToDisplay: {
name: e.file.name,
url: e.file.dataItem.url,
},
});
}
hideImagePopup() {
this.setState({
popupVisible: false,
});
}
onCurrentDirectoryChanged(e) {
this.setState({
currentPath: e.component.option("currentPath"),
});
}
render() {
console.log(remoteProvider);
return (
<>
{this.props.investment ? (
<div>
<FileManager
currentPath={this.state.currentPath}
fileSystemProvider={remoteProvider}
onSelectedFileOpened={this.displayImagePopup}
onCurrentDirectoryChanged={this.onCurrentDirectoryChanged}
>
<Permissions
create={true}
copy={true}
move={true}
delete={true}
rename={true}
upload={true}
download={true}
></Permissions>
</FileManager>
<Popup
maxHeight={600}
closeOnOutsideClick={true}
title={this.state.imageItemToDisplay.name}
visible={this.state.popupVisible}
onHiding={this.hideImagePopup}
className="photo-popup-content"
>
<img src={this.state.imageItemToDisplay.url} className="photo-popup-image" />
</Popup>
</div>
) : (
""
)}
</>
);
}
}
export default App;
We had the same issue lately, if I'm not mistaken, it was related to a mismatch between some DLLs versions of the project. The client-side version must match the FileSystemCommandeProcessor version. The DevExtreme team seems to have changed some property name which cause this issue.

How to make DynamoDB Table calls to different location than lambda endpoint?

I am trying to access a table in DynamoDB which is hosted in Europe (Ireland) eu-west-1, from a lambda endpoint which is hosted in US East (N. Virginia) us-east-1 - however, I am always getting the error:
{
"message": "Requested resource not found",
"code": "ResourceNotFoundException",
"time": "2020-07-05T22:13:17.145Z",
"requestId": "6SGPGDFVN6AE4QMC5A8LG2RJ0JVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 27.110475966612935
}
this is my code my code to call the DB:
class DynamoDB {
constructor() {
this.region = 'eu-west-1';
this.endpoint = 'https://dynamodb.eu-west-1.amazonaws.com';
this.tableName = 'MyTableName';
this.docClient = new AWS.DynamoDB.DocumentClient();
}
getUser(userId) {
return new Promise((resolve, reject) => {
const params = {
TableName: this.tableName,
Key: {
"id": userId,
}
}
this.docClient.get(params, function(err, data) {
if (err || !data.Item) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
return reject(JSON.stringify(err, null, 2))
} else {
console.log("GetItem data succeeded:", JSON.stringify(data, null, 2));
resolve(data.Item);
}
});
});
}
}
const DynamoDB = require("../Libraries/DynamoDB");
const $ = new DynamoDB;
const Interceptor = {
async process(session) {
return $.getUser(session.id).then(data => {
console.log(`User gotten! ${JSON.stringify(data, null, 2)}`);
}).catch(err => {
console.log(`Failure getting user... ${err}`);
};
}).finally(async () => {
await InitGameSettings();
});
}
When I attempt this using an endpoint that is hosted in the same region as the DynamoDB table - it works fine! Only when I try this using different regions does it break. Why is this?
Looks like the SDK is not using the DDB region and endpoint that you configured. Could you try replacing the constructor() with the following code snippet?
constructor() {
this.region = 'eu-west-1';
this.endpoint = 'https://dynamodb.eu-west-1.amazonaws.com';
this.tableName = 'MyTableName';
this.ddbService = new AWS.DynamoDB({
apiVersion: '2012-08-10',
endpoint: this.endpoint,
region: this.region
});
this.docClient = new AWS.DynamoDB.DocumentClient({
service: this.ddbService
});
}

Error UseHealthChecksUI Unexpected character encountered

I'm trying to implement the ASP.NET Core 2.2 health check feature. Setting up the health check itself isn't the problem, but I also want to be able to use the UI feature in other project to monitoring all my apis. Right now I get the exception message
Unexpected character encountered while parsing value: <.
What I'm doing bad?
API Project:
var healthCheckOptions = new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = async (c, r) =>
{
c.Response.ContentType = MediaTypeNames.Application.Json;
var result = JsonConvert.SerializeObject(
new
{
Checks = r.Entries.Select(e =>
new
{
Description = e.Key,
Status = e.Value.Status.ToString(),
ResponseTime = e.Value.Duration.TotalMilliseconds
}),
TotalResponseTime = r.TotalDuration.TotalMilliseconds
});
await c.Response.WriteAsync(result);
}
};
app.UseHealthChecks("/live", new HealthCheckOptions
{
Predicate = _ => true
});
app.UseHealthChecks("/hc", healthCheckOptions);
app.UseHealthChecksUI(options => options.UIPath = "/healtcheck");
// Registers required services for health checks
services
.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy())
.AddCheck("ComunContext Database", new SqlServerHealthCheck(configuration["ConnectionStrings:ComunContext"]));
Web project:
services.AddHealthChecksUI();
app.UseHealthChecksUI(config =>
{
config.UIPath = "/healthcheck";
});
appsettings.json
{
"HealthChecks-UI": {
"HealthChecks": [
{
"Name": "Local",
"Uri": "http://localhost:27365/hc"
}
],
"EvaluationTimeOnSeconds": 10,
"MinimumSecondsBetweenFailureNotifications": 60
}
}
Try adding a ResponseWriter:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHealthChecks("/healthchecks", new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
context.Response.ContentType = "application/json; charset=utf-8";
var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(report));
await context.Response.Body.WriteAsync(bytes);
}
});
app.UseHealthChecksUI();
}
After a few days struggling with this parser error, I've figured out that there are 2 problems:
1 - If you have an Exception, Health UI tries to convert Exception object field, resulting on error;
2 - If you try to pass your own anonymous object, Health UI fails to convert Entries collection, because it need to be an specific anonymous Dictionary.
Try this:
var healthCheckOptions = new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = async (c, r) =>
{
c.Response.ContentType = MediaTypeNames.Application.Json;
var result = JsonConvert.SerializeObject(
new
{
Checks = r.Entries.ToDictionary(
e => e.Key,
e =>
new
{
Description = e.Key,
Status = e.Value.Status.ToString(),
ResponseTime = e.Value.Duration.TotalMilliseconds
}),
TotalResponseTime = r.TotalDuration.TotalMilliseconds
});
await c.Response.WriteAsync(result);
}
};

How to dynamically update an attribute in a dynamodb item?

I created an item in dynamodb using Node js, the item has multiple attributes such as brand, category, discount, validity, etc. I am using uuid to generate ids for each item. Now let's say I want to update the validity attribute of the item, in which case I am currently sending the entire json object with the value of validity modified to the new value.
This is definitely not optimal, please help me find an optimal solution.
const params = {
TableName: process.env.PRODUCT_TABLE,
Key: {
id: event.pathParameters.id,
},
ExpressionAttributeNames: {
'#discount': 'discount',
},
ExpressionAttributeValues: {
':brand': data.brand,
':category': data.category,
':discount': data.discount,
':denominations': data.denominations,
":validity": data.validity,
":redemption": data.redemption
},
UpdateExpression: 'SET #discount = :discount, denominations = :denominations, brand = :brand, category = :category, validity = :validity, redemption = :redemption',
ReturnValues: 'ALL_NEW',
};
I want to send just the attribute I want to update with the new value, if I want to change the validity from 6 months to 8 months, I should just send something like:
{
"validity": "8 months"
}
And it should update the validity attribute of the item.
Same should apply to any other attribute of the item.
'use strict';
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.update = (event, context, callback) => {
const data = JSON.parse(event.body);
let attr = {};
let nameobj = {};
let exp = 'SET #';
let arr = Object.keys(data);
let attrname = {};
arr.map((key) => {attr[`:${key}`]=data[key]});
arr.map((key) => {
exp += `${key} = :${key}, `
});
arr.map((key) => {nameobj[`#${key}`]=data[key]});
attrname = {
[Object.keys(nameobj)[0]] : nameobj[Object.keys(nameobj)[0]]
}
const params = {
TableName: process.env.PRODUCT_TABLE,
Key: {
id: event.pathParameters.id,
},
ExpressionAttributeNames: attrname,
ExpressionAttributeValues: attr,
UpdateExpression: exp,
ReturnValues: 'ALL_NEW',
};
// update the todo in the database
dynamoDb.update(params, (error, result) => {
// handle potential errors
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
headers: { 'Content-Type': 'text/plain' },
body: 'Couldn\'t update the card',
});
return;
}
// create a response
const response = {
statusCode: 200,
body: JSON.stringify(result.Attributes),
};
callback(null, response);
});
};
Contrary to others comments, this is very possible, use the UpdateItem action.
Language agnostic API docs
JavaScript specific API docs
If you want to dynamically create the query, try something like this:
const generateUpdateQuery = (fields) => {
let exp = {
UpdateExpression: 'set',
ExpressionAttributeNames: {},
ExpressionAttributeValues: {}
}
Object.entries(fields).forEach(([key, item]) => {
exp.UpdateExpression += ` #${key} = :${key},`;
exp.ExpressionAttributeNames[`#${key}`] = key;
exp.ExpressionAttributeValues[`:${key}`] = item
})
exp.UpdateExpression = exp.UpdateExpression.slice(0, -1);
return exp
}
let data = {
'field' : { 'subfield': 123 },
'other': '456'
}
let expression = generateUpdateQuery(data)
let params = {
// Key, Table, etc..
...expression
}
console.log(params)
Output:
{
UpdateExpression: 'set #field = :field, #other = :other',
ExpressionAttributeNames: {
'#field': 'field',
'#other': 'other'
},
ExpressionAttributeValues: {
':field': {
'subfield': 123
},
':other': '456'
}
}
Using Javascript SDK V3:
Import from the right package:
import { DynamoDBClient PutItemCommandInput, UpdateItemCommandInput, UpdateItemCommand } from '#aws-sdk/client-dynamodb';
Function to dynamically do partial updates to the item:
(the code below is typescript can be easily converted to Javascript, just remove the types!)
function updateItem(id: string, item: any) {
const dbClient = new DynamoDBClient({region: 'your-region-here });
let exp = 'set ';
let attNames: any = { };
let attVal: any = { };
for(const attribute in item) {
const valKey = `:${attribute}`;
attNames[`#${attribute}`] = attribute;
exp += `#${attribute} = ${valKey}, `;
const val = item[attribute];
attVal[valKey] = { [getDynamoType(val)]: val };
}
exp = exp.substring(0, exp.length - 2);
const params: UpdateItemCommandInput = {
TableName: 'your-table-name-here',
Key: { id: { S: id } },
UpdateExpression: exp,
ExpressionAttributeValues: attVal,
ExpressionAttributeNames: attNames,
ReturnValues: 'ALL_NEW',
};
try {
console.debug('writing to db: ', params);
const command = new UpdateItemCommand(params);
const res = await dbClient.send(command);
console.debug('db res: ', res);
return true;
} catch (err) {
console.error('error writing to dynamoDB: ', err);
return false;
}
}
And to use it (we can do partial updates as well):
updateItem('some-unique-id', { name: 'some-attributes' });
What i did is create a helper class.
Here is a simple function : Add all the attribute and values that goes into, if the value is null or undefined it won't be in the expression.
I recommande to create a helper class with typescript and add more functions and other stuff like generator of expressionAttributeValues , expressionAttributeNames ... , Hope this help.
function updateExpression(attributes, values) {
const expression = attributes.reduce((res, attribute, index) => {
if (values[index]) {
res += ` #${attribute}=:${attribute},`;
}
return res;
}, "SET ");
return expression.slice(0, expression.length - 1)
}
console.log(
updateExpression(["id", "age", "power"], ["e8a8da9a-fab0-55ba-bae3-6392e1ebf624", 28, undefined])
);
You can use code and generate the params object based on the object you provide. It's just a JavaScript object, you walk through the items so that the update expression only contains the fields you have provided.
This is not really a DynamoDB question in that this is more a general JS coding question.
You can use UpdateItem; to familiarize yourself with DynamoDb queries I would suggest you DynamoDb NoSQL workbench:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.settingup.html
It can generate snippets for you based on your queries.
DynamoDb NoSQL workbench screenshot query

Parse JSON and return false if is not a valid JSON

If for any reason, is not a valid JSON, how to return false?
var ajv = new Ajv();
var schema = {
"properties": {
"payload": { "type": "string" },
"topic": { "type": "string" }
},
additionalProperties: false
};
var validate = ajv.compile(schema);
// My json string on property payload
const payloadLeans = R.lensProp('payload');
const payloadView = R.view(payloadLeans);
// get payload and parse JSON
const utf8String = prop => { console.log(prop); return prop.toString('utf-8'); } ;
const getPayload = R.pipe(R.over(payloadLeans, utf8String), payloadView, JSON.parse);
// My SCHEMA validation
const isPayloadValid = R.pipe(getPayload, validate);
const myInvalObj = {
payload: 'hello": "World" }', // INVALID JSON
topic: 'robot/20:30:AA:13'
};
const isValid = R.both(validate, getPayload)(myInvalObj); // ERROR! SHOULD RETURN FALSE
console.log(isValid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/5.0.1/ajv.bundle.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.23.0/ramda.min.js"></script>
Simple use a tryCatch ..
const isPayloadValid = R.pipe(R.tryCatch(getPayload, R.F), validate);

Resources