How do I loop through all compositions in an After Effects project? - extendscript

How does one loop through all the compositions in the currently opened After Effects project?

The app.project.items holds all the compositions, and folders in the currently opened project. So this way I can loop through all of these, and I also have to check for whether it is a composition (since it can be a folder as well).
for (var i = 1; i <= app.project.numItems; i++) {
if (app.project.item(i) instanceof CompItem) {
// Do stuff with the composition.
// app.project.item(i) is the composition.
}
}

Related

Modify object from multiple async streams in Dart

Imagine we had a object like this
class Foo {
List<int> data = [];
void addAndCheck(int n){
for(int number in data){
// check something
}
data.add(n);
}
}
and the imagine we spawn a bunch of subscriptions like this
Foo foo = Foo();
for(int i = 0; i++; i<10){
subscriptions.add(api.someRandomStream().listen((response){
foo.addAndCheck(response.value);
}));
}
As it stands, if this code is run it might work but as soon as the streams start emitting around the same time we get a exception: Concurrent modification during iteration
The cause is the for loop, but how can this problem be solved? In a language like Java there are things like ConcurrentHashMap, Collections.synchronizedList(...), etc..
If you get a concurrent modification error during the iteration, then you are doing something asynchronous inside the loop. That is, your function is probably async and there is at least one await inside the loop. That will allow another event to trigger while you are awaiting, and then modify the list.
There are several ways to avoid the exception, all with different trade-offs:
Don't do anything asynchronous in the loop, and make sure that nothing you do in there will call addAndCheck again. Then there should be no problem because the loop will complete before anyone else has a chance to modify the list. That obviously only works if you don't need to do something asynchronous.
Copy the list. If you do for(int number in [...data]) { ... } (or in data.toList() as it used to be written), then the list that you iterate is a different list than the one which is modified. It also means that you might not have checked all the elements that are actually in the list at the point you reach the add call.
Don't use an iterator. If you do for (int i = 0; i < data.length; i++) { var number = data[i]; ... } instead, you will not get a concurrent modification error from the iterator. If elements are added at the end of the list, then you will eventually reach them, and all is well. If elements are removed from the list, or added in any place other than at the end, then you might be skipping elements or seeing some of them twice, which may be bad for you.
Use a mutex. If you want to be sure that all the tests on existing elements are performed before any other element is added, then you need to prevent anything from happening while you are adding. Assume a Mutex class of some sort, which would allow you to write code like:
class Foo {
List<int> data = [];
final _mutex = Mutex();
void addAndCheck(int n) async {
await _mutex.acquire();
for(int number in data){
// check something
}
data.add(n);
_mutex.release();
}
}
(I found package:mutex by searching, I have no experience with it).
This might slow down your code, though, making every operation wait for the previous one to complete entirely.
In the end, only you can say which trade-off is best for the behavior of your code.

ANTLR4: getFirstChildWithType with a ParseTree

I've been playing around with ANTLR4, trying to convert an ANTLR3 project.
I have generated a lexer, a parser and a visitor class from an ANLTR4 grammar coming from the official repository. In the visitor, I am calling one of my classes using the ctx available from the visitor:
myFunction(ctx.getChild(0))
Then, in myFunction, I want to retrieve the first child having a specific type, so I tried doing:
final ParseTree classNameElement =
(ParseTree) ((GrammarAST) node).getFirstChildWithType(MyParser.IDENTIFIER);
where node is the argument of myFunction, thus a ParseTree. getFirstChildWithType seems to be available only in GrammarAST, hence the cast.
I am getting the error: cannot be cast to org.antlr.v4.tool.ast.GrammarAST
So maybe this is not possible as is and I must have missed something, but I want to find the first child having a specific type from a ParseTree.
Thank you!
Notice that GrammarAST is in the ANTLR tool hierarchy. With a generated parse-tree, you should be dealing exclusively with the runtime.
To search a parse-tree node for a child of a given type:
public ParseTree getFirstChildOfType(ParseTree node, int tokentype) {
for (int idx = 0; idx < node.getChildCount(); idx++) {
ParseTree child = node.getChild(idx);
if (child instanceof TerminalNode) {
Token token = (Token) child.getPayload();
if (token.getType() == tokentype) {
return child;
}
}
}
return null;
}
This will get the first direct, i.e., child terminal, of the given type. Will need to recurse into non-TerminalNodes if the absolute first of type is desired.
If the latter is actually the desired function, there may be a better/more direct use of parse-tree walker to obtain the desired overall goal.

How to convert a DTO to Domain Objects

I'm trying to apply ubiquitous language to my domain objects.
I want to convert a Data Transfer Object coming from a client into the domain object. The Aggregate's Constructor only accepts the required fields, and the rest of parameters should be passed using aggregate's API even when the Aggregate is being created(by say CreateAggregate command).
But the DTO to Aggregate mapping code becomes a bit messy:
if(DTO.RegistrantType == 0){
registrantType = RegistrantType.Person()
}
elseif(DTO.RegistrantType == 1){
registrantType = RegistrantType.Company()
}
//.....
//.....
var aggregate = new Aggregate(
title,
weight,
registrantType,
route,
callNumber,
)
//look at this one:
if(DTO.connectionType == 0){
aggregate.Route(ConnectionType.InCity(cityId))
}
elseif(DTO.connectionType == 1){
aggregate.Route(ConnectionType.Intercity(DTO.originCityId,DTO.DestinationCityId)
}
//..........
//..........
One thing I should mention is that this problem doesn't seem a domain specific problem.
How can I reduce these If-Else statements without letting my domain internals leakage, and with being sure that the aggregate(not a mapping tool) doesn't accept values that can invalide it's business rules, and with having the ubiquitous language applied?
Please don't tell me I can use AoutoMapper to do the trick. Please read the last part carefully.'
Thank you.
A typical answer would be to convert the DTO (which is effectively a message) into a Command, where the command has all of the arguments expressed as domain specific value types.
void doX(DTO dto) {
Command command = toCommand(dto)
doX(command)
}
void doX(Command command) {
// ...
aggregate.Route(command.connectionType)
}
It's fairly common for the toCommand logic use something like a Builder pattern to improve the readability of the code.
if(DTO.connectionType == 0){
aggregate.Route(ConnectionType.InCity(cityId))
}
elseif(DTO.connectionType == 1){
aggregate.Route(ConnectionType.Intercity(DTO.originCityId,DTO.DestinationCityId)
}
In cases like this one, the strategy pattern can help
ConnectionTypeFactory f = getConnectionFactory(DTO.connectionType)
ConnectionType connectionType = f.create(DTO)
Once that you recognize that ConnectionTypeFactory is a thing, you can think about building lookup tables to choose the right one.
Map<ConnectionType, ConnectionTypeFactory> lookup = /* ... */
ConnectionTypeFactory f = lookup(DTO.connectionType);
if (null == f) {
f = defaultConnectionFactory;
}
So why don't you use more inheritance
for example
class CompanyRegistration : Registration {
}
class PersonRegistraiton : Registration {
}
then you can use inheritance instead of your if/else scenario's
public class Aggregate {
public Aggregate (CompanyRegistration) {
registantType = RegistrantType.Company();
}
public Aggregate (PersonRegistration p) {
registrantType = RegistrantType.Person();
}
}
you can apply simmilar logic for say a setRoute method or any other large if/else situations.
Also, i know you don't want to hear it, you can write your own mapper (inside the aggegate) that maps and validates it's business logic
for example this idea comes from fluentmapper
var mapper = new FluentMapper.ThatMaps<Aggregate>().From<DTO>()
.ThatSets(x => x.title).When(x => x != null).From(x => x.title)
It isn't too hard to write your own mapper that allow this kind of rules and validates your properties. And i think it will improve readability

Is there a language that breaks out of conditional statements as soon as they become false?

I thought that I had come across this before, but I can't remember when or what language it was.
Basically if I have the following in C#:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond) {
someCondition = false;
continue;
}
// Do Something Else
}
In C# this will break out of the body of the if statement when someCondition changes, meaning that //DO Something Else only gets processed if someCondition doesn't change...
Is there a language that will do the interior if statement checking/continue automatically i.e. be able to write:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond){
someCondition = false;
}
// Do Something Else
}
with the same behaviors as the previous? Obviously there are multiple ways to get this behavior in every language conceivable, what I am interested in is if there is a language that by design has this functionality.
Edit: Reduced the examples so hopefully people can see what is happening, when someCondition changes (i.e. the condition that the if statement relied on to begin, we should break out of the remaining if statement. I am not looking for a way to do this in C#, or any particular language, but for a language that does this automatically.
You can create a property in C# that throws an exception on any condition you set, aka truth=true. The exception will break out of the loop to wherever you have your catch.
An example in C#:
public class MyException : Exception { }
public bool truth
{
get { return _truth; }
set
{
_truth = value;
if(value)
throw new MyException();
}
}
bool _truth;
I think you can simulate what you want in C# like so:
void ExecuteWhile( Func<bool> condition,
IEnumerable<Action> executeWhileTrue,
IEnumerable<Action> executeWhileFalse)
{
if (condition())
{
foreach (Action action in executeWhileTrue)
{
action();
if (!condition())
return;
}
}
else
{
foreach (Action action in executeWhileFalse)
{
action();
if (condition())
return;
}
}
}
and then use it as such:
truth = true;
while (true) // loop forever
{
ExecuteWhile( () => truth,
new List<Action> { () => { /* do something that might set truth to false*/},
() => { /* do something else*/}},
new List<Action> { () => { /* do something that might set truth to true*/},
() => { /* do something else*/}});
}
And to answer your question: no, I don't think there is a language with this as a build-in feature.
As far as I understood, the following is wanted:
if (cond) {
A;
B;
C;
}
shall behave as if written thus:
if (cond) {
A;
if (cond) {
B;
if (cond) {
C
}
}
}
IMHO, this would be a silly feature, unlikely to be implemented in any language except maybe in INTERCAL.
Why do I think that?
Well, suppose someone wants to refactor the code and moves B;C to a subroutine.
if (cond) {
A;
BC();
}
subroutine BC() { B;C }
The block - according to our feature - will mean as before:
if (cond) {
A;
if (cond) BC();
}
But what about our subroutine? The language designer has 2 choices here:
Treat the call BC() as atomic, i.e. in the subroutine, the
condition cond is not checked before statement C. This would mean
such a simple refactoring would change the meaning of the program
drastically.
Somehow pass the information that every statement must be guarded
with cond to the subroutine so that the behaviour of our block remains
unchanged. This, of course, leads to the silly situation that the
behaviour of any subroutine would depend upon the context it was
called in. A subroutine with n atomic statements would have n possible ways to behave even if it had no arguments and would not use non local mutable state explicitely, depending on how many of the statements would be actually executed. (Note that nowadays the trend is to minimize the most often harmful effects of shared non-local state. OO languages do it with encapsulation, FP languages by banning mutable state altogether.)
In any case, no matter how the language designer decides, we would have a feature that is the direct contradiction of the principle of the least surprise. It is clear that programs in such a language would be utterly hard to maintain.
If you broke you big bunch if/else statements into succinct little methods which tested each little piece of the puzzle, you could rely on the compilers short circuit boolean evaluation
I'm not sure if that helps as your example is a big vague. You don't say if you're doing any processing or if it's just a bunch of checks. Either way, breaking your code into smaller methods may help you out.
You can use a do..while loop:
do
{
} while (truth == true);
thats if i've understood correctly!
You say while true... but while what is true. I would think your loop will run infinitely regardless of the language used. Assuming true will be a real condition... I would say just set the exit condition in one of the if blocks. You question is a bit hard to understand. Also the continue is unnecessary.

Traverse in custom GUI in j2me

Here is my Traverse method code
protected boolean traverse(int dir, int viewportWidth, int viewportHeight,
int[] visRect_inout) {
try {
if (hori && vert) {
// CustomItems items=new CustomItems("Hi");
switch (dir) {
case Canvas.DOWN:
this.a=dir; //Canvas.DOWN
this.b=viewportWidth; //b=2
this.c=viewportHeight; //c=3
this.d=visRect_inout; //d={2,2,250,250}
this.traverse(Canvas.UP, b, c, d);
break;
case Canvas.UP:
this.a=dir;
this.j=viewportWidth;
this.k=viewportHeight;
this.d=visRect_inout;
this.traverse(Canvas.UP, j, k, d);
break;
case Canvas.LEFT:
this.a=dir;
this.j=viewportWidth;
this.k=viewportHeight;
this.d=visRect_inout;
this.traverse(Canvas.LEFT, j, k, d);
break;
case Canvas.RIGHT:
break;
}
}
} catch (Exception e) {
System.out.println("Exception " + e);
}
return false;
}
I am very new to Custom Item.
If I had done any wrong, let me know.
The way how you invoke traverse from within switch statement looks slippery to me:
this.traverse(Canvas.UP, b, c, d); // ...
// ...and similar in cases Canvas.UP, LEFT
The code you posted so far is quite fragmentary but as far as I can tell, above will lead to infinite recursive calls for traverse, eventually ending in stack overflow error.
In your particular case this might be harmless though because you unconditionally return false from your method. Per my understanding this means that device will never attempt to invoke traverse with Canvas UP and other potentially dangerous values. Feel free to check lcdui CustomItem#traverse API documentation for more details if you're interested.
Given your code I think it makes good sense for you to study introductory code examples in tutorials. There are plenty available online - search the web for something like "MIDP tutorial CustomItem". Here's the link to one for example: Adding Custom Items to MIDP 2.0 Forms
Also, if you are using Wireless Toolkit / Java ME SDK, you could check their code examples. Per my recollection, there were nice working examples of CustomItem code there.

Resources