Dumping whole array: console.log and console.dir output "... NUM more items]" - arrays

I am trying to log a long array so I can copy it quickly in my terminal. However, if I try and log the array it looks like:
['item',
'item',
>>more items<<<
... 399 more items ]
How can I log the entire array so I can copy it really quickly?

Setting maxArrayLength
There are a few methods all of which require setting maxArrayLength which otherwise defaults to 100.
Provide the override as an option to console.dir
console.dir(myArry, {'maxArrayLength': null});
Set util.inspect.defaultOptions.maxArrayLength = null; which will impact all calls to console.log and util.format
Call util.inspect yourself with options.
const util = require('util')
console.log(util.inspect(array, { maxArrayLength: null }))

Michael Hellein's answer didn't work for me, but a close version did:
console.dir(myArray, {'maxArrayLength': null})
This was the only solution that worked for me as JSON.stringify() was too ugly for my needs and I didn't need to write the code to print it out one at a time.

Using console.table
Available in Node v10+, and all modern web-browsers, you can use console.table() instead, which will output a beautiful utf8 table where each row represents an element of the array.
> console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
┌─────────┬─────┐
│ (index) │ a │
├─────────┼─────┤
│ 0 │ 1 │
│ 1 │ 'Z' │
└─────────┴─────┘

Just found that option maxArrayLength works well with console.dir too:
console.dir(array, {depth: null, colors: true, maxArrayLength: null});

What's wrong with myArray.forEach(item => console.log(item))?

Related

Terraform - Impossible to apply rights at the same time as creating groups

I have to put a list of groups (var.dev) in the group 'cod-xxx01'.
My terraform creates all the groups and rights at the same time.
Is there a way to retrieve this list once the groups are created ? The 'depends_on' does not seem to work.
The problem is if groups in my variable "codeur" are not created, I have this error :
│ Error: Invalid index
│
│ on RightGroupMember.tf line 35, in resource "azuread_group_member" "Terra-Aad-Member-Con-Dev-Reader":
│ 35: group_object_id = azuread_group.Terra-Aad-Group-Right["${var.dev[count.index]}"].object_id
│ ├────────────────
│ │ azuread_group.Terra-Aad-Group-Right is object with 65 attributes
│ │ count.index is 10
│ │ var.dev is list of string with 11 elements
│
│ The given key does not identify an element in this collection value.
My code is :
variable "dev" {
type = list(string)
default = [
"rea-vma-dev01",
"rea-vma-rec01",
"rea-vma-pre04",
"con-bql-dev01",
"rea-bql-rec01",
"rea-ins-dev01",
"rea-ins-rec01",
"rea-ins-pre04",
"rea-rmq-dev01",
"rea-rmq-rec01",
"rea-rmq-pre04",
]
description = "Access for 'cod-xxx01'"
}
resource "azuread_group_member" "Terra-Aad-Member-Con-Dev-Reader" {
count = length(var.dev)
group_object_id = azuread_group.Terra-Aad-Group-Right["${var.dev[count.index]}"].object_id
member_object_id = azuread_group.Terra-Aad-Group["cod-xxx01"].object_id
depends_on = [
azuread_group.Terra-Aad-Group-Right
]
}
Thank you so much.
The others resource are :
For groups :
Right_Groups = {for x in csvdecode(file("${path.module}/_RightGroups.csv")) : x.droits_groups => x.description}
resource "azuread_group" "Terra-Aad-Group-Right" {
for_each = local.Right_Groups
display_name = lower(each.key)
security_enabled = true
description = each.value
}
The CSV for 'Right_Groups' :
droits_groups,description
rea-vma-dev01,dev01
rea-vma-rec01,rec01
rea-vma-pre04,pre04
con-bql-dev01,dev01
rea-bql-rec01,rec01
rea-ins-dev01,dev01
rea-ins-rec01,rec01
rea-ins-pre04,pre04
rea-rmq-dev01,dev01
rea-rmq-rec01,rec01
rea-rmq-pre04,pre04
I think it has everything you need.
What I would suggest here is using resource chaining with for_each [1]. So the azuread_group can remain as is, but you would have to change the azuread_group_member resource:
resource "azuread_group_member" "Terra-Aad-Member-Con-Dev-Reader" {
for_each = azuread_group.Terra-Aad-Group-Right
group_object_id = each.value.object_id
member_object_id = azuread_group.Terra-Aad-Group["cod-xxx01"].object_id
}
[1] https://www.terraform.io/language/meta-arguments/for_each#chaining-for_each-between-resources

Remove a group on strings from an object in ruby

So, I have the following
removed_caps = self.user.caps.reject { |c| c == 'test' || c == 'test1'}
I want to have test and test1 as configs so that I can add to these in the future.
so something like:
caps_to_remove = ENV['BLACK_LIST']
split_caps_to_remove = caps_to_remove.split(' ')
puts split_caps_to_remove -->>> ["test", "test1"]
How do I incorporate split_caps_to_remove in the original code?
Thanks.
You could change your code to:
removed_caps = self.user.caps.reject { |c| split_caps_to_remove.include?(c) }
Use Fixed-String Methods
Assuming you have some variables defined as in the example below, then you can use String#delete or String#delete! as a faster way to remove your unwanted characters. Consider:
caps = ENV['BLACKLIST']='TE'
str1, str2 = 'TEST', 'TEST1'
[str1, str2].map { _1.delete caps }
#=> ["S", "S1"]
Fewer methods in a chain are often faster, and String methods that operate on a fixed String are often and order of magnitude faster Regexp-related methods like #gsub or iterating over a collection.
See Also
You didn't provide your actual input or calling code, but in newer Ruby versions (including 3.1.2) there are some other related methods (some with bang methods, which are both useful and faster if you aren't using frozen strings) that may also help:
String#delete_prefix
String#delete_suffix
String#downcase
String#swapcase

Can't add anything correctly to useState array?

I'm new in React. I writed that code by following a tutorial.
I tried many ways but couldn't add new arrays correctly into useState array.
function TodoApp(){
const [liste, setListe] = useState( [] );
function listeyeEkle(e) {
console.log(e); // {yazi: "First", id: 0} It's great here, no problems.
setListe( [e, ...liste] ) // Console log in Picture 1
setListe( e ); // Console log in Picture 2
console.log(liste);
}
Picture 1
Picture 2
Something going wrong and it's adding a empty object into array??
Do you have any idea?
Thanks!
The way you wrote it, you are setting the correct array first:
setListe( [e, ...liste] )
Afterwards you are setting the state to the value of the inputs element:
setListe( e )
I think you should remove this line? Then it will work! But might not show up in console.log(liste), due to the async nature of setState()!

How to add entries to my map without overwrite existing with a fallback in case of empty

I'm trying to create a map from a list of files that changed in our SCM,
So far I've managed to get the list of the changed files(in the code below I put hard-coded example )
and then map them to the relevant services which I want to build.
I also added the fallback in case the path is not mapped in the "path2component" function.
My problem is that the map that I'm creating is always overriding itself,
and not inserting the entries one after the other as expected.
ChangedFilesList = [main/exporter/pom.xml, main/app/download-server/pom.xml]
ChangedFilesList.each {
println "Changes in file: ${it}"
def file = "${it}"
triggermap = path2component.findAll{ // find relevant map entries
file.find(it.key)
}.collectEntries{ // build your map
["trigger-${it.value}", true]
} ?: ["trigger-none": true] // provide a fallback
println "triggermap:" + triggermap
}
My output is this:
Changes in file: main/app/download-server/pom.xml
triggermap:[trigger-download-server:true]
Changes in file: main/exporter/pom.xml
triggermap:[trigger-rest-exporter:true]
Expected output:
Changes in file: main/app/download-server/pom.xml
triggermap:[trigger-download-server:true]
Changes in file: main/exporter/pom.xml
triggermap:[trigger-download-server:true,trigger-rest-exporter:true]
The following code:
def changedFiles = ['main/exporter/pom.xml', 'main/app/download-server/pom.xml']
def path2component = [
'main/exporter': 'rest-exporter',
'main/app/download-server': 'download-server'
]
def triggerMap = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.collectEntries { path, service ->
["trigger-${service}".toString(), true]
}.withDefault { false }
println triggerMap
println("rest-exporter: ${triggerMap['trigger-rest-exporter']}")
println("unchanged-service: ${triggerMap['trigger-unchanged-service']}")
uses the groovy map withDefault construct to specify a value which should be returned if a key is not found in the map. This code tries to mock your scenario with a path2component map. Result of running the above:
─➤ groovy solution.groovy
[trigger-rest-exporter:true, trigger-download-server:true]
rest-exporter: true
unchanged-service: false
However if they only thing you want to do is figure out if a service needs rebuilding, there is really no need to have the 'trigger-' prefix in there:
def simplerMap = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.collectEntries { path, service ->
[service, true]
}.withDefault { false }
println simplerMap
println("rest-exporter: ${simplerMap['rest-exporter']}")
println("unchanged-service: ${simplerMap['unchanged-service']}")
which prints:
─➤ groovy solution.groovy
[rest-exporter:true, download-server:true]
rest-exporter: true
unchanged-service: false
and if you don't have millions of items in this trigger map (i.e. performance is not an issue), you could also just do:
def changedServices = path2component.findAll { path, service ->
changedFiles.any { it.find(path) }
}.values()
println changedServices
println("rest-exporter: ${changedServices.contains('rest-exporter')}")
println("unchanged-service: ${changedServices.contains('unchanged-service')}")
which prints:
─➤ groovy solution.groovy
[rest-exporter, download-server]
rest-exporter: true
unchanged-service: false
Groovy provides variant of get, that lets you provide a fallback, which also get's written into the map. E.g.:
def m = [a: true]
assert m.get("b", false)==false
assert m.containsKey("b")
Yet, the absence of a key with a regular get will give you null, which is basically false

ReasonML binding function with config having fixed string values

Lets say, that I have this function in Javascript which can generate string based on proper configuration:
function func(config) {
// ...
}
also, let's assume, that the config variable has structure as below (all of these can be not given to function call):
{
"color": string, // can be: "blue", "red", "green"
"number": int, // can be: any number
"other": string, // can be: "x", "y"
}
How to create proper binding for this? I'm stuck with:
[#bs.deriving abstract]
type options = {
[#bs.optional]
color: [#bs.string] [ | `blue | `red | `green ]
[#bs.optional]
number: int,
[#bs.optional]
other: [#bs.string] [ | `x | `y ]
}
[#bs.module]
external func: options => string = "func";
But it does not work when trying to use like this:
let config = MyModule.config(
~color=`blue,
~number=123,
~other=`x
);
let value = MyModule.func(config);
The color and other values are integers, not strings.
This is a case of a JavaScript idiom for named parameters (objects with optional fields), needing to be adapted to the OCaml/ReasonML idiom (functions with actual labelled parameters). You would do this in three steps. Step 1, as Glenn showed, define an external for the config:
type config;
[#bs.obj] external config: (
~color:[#bs.string] [`blue | `red | `green]=?,
~number:int=?,
~other:[#bs.string] [`x | `y]=?,
unit,
) => config = "";
Step 2, bind to the JavaScript function using the JavaScript style of the config object:
[#bs.val] external func: config => string = "";
Step 3, wrap the JavaScript function binding in an OCaml-idiomatic function with labelled parameters:
let func(~color=?, ~number=?, ~other=?, ()) = ()
|> config(~color?, ~number?, ~other?)
|> func;
You can use it like this:
let result = func(~color=`blue, ());
The #bs attributes are often poorly thought out hacks that you shouldn't expect to work well with other attributes, or really with anything other than exactly what the documentation explains or shows examples of. However, if an attribute is used where it is not intended you'll usually at least get a warning about the attribute being unused, which your code does.
#bs.string in particular only works on types at the outermost level of externals, i.e. on types whose values will be passed directly to the external function. There is also a way to create JavaScript objects using external functions which also happens to use less magic and give you much more control over the API. As far as I'm aware, the only downside compared to #bs.deriving is that you can't override field names using something like #bs.as. They have to be valid OCaml identifiers.
Here's your example implemented using an external function annotated with #bs.obj:
type options;
[#bs.obj] external options : (
~color:[#bs.string] [`blue | `red | `green]=?,
~number:int=?,
~other:[#bs.string] [`x | `y]=?,
unit
) => options = "";
To use it you call it exactly as with #bs.deriving:
let config = options(~color=`blue,~number=123, ~other=`x, ());
But even with this I've encountered edge cases where integer values are passed in instead of strings. For this reason I tend to avoid the polymorphic variant attributes altogether and instead use ordinary variants along with conversion functions. This has the added benefit of being more idiomatic, blending in better and being more interoperable with non-BuckleScript code.
Here's what your example might look like using this approach:
type color = Blue | Red | Green;
let colorToString = fun
| Blue => "blue"
| Red => "red"
| Green => "green";
type other = X | Y;
let otherToString = fun
| X => "x"
| Y => "y";
[#bs.obj] external options : (
~color:string=?,
~number:int=?,
~other:string=?,
unit
) => options = "";
[#bs.module] external func: options => string = "func";
let func = (~color=?, ~number=?, ~other=?, ()) =>
func(options(
~color = ?Belt.Option.map(color, colorToString),
~number?,
~other = ?Belt.Option.map(other, otherToString),
()));
let config = func(~color=Blue,~number=123, ~other=X, ());
This is because in reality, those values are variants, instead of trying to make it exactly like JavaScript, I would rather try something more idiomatic to Reason:
type color = Blue | Green | Red;
type coords = X | Y;
type config = {
color,
coords,
number: int
};
let func = (config: config) => "something"
And then inside your function actually return strings (if that is what you really need) by pattern matching on the correct values provided to config.
See the working code here.
Hope it helps!

Resources