Dart intl how to omit name and arguments - dart

I am trying to omit passing name and arguments into Intl.message. Intl documentation suggests that, there is a transformer provided that will automatically insert those parameters for you.
So I added following into pubspec.yaml:
dev_dependencies:
intl_translation: ^0.17.3
transformers:
- intl_translation:
$include: lib/localization.dart
In my localization.dart I have following method:
class AppLocalizations {
...
String greetingMessage(String name) => Intl.message(
"Hello $name!",
desc: "Greet the user as they first open the application",
examples: const {'name': "Emily"});
}
When I run flutter pub pub run intl_translation:extract_to_arb --output-dir=strings lib/localization.dart I have the following error:
<Intl.message("Hello $name!", desc: "Greet the user as they first open the application", examples: const {'name' : "Emily"})>
reason: The 'args' argument for Intl.message must be specified for messages with parameters. Consider using rewrite_intl_messages.dart
How I can enable that transformer?

Your error:
reason: The 'args' argument for Intl.message must be specified for
messages with parameters. Consider using rewrite_intl_messages.dart
Is because your Intl.message() has an argument in it, name, so you must also add: args: [name]
String greetingMessage(String name) => Intl.message(
"Hello $name!",
args: [name]
desc: "Greet the user as they first open the application",
examples: const {'name': "Emily"});
See: https://api.flutter.dev/flutter/intl/Intl/message.html
The args is a list containing the arguments of the enclosing function.
If there are no arguments, args can be omitted.
But you do have an argument, so it cannot be omitted.

Related

Is there a way to write single prepare function for all the KPIs in Gramex

I have a common function which needs to be evaluated before executing all the KPIs. So I wrote a prepare function but prepare function is calling for all the KPIs separately. Instead I want a prepare function to be executed once for the each endpoint. My endpoint is like this
project-test:
pattern: /$YAMLURL/test
handler: FormHandler
kwargs:
auth: &AUTH
login_url: /$YAMLURL/login
kpi1:
prepare: validations.validate_request(args, handler)
url: $CONNECTION_STRING
queryfunction: queries.query1(args)
kpi2:
prepare: validations.validate_request(args, handler)
url: $CONNECTION_STRING
queryfunction: queries.query2(args)
modify: project.refactor(data, handler)
I tried to giving prepare function in the kwargs but getting
AttributeError: 'str' object has no attribute 'get'
The approach you shared is correct. The error may be in one of the custom functions, e.g. validations.validate_request, queries.query* or project.refactor
To test this, I created the following data1.csv
a,b
1,2
3,4
... and data2.csv
a,b
4,5
6,7
This is my gramex.yaml
url:
project-test:
pattern: /$YAMLURL/test
handler: FormHandler
kwargs:
kpi1:
prepare: validations.validate_request(args, handler)
url: data1.csv
kpi2:
prepare: validations.validate_request(args, handler)
url: data2.csv
... and this is my validations.py:
def validate_request(args, handler):
print(args, handler)
args['_c'] = ['a'] # Filter column 'a' alone
When I visit /test, the output only shows column 'a':
{"kpi1":[{"a":1},{"a":3}],"kpi2":[{"a":4},{"a":6}]}
... and the command prompt shows that the prepare function is called once for each dataset:
{'_limit': [10000]} <gramex.services.FormHandler object at 0x000001B1C14A43C8>
{'_limit': [10000]} <gramex.services.FormHandler object at 0x000001B1C14A43C8>
Perhaps you could share the full error message about where the AttributeError appeared? That might help.
I guess this is more of a prepare function issue. Could you please check if you are trying to access a string using its key. Just a quick hypothesis - check if any of your dict is in json/ string format.

How to escape - (hyphen) using the groovy language

I am trying to declare a variable that requires hyphen as part of the design spec.
def user-svc = "accounts"
However, i am getting this error -
https://www.tutorialspoint.com/execute_groovy_online.php
$groovy main.groovy
Hello world
Caught: groovy.lang.MissingPropertyException: No such property: user for class: main
groovy.lang.MissingPropertyException: No such property: user for class: main
at main.run(main.groovy:3)
Local variable names must be normal groovy identifiers, which doesn't include the hyphen.
Though any object property name can consist of arbitrary characters, when using quoted identifiers or subscript operator:
def m = [:]
m.'user-svc' = "accounts"
println m.'user-svc'
println m['user-svc']

CDK generating empty targets for CfnCrawler

I'm using CDK Python API to define a Glue crawler, however, the CDK generated template contains empty 'Targets' block in the Crawler resource.
I've not been able to find an example to emulate. I've tried varying the definition of the targets object, but the object definition seems to be ignored by CDK.
from aws_cdk import cdk
BUCKET='poc-1-bucket43879c71-5uabw2rni0cp'
class PocStack(cdk.Stack):
def __init__(self, app: cdk.App, id: str, **kwargs) -> None:
super().__init__(app, id)
from aws_cdk import (
aws_iam as iam,
aws_glue as glue,
cdk
)
glue_role = iam.Role(
self, 'glue_role',
assumed_by=iam.ServicePrincipal('glue.amazonaws.com'),
managed_policy_arns=['arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole']
)
glue_crawler = glue.CfnCrawler(
self, 'glue_crawler',
database_name='db',
role=glue_role.role_arn,
targets={"S3Targets": [{"Path": f'{BUCKET}/path/'}]},
)
I expect the generated template to contain a valid 'targets' block with a single S3Target. However, cdk synth outputs a template with empty Targets in the AWS::Glue::Crawler resource:
gluecrawler:
Type: AWS::Glue::Crawler
Properties:
DatabaseName: db
Role:
Fn::GetAtt:
- glueroleFCCAEB57
- Arn
Targets: {}
Resolved, thanks to a clever colleague!
Changing "S3Targets" to "s3Targets", and "Path" to "path" resolved the issue. See below.
Hi Bob,
When I use typescript, the following works for me:
new glue.CfnCrawler(this, 'glue_crawler', {
databaseName: 'db',
role: glue_role.roleArn,
targets: {
s3Targets: [{ path: "path" }]
}
}
When I used Python, the following appears working too:
glue_crawler = glue.CfnCrawler(
self, 'glue_crawler',
database_name='db',
role=glue_role.role_arn,
targets={
"s3Targets": [{ "path": f'{BUCKET}/path/'}]
},
)
In Typescript, TargetsProperty is an interface with s3Targets as a property. And in
s3Targets, path is a property as well. I guess during the JSII transformation, it forces
us to use the same names in Python instead of the initial CFN resource names.
A more general way to approach this problem is to dig inside the cdk library in 2 steps:
1.
from aws_cdk import aws_glue
print(aws_glue.__file__)
(.env/lib/python3.8/site-packages/aws_cdk/aws_glue/__init__.py)
Go to that file and see how the mapping/types are defined. As of 16 Aug 2020, you find
#jsii.data_type(
jsii_type="#aws-cdk/aws-glue.CfnCrawler.TargetsProperty",
jsii_struct_bases=[],
name_mapping={
"catalog_targets": "catalogTargets",
"dynamo_db_targets": "dynamoDbTargets",
"jdbc_targets": "jdbcTargets",
"s3_targets": "s3Targets",
}
)
I found that the lowerCamelCase always work, while the pythonic snake_case does not.

Argument Error when trying to specify :env in Elixir Port.open

I'm trying to set an environment variable when running a shell command using Port.open. It raises an error, ArgumentError no matter what I pass in.
port = Port.open({ :spawn_executable, "/usr/local/bin/cool" },
[:stream, :in, :binary, :eof, :hide,
{:env, [{"COOL_ENV", "cool"}]},
{ :args, ["test.js"] }])
According to the Elixir docs for Port.open, it should accept any arguments that the Erlang function :erlang.open_port accepts. The Erlang documentation mentions:
{env, Env} Only valid for {spawn, Command}, and {spawn_executable,
FileName}. The environment of the started process is extended using
the environment specifications in Env.
Env is to be a list of tuples {Name, Val}, where Name is the name of
an environment variable, and Val is the value it is to have in the
spawned port process. Both Name and Val must be strings. The one
exception is Val being the atom false (in analogy with os:getenv/1,
which removes the environment variable.
(http://erlang.org/doc/man/erlang.html#open_port-2)
This error occurs even if I try to call the erlang function directly like so:
:erlang.open_port({:spawn_executable, "/usr/local/bin/cool"}, [:stream, :in, :binary, :eof, :hide, {:env, [{"COOL", "cool"}] },{:args, ["test.js"]}])
The error goes away if I remove the {:env, [{...}] argument.
The :env option requires both the name and the value to be Erlang strings, which is called a charlist in Elixir, and is constructed using single quotes instead of double.
Opt =
...
{env, Env :: [{Name :: string(), Val :: string() | false}]} |
...
Source
The following should fix the error:
port = Port.open({ :spawn_executable, "/usr/local/bin/cool" },
[:stream, :in, :binary, :eof, :hide,
{:env, [{'COOL_ENV', 'cool'}]},
{ :args, ["test.js"] }])
:args accepts both Erlang strings and Erlang binaries (Elixir Strings), so you don't need to change that.

grails changelog preconditions not doing anything

I am trying to make changes to the database using the changelog. Since I cannot guarantee that the values currently exist for the specific code, but could exist, I need to be able to check for them in order to either do an insert or an update.
Here is what I have been testing, which doesn't appear to do anything. Any words of advice are welcome.
databaseChangeLog = {
changeSet(author:'kmert', id:'tubecap-insert-update-1') {
preConditions(onFail="WARN",onFailMessage:"Tube cap does not exist,skipping because it cannot be updated."){
sqlCheck(expectedResult='1', 'SELECT * FROM [ltc2_tube_cap] WHERE code=11')
}
grailsChange {
change {
sql.execute("""
UPDATE [ltc2_tube_cap]
SET [name] = 'White'
WHERE [code] = 11;
""")
}
rollback {
}
}
}
}
UPDATE: I got the changelog script running, but I am now getting this error. I found the code from an online source. I cannot find a lot of documentation on preconditions...
| Starting dbm-update for database hapi_app_user # jdbc:jtds:sqlserver://localhost;databaseName=LabTraffic;MVCC=TRUE;LOCK_TIMEOUT=10000
problem parsing TubeCapUpdate.groovy: No signature of method: grails.plugin.databasemigration.DslBuilder.sqlCheck() is applicable for argument types: (java.lang.String, java.lang.String) values: [1, SELECT * FROM ltc2_tube_cap WHERE code=11] (re-run with --verbose to see the stacktrace)
problem parsing changelog.groovy: No signature of method: grails.plugin.databasemigration.DslBuilder.sqlCheck() is applicable for argument types: (java.lang.String, java.lang.String) values: [1, SELECT * FROM ltc2_tube_cap WHERE code=11] (re-run with --verbose to see the stacktrace)
groovy.lang.MissingMethodException: No signature of method: grails.plugin.databasemigration.DslBuilder.sqlCheck() is applicable for argument types: (java.lang.String, java.lang.String) values: [1, SELECT * FROM ltc2_tube_cap WHERE code=11]
at grails.plugin.databasemigration.DslBuilder.invokeMethod(DslBuilder.groovy:117)
at Script1$_run_closure1_closure2_closure3.doCall(Script1.groovy:13)
at grails.plugin.databasemigration.DslBuilder.invokeMethod(DslBuilder.groovy:117)
at Script1$_run_closure1_closure2.doCall(Script1.groovy:12)
at grails.plugin.databasemigration.DslBuilder.invokeMethod(DslBuilder.groovy:117)
at Script1$_run_closure1.doCall(Script1.groovy:11)
at grails.plugin.databasemigration.GrailsChangeLogParser.parse(GrailsChangeLogParser.groovy:84)
at grails.plugin.databasemigration.DslBuilder.handleIncludedChangeLog(DslBuilder.groovy:747)
at grails.plugin.databasemigration.DslBuilder.createNode(DslBuilder.groovy:139)
at grails.plugin.databasemigration.DslBuilder.createNode(DslBuilder.groovy:590)
at grails.plugin.databasemigration.DslBuilder.invokeMethod(DslBuilder.groovy:117)
at Script1$_run_closure1.doCall(Script1.groovy:6)
at grails.plugin.databasemigration.GrailsChangeLogParser.parse(GrailsChangeLogParser.groovy:84)
at liquibase.Liquibase.update(Liquibase.java:107)
at DbmUpdate$_run_closure1_closure2.doCall(DbmUpdate:26)
at _DatabaseMigrationCommon_groovy$_run_closure2_closure11.doCall(_DatabaseMigrationCommon_groovy:59)
at grails.plugin.databasemigration.MigrationUtils.executeInSession(MigrationUtils.groovy:133)
at _DatabaseMigrationCommon_groovy$_run_closure2.doCall(_DatabaseMigrationCommon_groovy:51)
at DbmUpdate$_run_closure1.doCall(DbmUpdate:25)
Your syntax is incorrect for the sqlCheck preCondition.
sqlCheck(expectedResult:'1', 'SELECT * FROM [ltc2_tube_cap] WHERE code=11')
Notice in your code the first argument is an assignment statement expectedResult=1 and it should be a map entry expectedResult:1.
I found the answer buried on this Jira page. https://jira.grails.org/browse/GPDATABASEMIGRATION-40 which ironically is about adding lots of examples to the DB migration DSL to the documentation.
Make sure the following
grails dbm-gorm-diff add-your-file-forupdate.groovy -add
then inside your-file-forupdate.groovy is expected to see
databaseChangeLog = {
changeSet(author:'kmert', id:'tubecap-insert-update-1') {
.
.
.
}
}
Then ,the Big deal is either you have included this as migration script file to be executed as follow:
just manually add a line like the following to the end of grails-app/migrations/changelog.groovy:
include file: 'your-file-forupdate.groovy'
The changelog.groovy is always run from beginning to end, so make sure that you always add newly created migrations to the end.
Cheers! for more info see this

Resources