() => {
const object = {
  key1: 'some value',
  key2: {
    key1: 'some value',
    key2: [5, 'some value', 'some other value', 10],
    key3: [
      { key1: 'some other value' },
      { key2: [10, 'some other value', 5, 'some value'] },
      { key3: 'some value' },
      { key4: 5 },
      { key5: 10 }
    ],
    key4: 10,
    key5: 5,
  },
  key3: [10, 'some other value', 'some value', 5],
  key4: 10,
  key5: 'some other value',
  key6: 5,
};

  it('does not mutate the object', () => {
    const clonedObject = clone(object);
    deepReplaceInObject('some value', 'a new value', object);
    expect(object).to.deep.equal(clonedObject);
  });

  it('can replace string values', () => {
    const expected =
{
  key1: 'a new value',
  key2: {
    key1: 'a new value',
    key2: [5, 'a new value', 'some other value', 10],
    key3: [
      { key1: 'some other value' },
      { key2: [10, 'some other value', 5, 'a new value'] },
      { key3: 'a new value' },
      { key4: 5 },
      { key5: 10 }
    ],
    key4: 10,
    key5: 5,
  },
  key3: [10, 'some other value', 'a new value', 5],
  key4: 10,
  key5: 'some other value',
  key6: 5,
};
    const replacedObject = deepReplaceInObject('some value', 'a new value', object);
    expect(replacedObject).to.deep.equal(expected);
  });

  it('can replace number values', () => {
const expected = {
  key1: 'some value',
  key2: {
    key1: 'some value',
    key2: [5, 'some value', 'some other value', 4],
    key3: [
      { key1: 'some other value' },
      { key2: [4, 'some other value', 5, 'some value'] },
      { key3: 'some value' },
      { key4: 5 },
      { key5: 4 }
    ],
    key4: 4,
    key5: 5,
  },
  key3: [4, 'some other value', 'some value', 5],
  key4: 4,
  key5: 'some other value',
  key6: 5,
};
    const replacedObject = deepReplaceInObject(10, 4, object);
    expect(replacedObject).to.deep.equal(expected);
  });

  it('returns a copy of the object if nothing matches', () => {
    const replacedObject = deepReplaceInObject('no match', 'a new value', object);
    expect(replacedObject).to.deep.equal(object);
  });
}


() => {
    const clonedObject = clone(object);
    deepReplaceInObject('some value', 'a new value', object);
    expect(object).to.deep.equal(clonedObject);
  }


() => {
    const expected =
{
  key1: 'a new value',
  key2: {
    key1: 'a new value',
    key2: [5, 'a new value', 'some other value', 10],
    key3: [
      { key1: 'some other value' },
      { key2: [10, 'some other value', 5, 'a new value'] },
      { key3: 'a new value' },
      { key4: 5 },
      { key5: 10 }
    ],
    key4: 10,
    key5: 5,
  },
  key3: [10, 'some other value', 'a new value', 5],
  key4: 10,
  key5: 'some other value',
  key6: 5,
};
    const replacedObject = deepReplaceInObject('some value', 'a new value', object);
    expect(replacedObject).to.deep.equal(expected);
  }


() => {
const expected = {
  key1: 'some value',
  key2: {
    key1: 'some value',
    key2: [5, 'some value', 'some other value', 4],
    key3: [
      { key1: 'some other value' },
      { key2: [4, 'some other value', 5, 'some value'] },
      { key3: 'some value' },
      { key4: 5 },
      { key5: 4 }
    ],
    key4: 4,
    key5: 5,
  },
  key3: [4, 'some other value', 'some value', 5],
  key4: 4,
  key5: 'some other value',
  key6: 5,
};
    const replacedObject = deepReplaceInObject(10, 4, object);
    expect(replacedObject).to.deep.equal(expected);
  }


() => {
    const replacedObject = deepReplaceInObject('no match', 'a new value', object);
    expect(replacedObject).to.deep.equal(object);
  }


export interface ListTaskRunLogsRequest extends common.BaseRequest {
  /**
   * The workspace ID.
   */
  "workspaceId": string;
  /**
   * The application key.
   */
  "applicationKey": string;
  /**
   * The task run key.
   */
  "taskRunKey": string;
  /**
   * Unique Oracle-assigned identifier for the request. If
   * you need to contact Oracle about a particular request,
   * please provide the request ID.
   *
   */
  "opcRequestId"?: string;
  /**
   * For list pagination. The value for this parameter is the `opc-next-page` or the `opc-prev-page` response header from the previous `List` call. See [List Pagination](https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
   */
  "page"?: string;
  /**
   * Sets the maximum number of results per page, or items to return in a paginated `List` call. See [List Pagination](https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
   */
  "limit"?: number;
  /**
   * Specifies sort order to use, either `ASC` (ascending) or `DESC` (descending).
   */
  "sortOrder"?: ListTaskRunLogsRequest.SortOrder;
  /**
   * Specifies the field to sort by. Accepts only one field. By default, when you sort by time fields, results are shown in descending order. All other fields default to ascending order. Sorting related parameters are ignored when parameter `query` is present (search operation and sorting order is by relevance score in descending order).
   */
  "sortBy"?: ListTaskRunLogsRequest.SortBy;
}


export enum SortOrder {
    Asc = "ASC",
    Desc = "DESC"
  }


export enum SortBy {
    TimeCreated = "TIME_CREATED",
    DisplayName = "DISPLAY_NAME"
  }


export type RepositoryProjects = typeof repositoryProjects


export class SimulationRun implements BaseEntity {
    constructor(
        public id?: number,
        public simulationTrial?: string,
        public index?: number,
        public team_id?: number,
        public score?: number,
        public teamCapture?: number,
        public nonTeamCapture?: number,
        public job_num?: number,
        public task_num?: number,
        public results_dir?: string,
        public num_rows?: number,
        public align_weight_t_1?: number,
        public avoid_nonteam_weight_t_1?: number,
        public avoid_team_weight_t_1?: number,
        public centroid_weight_t_1?: number,
        public comms_range_t_1?: number,
        public fov_az_t_1?: number,
        public fov_el_t_1?: number,
        public goal_weight_t_1?: number,
        public max_pred_speed_t_1?: number,
        public max_speed_t_1?: number,
        public sphere_of_influence_t_1?: number,
        public motion_model_t_1?: string,
        public vel_max_t_1?: number,
        public motion_model_predator?: string,
        public pitch_rate_max_predator?: number,
        public turn_rate_max_predator?: number,
        public vel_max_predator?: number,
        public align_weight_t_2_predator?: number,
        public allow_prey_switching_t_2_predator?: boolean,
        public autonomy_t_2_predator?: string,
        public avoid_nonteam_weight_t_2_predator?: number,
        public avoid_team_weight_t_2_predator?: number,
        public capture_range_t_2_predator?: number,
        public centroid_weight_t_2_predator?: number,
        public comms_range_t_2_predator?: number,
        public max_pred_speed_t_2_predator?: number,
        public max_speed_t_2_predator?: number,
        public align_weight_t_3_predator?: number,
        public allow_prey_switching_t_3_predator?: boolean,
        public autonomy_t_3_predator?: string,
        public avoid_nonteam_weight_t_3_predator?: number,
        public avoid_team_weight_t_3_predator?: number,
        public capture_range_t_3_predator?: number,
        public centroid_weight_t_3_predator?: number,
        public comms_range_t_3_predator?: number,
        public max_pred_speed_t_3_predator?: number,
        public max_speed_t_3_predator?: number,
    ) {
        this.allow_prey_switching_t_2_predator = false;
        this.allow_prey_switching_t_3_predator = false;
    }
}


(sx: Object) =>
  renderToString(
    jsx('div', {
      sx,
    })
  )


() => {
  expect(() =>
    render({
      flex: 1,
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot specify disallowed CSS property \\"flex\\"."`
  )
}


() =>
    render({
      flex: 1,
    })


() => {
  expect(() =>
    render({
      justifyContent: 1,
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot specify disallowed CSS property \\"justifyContent\\"."`
  )
}


() =>
    render({
      justifyContent: 1,
    })


() => {
  expect(() =>
    render({
      padding: '2px',
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot use a non-theme value \\"2px\\" for \\"padding\\". Please either use a theme value or add a new value to the theme."`
  )
}


() =>
    render({
      padding: '2px',
    })


() => {
  expect(() =>
    render({
      padding: 3,
    })
  ).not.toThrowError()
}


() =>
    render({
      padding: 3,
    })


() => {
  expect(() =>
    render({
      padding: [1, 2, 3],
    })
  ).not.toThrowError()
}


() =>
    render({
      padding: [1, 2, 3],
    })


() => {
  expect(() =>
    render({
      padding: [1, '3px', 3],
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot use a non-theme value \\"3px\\" for \\"padding\\". Please either use a theme value or add a new value to the theme."`
  )
}


() =>
    render({
      padding: [1, '3px', 3],
    })


() => {
  expect(() =>
    render({
      mx: 2,
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot specify disallowed CSS property \\"mx\\"."`
  )
}


() =>
    render({
      mx: 2,
    })


() => {
  expect(() =>
    render({
      marginX: 2,
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot specify disallowed CSS property \\"marginX\\"."`
  )
}


() =>
    render({
      marginX: 2,
    })


() => {
  expect(() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            colors: {
              red: 'red',
            },
          },
        },
        jsx('div', {
          sx: {
            color: 'red',
          },
        })
      )
    )
  ).not.toThrowError()
}


() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            colors: {
              red: 'red',
            },
          },
        },
        jsx('div', {
          sx: {
            color: 'red',
          },
        })
      )
    )


() => {
  expect(() =>
    render({
      height: 2,
    })
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot specify \\"height\\" because no \\"sizes\\" scale is defined in the theme."`
  )
}


() =>
    render({
      height: 2,
    })


() => {
  expect(() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            sizes: ['0', '2px', '4px'],
          },
        },
        jsx('div', {
          sx: {
            height: 2,
          },
        })
      )
    )
  ).not.toThrowError()
}


() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            sizes: ['0', '2px', '4px'],
          },
        },
        jsx('div', {
          sx: {
            height: 2,
          },
        })
      )
    )


() => {
  expect(() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            sizes: ['0', '2px', '4px'],
          },
        },
        jsx('div', {
          sx: {
            height: '16px',
          },
        })
      )
    )
  ).toThrowErrorMatchingInlineSnapshot(
    `"Cannot use a non-theme value \\"16px\\" for \\"height\\". Please either use a theme value or add a new value to the theme."`
  )
}


() =>
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            sizes: ['0', '2px', '4px'],
          },
        },
        jsx('div', {
          sx: {
            height: '16px',
          },
        })
      )
    )


() => {
  expect(
    renderToString(
      jsx(
        ThemeProvider,
        {
          theme: {
            colors: {
              text: '#000',
              background: '#fff',
            },
          },
        },
        jsx('div', {
          sx: {
            padding: 2,
            color: 'background',
          },
        })
      )
    )
  ).toMatchInlineSnapshot(
    `"<div class=\\"css-1m7wf6w\\"></div>"`
  )
}


() => {
  describe('#constructor()', () => {
    it('should return a new instance', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box).toBeInstanceOf(CommitBox);
    });

    it('should set the default commit message summary to an empty string', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.summary).toEqual('');
    });

    it('should set the default commit message description to an empty string', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.description).toEqual('');
    });
  });

  describe('#render()', () => {
    it('should display placeholder text for the commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('placeholder')).toEqual('Summary (required)');
    });

    it('should set a `title` attribute on the input element to provide a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should display placeholder text for the commit message description', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('placeholder')).toEqual('Description');
    });

    it('should set a `title` attribute on the input element to provide a commit message description', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should display a button to commit changes', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('value')).toEqual('Commit');
    });

    it('should set a `title` attribute on the button to commit changes', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should apply a class to disable the commit button when no files have changes to commit', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    });

    it('should apply a class to disable the commit button when files have changes to commit, but the user has not entered a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    });

    it('should not apply a class to disable the commit button when files have changes to commit and the user has entered a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      component.setState({
        summary: 'beep boop'
      });

      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(false);
    });
  });
}


() => {
    it('should return a new instance', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box).toBeInstanceOf(CommitBox);
    });

    it('should set the default commit message summary to an empty string', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.summary).toEqual('');
    });

    it('should set the default commit message description to an empty string', () => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.description).toEqual('');
    });
  }


() => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box).toBeInstanceOf(CommitBox);
    }


() => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.summary).toEqual('');
    }


() => {
      const box = new CommitBox({
        onCommit: async () => {},
        hasFiles: false
      });
      expect(box.state.description).toEqual('');
    }


() => {
    it('should display placeholder text for the commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('placeholder')).toEqual('Summary (required)');
    });

    it('should set a `title` attribute on the input element to provide a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should display placeholder text for the commit message description', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('placeholder')).toEqual('Description');
    });

    it('should set a `title` attribute on the input element to provide a commit message description', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should display a button to commit changes', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('value')).toEqual('Commit');
    });

    it('should set a `title` attribute on the button to commit changes', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    });

    it('should apply a class to disable the commit button when no files have changes to commit', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    });

    it('should apply a class to disable the commit button when files have changes to commit, but the user has not entered a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    });

    it('should not apply a class to disable the commit button when files have changes to commit and the user has entered a commit message summary', () => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      component.setState({
        summary: 'beep boop'
      });

      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(false);
    });
  }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('placeholder')).toEqual('Summary (required)');
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="text"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('placeholder')).toEqual('Description');
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('TextareaAutosize').first();
      expect(node.prop('title').length > 0).toEqual(true);
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('value')).toEqual('Commit');
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      expect(node.prop('title').length > 0).toEqual(true);
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: false
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(true);
    }


() => {
      const props = {
        onCommit: async () => {},
        hasFiles: true
      };
      const component = shallow(<CommitBox {...props} />);
      component.setState({
        summary: 'beep boop'
      });

      const node = component.find('input[type="button"]').first();
      const prop = node.prop('disabled');
      expect(prop).toEqual(false);
    }


async () => {
        app = await initApp({
            imports: [ArticleModule],
        });
    }


async () => {
        await clearModelCollectionData();
    }


() => {
        test('create article success', async () => {
            const article = getArticle();
            return request(app.getHttpServer())
                .post('/api/articles')
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(201)
                .then((res) => {
                    expect(res.body).toHaveProperty('_id');
                });
        });

        test('bad request, create article failure, the category can not an empty string', async () => {
            const article1 = getArticle({ category: '' });
            return request(app.getHttpServer())
                .post('/api/articles')
                .set('authorization', __TOKEN__)
                .send(article1)
                .expect(400);
        });
    }


async () => {
            const article = getArticle();
            return request(app.getHttpServer())
                .post('/api/articles')
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(201)
                .then((res) => {
                    expect(res.body).toHaveProperty('_id');
                });
        }


(res) => {
                    expect(res.body).toHaveProperty('_id');
                }


async () => {
            const article1 = getArticle({ category: '' });
            return request(app.getHttpServer())
                .post('/api/articles')
                .set('authorization', __TOKEN__)
                .send(article1)
                .expect(400);
        }


() => {
        test('update article success', async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .put('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(200);
        });

        test('update article new category id success & the articleCount should be updated in category', async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            const newCategory = getObjectId();
            return request(app.getHttpServer())
                .put('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .send({ ...article, category: newCategory })
                .expect(200);
        });

        test('bad request, update the article data & the data not found in db', async () => {
            const article = getArticle();
            return request(app.getHttpServer())
                .put('/api/articles/' + getObjectId())
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(400);
        });

        test('bad request, update the article data & the data not found in db', async () => {
            const article = getArticle();
            return request(app.getHttpServer())
                .put('/api/articles/' + getObjectId())
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(400);
        });
    }


async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .put('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(200);
        }


async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            const newCategory = getObjectId();
            return request(app.getHttpServer())
                .put('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .send({ ...article, category: newCategory })
                .expect(200);
        }


async () => {
            const article = getArticle();
            return request(app.getHttpServer())
                .put('/api/articles/' + getObjectId())
                .set('authorization', __TOKEN__)
                .send(article)
                .expect(400);
        }


() => {
        test('bad request, batch delete the data failure, the articleIds should be an objectId array', async () => {
            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [],
                })
                .expect(400);
        });

        test('not found, batch delete the data failure, the articleIds data should be found in db', async () => {
            const testId = getObjectId();
            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [testId],
                })
                .expect(404);
        });

        test('batch delete the data success', async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [_id],
                })
                .expect(200);
        });
    }


async () => {
            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [],
                })
                .expect(400);
        }


async () => {
            const testId = getObjectId();
            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [testId],
                })
                .expect(404);
        }


async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .delete('/api/articles')
                .set('authorization', __TOKEN__)
                .send({
                    articleIds: [_id],
                })
                .expect(200);
        }


() => {
        test('delete the article success', async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);
            return request(app.getHttpServer())
                .delete('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .expect(200);
        });

        test('not found, delete failure, the article id not found in db', async () => {
            return request(app.getHttpServer())
                .delete('/api/articles/' + getObjectId())
                .set('authorization', __TOKEN__)
                .expect(404);
        });
    }


async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);
            return request(app.getHttpServer())
                .delete('/api/articles/' + _id)
                .set('authorization', __TOKEN__)
                .expect(200);
        }


async () => {
            return request(app.getHttpServer())
                .delete('/api/articles/' + getObjectId())
                .set('authorization', __TOKEN__)
                .expect(404);
        }


() => {
        test('success', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get('/api/recentArticles')
                .expect(200)
                .then((res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(5);
                });
        });
    }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get('/api/recentArticles')
                .expect(200)
                .then((res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(5);
                });
        }


() => getArticle()


(res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(5);
                }


() => {
        test('success', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get('/api/articles-aggregation/date')
                .expect(200)
                .then((res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(1);
                });
        });
    }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get('/api/articles-aggregation/date')
                .expect(200)
                .then((res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(1);
                });
        }


(res) => {
                    expect(res.body.length).toBeGreaterThanOrEqual(1);
                }


() => {
        test('get article success, the content is a common string', async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .get('/api/articles/' + _id + '?md=false')
                .expect(200)
                .then((res) => {
                    const a = res.body;
                    expect(a.content).toEqual(article.content);
                });
        });
    }


async () => {
            const article = getArticle();
            const { _id } = await ArticleModel.create(article);

            return request(app.getHttpServer())
                .get('/api/articles/' + _id + '?md=false')
                .expect(200)
                .then((res) => {
                    const a = res.body;
                    expect(a.content).toEqual(article.content);
                });
        }


(res) => {
                    const a = res.body;
                    expect(a.content).toEqual(article.content);
                }


() => {
        test('set pagination', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get(`/api/articles?${queryString.stringify({ page: 1, limit: 10 })}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(10);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        });

        test('filter the data by tag field', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);
            return request(app.getHttpServer())
                .get(`/api/articles?tag=${articles[0].tags[0]}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        });

        test('filter the data by category field', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get(`/api/articles?cid=${articles[0].category}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        });

        test('filter the data by title field', async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);
            const title = articles[0].title.slice(0, 10);

            return request(app.getHttpServer())
                .get(`/api/articles?title=${title}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        });
    }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get(`/api/articles?${queryString.stringify({ page: 1, limit: 10 })}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(10);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        }


(res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(10);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);
            return request(app.getHttpServer())
                .get(`/api/articles?tag=${articles[0].tags[0]}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        }


(res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);

            return request(app.getHttpServer())
                .get(`/api/articles?cid=${articles[0].category}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        }


async () => {
            const articles = generateDataList(() => getArticle(), 10);
            await ArticleModel.create(articles);
            const title = articles[0].title.slice(0, 10);

            return request(app.getHttpServer())
                .get(`/api/articles?title=${title}`)
                .expect(200)
                .then((res) => {
                    expect(res.body.totalCount).toBeGreaterThanOrEqual(1);
                    expect(isExpectPass(res.body.items, articles, ['content', 'category'])).toEqual(true);
                });
        }


async () => {
        await closeApp(app);
    }


({ afterChange, node }) => {
  const { name } = node;
  return <EditableText value={name} onChange={afterChange} />;
}


/**
 * Types for redux state and dispatch
 */
// Types for basic undoable store
export type ReduxState = StateWithHistory<State>


export type ReduxStore = Store<ReduxState, AnyAction>


// Thunk-types extend the dispatch of the store to functions
export type ThunkDispatchType = ThunkDispatch<ReduxState, undefined, BaseAction>


export type FullStore = ReduxStore & {
  /** Thunk dispatch used for redux-thunk async actions */
  dispatch: ThunkDispatchType
}


export type ThunkActionType = ThunkAction<void, ReduxState, void, BaseAction>


export type ThunkCreatorType = ActionCreator<ThunkActionType>


interface BLEAFrontendSslStackProps extends cdk.StackProps {
  myVpc: ec2.Vpc;
  hostedZoneId: string;
  domainName: string;
  hostName: string;
  webAcl: wafv2.CfnWebACL;
}


() => {
  let component: BillBoardCardComponent;
  let fixture: ComponentFixture<BillBoardCardComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ BillBoardCardComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(BillBoardCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


async () => {
    await TestBed.configureTestingModule({
      declarations: [ BillBoardCardComponent ]
    })
    .compileComponents();
  }


() => {
    fixture = TestBed.createComponent(BillBoardCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


function handleKeyDown(event: KeyboardEvent) {
    if (event.key === 'Escape') {
      setPad({} as PadProps)
    }
  }


async function handleUpdatePad(data: PadProps) {
    if (!data.id) data.id = uuid()
    if (data.index === -1) data.index = index
    const response = await api.put('button', data)
    setPadProperties(response.data)
  }


async function handleDeletePad() {
    const { data } = await api.delete(`button/${padProprieties.id}`)
    setPadProperties(data)
    setPad({} as PadProps)
  }


function openModal() {
    setIsModalOpen(true)
  }


function closeModal() {
    setIsModalOpen(false)
  }


function handleConfigurationButtonClick() {
    resetPad()
    openModal()
  }


function handleConfigurablePadClick() {
    setPad(padProprieties)
  }


({ data, index }) => {
  const [padProprieties, setPadProperties] = useState({} as PadProps)

  const { setPad, selectedPad, hasPadSelected, resetPad } = usePads()
  const [isModalOpen, setIsModalOpen] = useState(false)

  function handleKeyDown(event: KeyboardEvent) {
    if (event.key === 'Escape') {
      setPad({} as PadProps)
    }
  }

  useEffect(() => {
    setPadProperties(data)
  }, [data])

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown)

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [])

  async function handleUpdatePad(data: PadProps) {
    if (!data.id) data.id = uuid()
    if (data.index === -1) data.index = index
    const response = await api.put('button', data)
    setPadProperties(response.data)
  }

  async function handleDeletePad() {
    const { data } = await api.delete(`button/${padProprieties.id}`)
    setPadProperties(data)
    setPad({} as PadProps)
  }

  const [, dropRef] = useDrop({
    accept: 'ACTION',
    drop({ data }: Props) {
      handleUpdatePad(data)
    }
  })

  function openModal() {
    setIsModalOpen(true)
  }

  function closeModal() {
    setIsModalOpen(false)
  }

  function handleConfigurationButtonClick() {
    resetPad()
    openModal()
  }

  function handleConfigurablePadClick() {
    setPad(padProprieties)
  }

  return padProprieties.id !== '' ? (
    <>
      <ConfigurablePad
        isSelected={padProprieties.id === selectedPad.id}
        hasPadSelected={hasPadSelected}
      >
        <img
          onClick={handleConfigurablePadClick}
          className={
            padProprieties.iconPath === padProprieties.alternativeIconPath
              ? 'padding-on'
              : ''
          }
          src={padProprieties.iconPath}
          alt="icon"
        />
        <SettingsAndDeleteContainer
          isActive={selectedPad.id === padProprieties.id}
        >
          <SettingsIcon onClick={handleConfigurationButtonClick} />
          <VerticalSeparationLine />
          <DeleteIcon onClick={handleDeletePad} />
        </SettingsAndDeleteContainer>
      </ConfigurablePad>
      <PadConfigurationModal
        isOpen={isModalOpen}
        onRequestClose={closeModal}
        pad={padProprieties}
        setPadProperties={handleUpdatePad}
      />
    </>


() => {
    setPadProperties(data)
  }


() => {
    document.addEventListener('keydown', handleKeyDown)

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }


() => {
      document.removeEventListener('keydown', handleKeyDown)
    }


interface Props {
  data: PadProps
  index: number
}


drop({ data }: Props) {
      handleUpdatePad(data)
    }


export function createInjectMiddleware(
  container: Container,
  customizer?: (container: Container, middlewareApi: MiddlewareAPI<any>) => void,
): Middleware {
  return middlewareApi => {
    // allow caller to customize container with dispatcher
    if (customizer) {
      customizer(container, middlewareApi);
    }
    return next => (action: any) => {
      if (typeof action === "function") {
        const deps = getDependencies(action);

        depSanityCheck(deps);

        const injections = deps.map(dep => container.get(dep));

        return action(...injections);
      }

      return next(action);
    };
  };
}


export function depSanityCheck(deps: symbol[]): void {
  if (!deps.every(v => !!v)) {
    throw new Error("Circular dependency on symbols detected!");
  }
}


export function getDependencies(func: Function): symbol[] {
  // try to get deps from explicitly annotated function
  const anyFunc: any = func;
  if (anyFunc[dependencyInfoSymbol]) {
    return anyFunc[dependencyInfoSymbol];
  } else {
    throw new Error("Explicit dependency list required!");
  }
}


export function injectableFn<T extends Function>(
  func: T,
  dependencies: symbol[],
): FunctionWithDeps & T {
  (func as any)[dependencyInfoSymbol] = dependencies;

  return func as any;
}


middlewareApi => {
    // allow caller to customize container with dispatcher
    if (customizer) {
      customizer(container, middlewareApi);
    }
    return next => (action: any) => {
      if (typeof action === "function") {
        const deps = getDependencies(action);

        depSanityCheck(deps);

        const injections = deps.map(dep => container.get(dep));

        return action(...injections);
      }

      return next(action);
    };
  }


next => (action: any) => {
      if (typeof action === "function") {
        const deps = getDependencies(action);

        depSanityCheck(deps);

        const injections = deps.map(dep => container.get(dep));

        return action(...injections);
      }

      return next(action);
    }


(action: any) => {
      if (typeof action === "function") {
        const deps = getDependencies(action);

        depSanityCheck(deps);

        const injections = deps.map(dep => container.get(dep));

        return action(...injections);
      }

      return next(action);
    }


dep => container.get(dep)


v => !!v


// tslint:disable-next-line
export interface Dispatch<A extends Action = AnyAction> {
    (asyncAction: Function): void;
  }


export class FormstackOAuth2Api implements ICredentialType {
	name = 'formstackOAuth2Api';
	extends = [
		'oAuth2Api',
	];
	displayName = 'Formstack OAuth2 API';
	documentationUrl = 'formstackTrigger';
	properties = [
		{
			displayName: 'Authorization URL',
			name: 'authUrl',
			type: 'hidden' as NodePropertyTypes,
			default: 'https://www.formstack.com/api/v2/oauth2/authorize',
			required: true,
		},
		{
			displayName: 'Access Token URL',
			name: 'accessTokenUrl',
			type: 'hidden' as NodePropertyTypes,
			default: 'https://www.formstack.com/api/v2/oauth2/token',
			required: true,
		},
		{
			displayName: 'Scope',
			name: 'scope',
			type: 'hidden' as NodePropertyTypes,
			default: scopes.join(' '),
		},
		{
			displayName: 'Auth URI Query Parameters',
			name: 'authQueryParameters',
			type: 'hidden' as NodePropertyTypes,
			default: '',
		},
		{
			displayName: 'Authentication',
			name: 'authentication',
			type: 'hidden' as NodePropertyTypes,
			default: 'header',
		},
	];
}


export class App {
    componets = [
        PositionComponent,
        RenderComponent
    ];

    engine = new Engine(this.componets, BlueprintType);

    constructor() {
        this.engine.addBlueprint({
            name: 'Renderable',
            components: [
                {component: PositionComponent, values: {}},
                {component: RenderComponent, values: null}
            ],
            blueprints: []
        });
        this.engine.addBlueprint({
            name: 'Player',
            blueprints: ['renderable'],
            components: [
                {component: RenderComponent, values: {value: "@"}}
            ]
        });

        this.engine.start();
        this.engine.addSystems(...appSystems);

        let entity = new Entity();
        entity.putComponent(PositionComponent);
        this.engine.addEntity(entity);
        this.engine.update(0);
        this.engine.update(0);
        this.engine.update(0);
    }
}


() => {
  let component: CustomAttributeDetailsComponent;
  let fixture: ComponentFixture<CustomAttributeDetailsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomAttributeDetailsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CustomAttributeDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


() => {
    TestBed.configureTestingModule({
      declarations: [ CustomAttributeDetailsComponent ]
    })
    .compileComponents();
  }


() => {
    fixture = TestBed.createComponent(CustomAttributeDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


export default function serializeObject(obj: any): string {
    const s: any = {};
    Object.getOwnPropertyNames(obj).forEach(key => {
        s[key] = obj[key];
    });
    return JSON.stringify(s);
}


key => {
        s[key] = obj[key];
    }


() => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [WebsocketChannelService]
    });
  });

  it('should be created', inject([WebsocketChannelService], (service: WebsocketChannelService) => {
    expect(service).toBeTruthy();
  }));
}


() => {
    TestBed.configureTestingModule({
      providers: [WebsocketChannelService]
    });
  }


(service: WebsocketChannelService) => {
    expect(service).toBeTruthy();
  }


@NgModule({
  declarations: [
    DetailFormComponent,
    ProfilePictureComponent,
  ],
  imports: [
    DropzoneModule,
    AvatarModule,
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    TranslateModule,
    MatSelectModule,
    MatButtonModule,
    MatTooltipModule,
    MatIconModule,
    TranslateModule,
    InputModule,
  ],
  exports: [
    DetailFormComponent,
  ],
})
export class DetailFormModule { }


({
  loading,
  texts,
  selectedTexts: selectedTextsInitial,
  title,
  fieldName,
}) => {
  const [isEditing, setIsEditing] = useState<boolean>(false)
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [selectedTexts, setSelectedTexts] = useState<FieldText[]>([])
  const [saveLoading, setSaveLoading] = useState<boolean>(false)

  useEffect(() => {
    if (!loading && selectedTextsInitial) {
      const {
        selectedIds: dataSelectedIds,
        texts: dataTexts,
      } = selectedTextsInitial
      setSelectedIds(dataSelectedIds ?? [])
      setSelectedTexts(dataTexts ?? [])
    }
  }, [selectedTextsInitial, loading])

  const handleCheck = (text: FieldText, selected: boolean) => {
    if (!selected && selectedIds.length >= MAX_TEXTS) return selected
    let ids = selectedIds
    let texts = selectedTexts
    if (!selected) {
      ids.push(text.id)
      texts.push(text)
    } else {
      ids = ids.filter((value) => text.id !== value)
      texts = texts.filter(({ id: value }) => text.id !== value)
    }
    setSelectedIds(ids)
    setSelectedTexts(texts)

    return !selected
  }

  const handleSave = () => {
    setSaveLoading(true)
    const base = new Firebase()

    base.saveSelected(fieldName, selectedIds, selectedTexts).then(() => {
      setSaveLoading(false)
      setIsEditing(false)
    })
  }

  return (
    <>

{title}

        {isEditing ? (
          <Button isLoading={saveLoading} onClick={handleSave}>
            Salvar
          </Button>


() => {
    if (!loading && selectedTextsInitial) {
      const {
        selectedIds: dataSelectedIds,
        texts: dataTexts,
      } = selectedTextsInitial
      setSelectedIds(dataSelectedIds ?? [])
      setSelectedTexts(dataTexts ?? [])
    }
  }


(text: FieldText, selected: boolean) => {
    if (!selected && selectedIds.length >= MAX_TEXTS) return selected
    let ids = selectedIds
    let texts = selectedTexts
    if (!selected) {
      ids.push(text.id)
      texts.push(text)
    } else {
      ids = ids.filter((value) => text.id !== value)
      texts = texts.filter(({ id: value }) => text.id !== value)
    }
    setSelectedIds(ids)
    setSelectedTexts(texts)

    return !selected
  }


(value) => text.id !== value


({ id: value }) => text.id !== value


() => {
    setSaveLoading(true)
    const base = new Firebase()

    base.saveSelected(fieldName, selectedIds, selectedTexts).then(() => {
      setSaveLoading(false)
      setIsEditing(false)
    })
  }


() => {
      setSaveLoading(false)
      setIsEditing(false)
    }


(text) => (
                <TextTableItem
                  key={text.id}


interface Props {
  loading: boolean
  texts?: FieldText[]
  selectedTexts?: Selected
  title: string
  fieldName: TextFieldKey
}


export interface FlatpickrOption {
  /** defaults to "F j, Y",	exactly the same as date format, but for the altInput field */
  altFormat?: string;

  /** default to false, show the user a readable date (as per altFormat), but return something totally different to the server. */
  altInput?: boolean;

  /** defaults to false, allows the user to enter a date directly input the input field. By default, direct entry is disabled. */
  allowInput?: boolean;

  /** defaults to false, allows the user to input date and/or date format that might be partially invalid. */
  allowInvalidPreload?: boolean;

  /** This class will be added to the input element created by the altInput option.  Note that altInput already inherits classes from the original input. */
  altInputClass?: string;

  /** Instead of body, appends the calendar to the specified node instead*. */
  appendTo?: HTMLElement;

  /** defaults to "F j, Y", defines how the date will be formatted in the aria-label for calendar days, using the same tokens as dateFormat. If you change this, you should choose a value that will make sense if a screen reader reads it out loud. */
  ariaDateFormat?: string;

  /** defaults to true, whether clicking on the input should open the picker. You could disable this if you wish to open the calendar manually with.open() */
  clickOpens?: boolean;

  /** defaults to false, closes the date picker after selecting a date */
  closeOnSelect?: boolean;

  /** defaults to "Y-m-d", a string of characters which are used to define how the date will be displayed in the input box. The supported characters are defined in the table below. */
  dateFormat?: string;

  /**
   * Sets the initial selected date(s).
   * If you're using mode?: "multiple" or a range calendar supply an Array of Date objects or an Array of date strings which follow your dateFormat.
   * Otherwise, you can supply a single Date object or a date string.
   */
  defaultDate?: string | string[] | Date | Date[];

  /** defaults to 12, initial value of the hour element. */
  defaultHour?: number;

  /** defaults to 0, initial value of the minute element. */
  defaultMinute?: number;

  /** defaults to 0, initial value of the seconds element. */
  defaultSeconds?: number;

  /** See Disabling dates */
  disable?: any[];

  /**
   * defaults to false.
   * Set disableMobile to true to always use the non-native picker.
   * By default, flatpickr utilizes native datetime widgets unless certain options (e.g. disable) are used.
   */
  disableMobile?: boolean;

  /** See Enabling dates */
  enable?: any[];

  /** defaults to false, enables seconds in the time picker. */
  enableSeconds?: boolean;

  /** defaults to false, enables time picker */
  enableTime?: boolean;

  /**
   * callback method when Flapickr detects an error.
   * For example if a minDate is specified and setDate is called with a date that is lower than minDate it will throw an error.
   */
  errorHandler?: (error: any) => void;

  /** Allows using a custom date formatting function instead of the built-in handling for date formats using dateFormat, altFormat, etc. */
  formatDate?: (dateObj: Date, format: string, locale: Locale) => string;

  /** defaults to 1, adjusts the step for the hour input (incl. scrolling) */
  hourIncrement?: number;

  /** defaults to false, displays the calendar inline */
  inline?: boolean;

  /** provide a custom set of locales */
  locale?: any;

  /** The maximum date that a user can pick to (inclusive). */
  maxDate?: string | Date;

  /** The minimum date that a user can start picking from (inclusive). */
  minDate?: string | Date;

  /** defaults to 5, adjusts the step for the minute input (incl. scrolling) */
  minuteIncrement?: number;

  /** defaults to "dropdown", the selector type to change the month */
  monthSelectorType?: 'dropdown' | 'static';

  /** defaults to single, what mode to use the picker */
  mode?: 'single' | 'multiple' | 'range';

  /** defaults to ">", HTML for the arrow icon, used to switch months. */
  nextArrow?: string;

  /** defaults to false, Hides the day selection in calendar. Use it along with enableTime to create a time picker. */
  noCalendar?: boolean;

  /** defaults to false, function that expects a date string and must return a Date object */
  parseDate?: (date: Date, format: string) => void;

  /** Provide external flatpickr plugin(s) */
  plugins?: any | any[];

  /** Where the calendar is rendered relative to the input. */
  position?: 'auto' | 'above' | 'below';

  /** defaults to "<"", HTML for the left arrow icon. */
  prevArrow?: string;

  /** defaults to false, show the month using the shorthand version (ie, Sep instead of September). */
  shorthandCurrentMonth?: boolean;

  /** defaults to 1, number of months to show */
  showMonths?: number;

  /** defaults to false, position the calendar inside the wrapper and next to the input element*. */
  static?: boolean;

  /** defaults to false, displays time picker in 24 hour mode without AM/PM selection when enabled. */
  time_24hr?: boolean;

  /** defaults to false, enables display of week numbers in calendar. */
  weekNumbers?: boolean;

  /** defaults to false, custom elements and input groups */
  wrap?: boolean;

  // --
  // Events
  // -----------------

  /** Function(s) to trigger on every date selection. See Events API */
  onChange?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function(s) to trigger on every time the calendar is closed. See Events API */
  onClose?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function(s) to trigger on every time the calendar gets created. See Events API */
  onDayCreate?: (date: Date | Date[]) => void;

  /** Function(s) to trigger when the date picker gets drestroyed. See Events API */
  onDestroy?: (day: Date) => void;

  /** Function(s) to trigger when the date picker gets drestroyed. See Events API */
  onKeyDown?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function(s) to trigger on every time the month changes. See Events API */
  onMonthChange?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function(s) to trigger on every time the calendar is opened. See Events API */
  onOpen?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function to trigger when the calendar is ready. See Events API */
  onReady?: () => void;

  /** Function(s) to trigger on every time the value input associated with the calendar get updated. See Events API */
  onValueUpdate?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;

  /** Function(s) to trigger on every time the year changes. See Events API */
  onYearChange?: (selectedDates: Date[] | Date, dateStr: string, instance: FlatpickrInstance) => void;
}


cls => ren.removeClass(el, cls)


cls => ren.addClass(el, cls)


@Component({
  selector: 'sv, [sv]',
  templateUrl: './view.component.html',
  host: {
    '[style.padding-left.px]': 'paddingValue',
    '[style.padding-right.px]': 'paddingValue',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SVComponent implements AfterViewInit, OnChanges {
  @ViewChild('conEl')
  private conEl: ElementRef;
  private el: HTMLElement;
  private clsMap: string[] = [];

  // #region fields

  @Input() label: string | TemplateRef<void>;
  @Input() unit: string | TemplateRef<void>;
  @Input() @InputNumber(null) col: number;
  @Input() @InputBoolean(null) default: boolean;
  @Input() type: 'primary' | 'success' | 'danger' | 'warning';

  // #endregion

  get paddingValue(): number {
    return this.parent && this.parent.gutter / 2;
  }

  constructor(
    el: ElementRef,
    @Host() @Optional() public parent: SVContainerComponent,
    private rep: ResponsiveService,
    private ren: Renderer2,
  ) {
    if (parent == null) {
      throw new Error(`[sv] must include 'sv-container' component`);
    }
    this.el = el.nativeElement;
  }

  private setClass() {
    const { el, ren, col, clsMap, type, rep } = this;
    clsMap.forEach(cls => ren.removeClass(el, cls));
    clsMap.length = 0;
    clsMap.push(...rep.genCls(col != null ? col : this.parent.col));
    clsMap.push(`${prefixCls}__item`);
    if (this.parent.labelWidth) clsMap.push(`${prefixCls}__item-fixed`);
    if (type) clsMap.push(`${prefixCls}__type-${type}`);
    clsMap.forEach(cls => ren.addClass(el, cls));
  }

  ngAfterViewInit() {
    this.setClass();
    this.checkContent();
  }

  ngOnChanges() {
    this.setClass();
  }

  checkContent() {
    const { conEl } = this;
    const def = this.default;
    if (!(def != null ? def : this.parent.default)) return;
    const el = conEl.nativeElement as HTMLElement;
    const cls = `sv__default`;
    if (el.classList.contains(cls)) {
      el.classList.remove(cls);
    }
    if (isEmpty(el)) {
      el.classList.add(cls);
    }
  }
}


private setClass() {
    const { el, ren, col, clsMap, type, rep } = this;
    clsMap.forEach(cls => ren.removeClass(el, cls));
    clsMap.length = 0;
    clsMap.push(...rep.genCls(col != null ? col : this.parent.col));
    clsMap.push(`${prefixCls}__item`);
    if (this.parent.labelWidth) clsMap.push(`${prefixCls}__item-fixed`);
    if (type) clsMap.push(`${prefixCls}__type-${type}`);
    clsMap.forEach(cls => ren.addClass(el, cls));
  }


ngAfterViewInit() {
    this.setClass();
    this.checkContent();
  }


ngOnChanges() {
    this.setClass();
  }


checkContent() {
    const { conEl } = this;
    const def = this.default;
    if (!(def != null ? def : this.parent.default)) return;
    const el = conEl.nativeElement as HTMLElement;
    const cls = `sv__default`;
    if (el.classList.contains(cls)) {
      el.classList.remove(cls);
    }
    if (isEmpty(el)) {
      el.classList.add(cls);
    }
  }


() => {
  return (
    <div className={styles.signOutPopUp} >
      <button className={styles.signOutBtn}>
        Sign Out
      </button>
    </div>


/**
     * The Collection of JournalEntry documents which exist within the active World.
     * This Collection is accessible within the Game object as game.journal.
     * @see {@link JournalEntry} The JournalEntry entity
     * @see {@link JournalDirectory} The JournalDirectory sidebar directory
     */
class Journal extends WorldCollection<JournalEntry> {
        /** @override */
        static documentName: "JournalEntry";

        /** Open Socket listeners which transact JournalEntry data */
        protected static _activateSocketListeners(socket: io.Socket): void;

        /**
         * Handle a received request to show a JournalEntry to the current client
         * @param entryId The ID of the journal entry to display for other players
         * @param mode    The JournalEntry mode to display
         * @param force   Display the entry to all players regardless of normal permissions
         */
        static _showEntry(entryId: string, mode?: string, force?: boolean): Promise<void>;
    }


/** Open Socket listeners which transact JournalEntry data */
protected static _activateSocketListeners(socket: io.Socket): void;


/**
         * Handle a received request to show a JournalEntry to the current client
         * @param entryId The ID of the journal entry to display for other players
         * @param mode    The JournalEntry mode to display
         * @param force   Display the entry to all players regardless of normal permissions
         */
static _showEntry(entryId: string, mode?: string, force?: boolean): Promise<void>;


() => {
  const b = bemfy("custom-button");

  return

The lazy cat jumps over dizzy fox

    <button className={b('button', 'primary', 'independent-class', c({ 'not-render': false, 'will-render': true }) )}


b('button', 'primary', 'independent-class', c


(error: IExportError) => {
        errors.push(error)
        errorCallback(error)
      }


(data) => {
        if (prevData) {
          data.records = data.records.concat(prevData.records)
        }
        if (data.pager.total >= start + 1024) {
          return this.records(alias, start + 1025, data)
        }
        else {
          return data
        }
      }


(node: any) => {
        pages = pages.concat(this._toArray(node.page))
      }


(nick: string) => nick !== ''


(nick: string) => {
          value += (typeof item[nick] === 'string') ? item[nick].replace(/;+$/g, '') + "; " : ""
        }


(key) => {
          return key.name;
        }


(cpo, cpototal) => {
        if (cpototal > 30) { // threshold so the display doesn't get to crazy
          progressCallback({
            value: progressValue,
            description: `Mapping item ${count} of ${records.length}`,
            subdescription: `Getting compound object item record ${cpo} of ${cpototal}`
          })
        }
      }


(file: any) => {
        this.files.push(file)
        items.push(['File', file.filename].concat(this._map(file.info, fields, undefined, true)))
      }


(key) => {
          return key.name.toLowerCase()
        }


(file: any) => {
        this.files.push(file)
        filenames.push(file.filename)
      }


(bytes) => {
        totalTransfered += bytes
        const transfered = filesize(totalTransfered, { output: "object" }) as any

        progressCallback({
          value: (totalTransfered / totalSize),
          description: `Downloaded ${transfered.value.toFixed(1)} ${transfered.symbol}
            of ${filesize(totalSize, { round: 1 })}`,
          subdescription: `Downloading ${file.filename}`
        })
      }


(acc: number, cur: any) => acc + Number(cur.size)


field => field.required


field => {
      return crosswalk[field.id].nicks.filter((nick: string) => nick !== '').length === 0
    }


(field) => {
      return `Missing required field '${field.name}'`
    }


(error) => {
      errorString += error.description + "\n"
    }


(err) => {
      if (err) {
        console.error(err)
      }
    }


public async export(
    alias: string,
    location: string,
    download: boolean,
    fields: ReadonlyArray<IField>,
    crosswalk: ICrosswalkFieldHash,
    progressCallback: (progress: IExportProgress) => void,
    errorCallback: (error: IExportError) => void
  ): Promise<void> {

    const errors: Array<IExportError> = []
    this.exportAlias = alias
    this.exportCrosswalk = crosswalk
    this.files = []

    const missing = this._missingFields(fields, crosswalk)
    if (missing) {
      return Promise.reject(
        new Error(missing.toString().replace(/,/gi, "\n"))
      )
    }

    progressCallback({ value: undefined, description: 'Getting item records' })

    location = download ? this.downloadLocation(location) : location
    const exportStream = createWriteStream(location)
    const data = await this.records(alias)

    await this._processRecords(
      data.records,
      fields,
      exportStream,
      progressCallback,
      (error: IExportError) => {
        errors.push(error)
        errorCallback(error)
      }
    )
    exportStream.end();

    if (errors.length > 0) {
      this.processErrors(errors, location)
    }

    if (download && this.files) {
      await this._downloadFiles(this.files, location, progressCallback)
    }

    progressCallback({
      value: 1,
      description: `Mapped ${data.records.length} items`,
      subdescription: `Collection total file size: ${filesize(this.totalFileSize(this.files))}`
    })
  }


public async bulkrax(
    alias: string,
    location: string,
    fields: ReadonlyArray<IField>,
    crosswalk: ICrosswalkFieldHash,
    progressCallback: (progress: IExportProgress) => void,
    errorCallback: (error: IExportError) => void
  ): Promise<void> {
    const errors: Array<IExportError> = []
    this.exportAlias = alias
    this.exportCrosswalk = crosswalk
    this.files = []

    const missing = this._missingFields(fields, crosswalk)
    if (missing) {
      return Promise.reject(
        new Error(missing.toString().replace(/,/gi, "\n"))
      )
    }

    try {
      sync(`${location}/files`)
    } catch (e) {
      return Promise.reject(e)
    }

    progressCallback({ value: undefined, description: 'Getting item records' })
    const exportStream = createWriteStream(`${location}/metadata.csv`)
    const data = await this.records(alias)

    await this._processBulkraxRecords(
      data.records,
      fields,
      exportStream,
      progressCallback,
      (error: IExportError) => {
        errors.push(error)
        errorCallback(error)
      }
    )
    exportStream.end()

    if (errors.length > 0) {
      this.processErrors(errors, location)
    }

    if (this.files) {
      await this._downloadFiles(this.files, `${location}/files/trash.txt`, progressCallback)
    }

    progressCallback({
      value: 1,
      description: `Mapped ${data.records.length} items`,
      subdescription: `Collection total file size: ${filesize(this.totalFileSize(this.files))}`
    })

  }


private async records(
    alias: string,
    start: number = 1,
    prevData?: any
  ): Promise<any> {
    alias = alias.replace('/', '')
    const s = String(start)

    return this.cdm._request(
      'dmQuery',
      [alias, '0', '0', 'filetype', '1024', s, '0', '0', '0', '0', '1', '0']
    )
      .then((data) => {
        if (prevData) {
          data.records = data.records.concat(prevData.records)
        }
        if (data.pager.total >= start + 1024) {
          return this.records(alias, start + 1025, data)
        }
        else {
          return data
        }
      })
  }


private async getRecord(
    record: any,
    compoundProgressCallback?: (item: number, total: number) => void
  ): Promise<any> {
    const item = await this.cdm.item(this.exportAlias, record.pointer)

    if (record.filetype === 'cpd') {
      const object = await this.cdm.compoundObject(
        this.exportAlias,
        record.pointer
      )
      const pages = this._pages(object)

      item.files = []
      let count = 0;
      for (let page of pages) {
        if (compoundProgressCallback) {
          compoundProgressCallback(++count, pages.length)
        }
        const pageInfo = await this.cdm.item(this.exportAlias, page.pageptr)

        item.files.push({
          filename: page.pagefile,
          alias: this.exportAlias,
          pointer: page.pageptr,
          size: pageInfo.cdmfilesize,
          info: pageInfo
        })
      }
    }
    else {
      item.files = [{
        filename: record.find,
        alias: this.exportAlias,
        pointer: record.pointer,
        size: item.cdmfilesize,
        info: null
      }]
    }

    return item
  }


private _pages(object: any): ReadonlyArray<any> {
    let pages: Array<any> = new Array()

    if (object.node && object.node.node) {
      const nodes = this._toArray(object.node.node)
      nodes.map((node: any) => {
        pages = pages.concat(this._toArray(node.page))
      })
    }
    const otherPages = object.page || object.node.page || []

    return pages.concat(this._toArray(otherPages))
  }


private _toArray(obj: any): Array<any> {
    if (!obj) {
      return []
    }
    return Array.isArray(obj) ? obj : [obj]
  }


private _map(
    item: any,
    fields: ReadonlyArray<IField>,
    errorCallback?: (error: IExportError) => void,
    itemLevel?: boolean
  ): any {

    if (!item) {
      return []
    }

    let mapItem: any = []
    for (let field of fields) {
      const nicks = this.exportCrosswalk[field.id] ?
        this.exportCrosswalk[field.id].nicks.filter((nick: string) => nick !== '') :
        []
      const exportItem = this.exportCrosswalk[field.id] ?
        this.exportCrosswalk[field.id].itemExport : false

      let value = ''
      if (itemLevel && !exportItem) {
        value = ''
      }
      else {
        nicks.map((nick: string) => {
          value += (typeof item[nick] === 'string') ? item[nick].replace(/;+$/g, '') + "; " : ""
        })
        value = value.slice(0, -2)
      }

      if (errorCallback && field.required && value === "") {
        errorCallback({
          description: `Item ${item['dmrecord']} '${item['title']}' is missing data for required field '${field.name}'`
        })
      }

      mapItem.push(value)
    }
    return mapItem
  }


private async _processRecords(
    records: any,
    fields: ReadonlyArray<IField>,
    exportStream: WriteStream,
    progressCallback: (progress: IExportProgress) => void,
    errorCallback: (error: IExportError) => void
  ): Promise<any> {

    let count = 0
    let items: Array<any> = [['Object Type', 'Filename']
      .concat(
        fields.map((key) => {
          return key.name;
        })
      )]

    for (let record of records) {
      const progressValue = count / records.length
      progressCallback({
        value: progressValue,
        description: `Mapping item ${++count} of ${records.length}`
      })

      const item = await this.getRecord(record, (cpo, cpototal) => {
        if (cpototal > 30) { // threshold so the display doesn't get to crazy
          progressCallback({
            value: progressValue,
            description: `Mapping item ${count} of ${records.length}`,
            subdescription: `Getting compound object item record ${cpo} of ${cpototal}`
          })
        }
      })
      items.push(['GenericWork', ''].concat(this._map(item, fields, errorCallback)))

      item.files.map((file: any) => {
        this.files.push(file)
        items.push(['File', file.filename].concat(this._map(file.info, fields, undefined, true)))
      })

      const csvData = await csvString(items)
      await exportStream.write(csvData)
      items = []

      if (__DEV__) {
        console.log(`heapTotal: ${Math.round(process.memoryUsage().heapTotal / 1e6)}MB, heapUsed: ${Math.round(process.memoryUsage().heapUsed / 1e6)}MB`);
      }
    }
  }


private async _processBulkraxRecords(
    records: any,
    fields: ReadonlyArray<IField>,
    exportStream: WriteStream,
    progressCallback: (progress: IExportProgress) => void,
    errorCallback: (error: IExportError) => void
  ): Promise<any> {

    let count = 0
    let items: Array<any> = [['source_identifier']
      .concat(
        fields.map((key) => {
          return key.name.toLowerCase()
        }),
        'file'
      )]

    for (let record of records) {
      const progressValue = count / records.length
      progressCallback({
        value: progressValue,
        description: `Mapping item ${++count} of ${records.length}`
      })

      const item = await this.getRecord(record, (cpo, cpototal) => {
        if (cpototal > 30) { // threshold so the display doesn't get to crazy
          progressCallback({
            value: progressValue,
            description: `Mapping item ${count} of ${records.length}`,
            subdescription: `Getting compound object item record ${cpo} of ${cpototal}`
          })
        }
      })
      const filenames: Array<String> = []
      item.files.map((file: any) => {
        this.files.push(file)
        filenames.push(file.filename)
      })

      items.push([v4()].concat(this._map(item, fields, errorCallback), filenames.join(';')))

      const csvData = await csvString(items)
      await exportStream.write(csvData)
      items = []
    }
  }


private async _downloadFiles(
    files: any,
    location: string,
    progressCallback: (progress: IExportProgress) => void
  ): Promise<any> {

    let totalTransfered = 0
    const totalSize = this.totalFileSize(files)

    for (let file of files) {
      await this.cdm.download(file, dirname(location), (bytes) => {
        totalTransfered += bytes
        const transfered = filesize(totalTransfered, { output: "object" }) as any

        progressCallback({
          value: (totalTransfered / totalSize),
          description: `Downloaded ${transfered.value.toFixed(1)} ${transfered.symbol}
            of ${filesize(totalSize, { round: 1 })}`,
          subdescription: `Downloading ${file.filename}`
        })
      })
    }
  }


private totalFileSize(files: any): number {
    return files.reduce((acc: number, cur: any) => acc + Number(cur.size), 0)
  }


private downloadLocation(location: string): string {
    let csvFile = basename(location)
    let newLocation = dirname(location) + '/' + basename(location, '.csv')

    try {
      sync(newLocation)
    }
    catch (err) {
      return location
    }

    return newLocation + '/' + csvFile
  }


private _missingFields(
    fields: ReadonlyArray<IField>,
    crosswalk: ICrosswalkFieldHash
  ): ReadonlyArray<string> | null {
    if (!crosswalk) {
      return ["No fields mapped"]
    }

    const required = fields.filter(field => field.required)
    const missing = required.filter(field => {
      return crosswalk[field.id].nicks.filter((nick: string) => nick !== '').length === 0
    })

    const err = missing.map((field) => {
      return `Missing required field '${field.name}'`
    })

    return err.length > 0 ? err : null
  }


private processErrors(errors: ReadonlyArray<IExportError>, location: string) {
    const date = this.toLocalDateString()
    const alias = this.exportAlias.replace('/', '')
    const errorLocation = dirname(location) + `/errors_${alias}_${date}.txt`
    let errorString = ""
    errors.map((error) => {
      errorString += error.description + "\n"
    })
    writeFile(errorLocation, errorString, (err) => {
      if (err) {
        console.error(err)
      }
    })
  }


private toLocalDateString(): string {
    const date = new Date();
    return String(date.getFullYear()) +
      ('0' + (date.getMonth() + 1)).slice(-2) +
      ('0' + date.getDate()).slice(-2) + '_' +
      ('0' + date.getHours()).slice(-2) +
      ('0' + date.getMinutes()).slice(-2)
  }


(data: any) => {
        if (data.token) {

          // save token to service
          this.session.firebaseTempAuthToken = data.token;

          // navigate to /login with custom firebase login token
          this.router.navigate(['/login'], { queryParams: { token: 'check' } });
        } else {
          // failed to get auth token so redirect to unauthorized
          this.unauthorized();
        }
      }


(err: any) => {
        console.log(err);
        // failed 2fa so redirect to unauthorized
        this.unauthorized();
      }


@Component({
  selector: 'app-verify',
  templateUrl: './verify.component.html',
  styleUrls: ['./verify.component.scss']
})
export class VerifyComponent implements OnInit {

  constructor(
    private session: SessionService,
    private confirm2fa: Confirm2faService,
    private router: Router
  ) { }

  ngOnInit() {

    // get authentication code IBMId
    const r = new HttpRequest(
      'POST',
      environment.apiRootUrl + '/sso/portal-login-totp',
      null,
      { withCredentials: true }
    );

    this.confirm2fa.go(r)
      .then((data: any) => {
        if (data.token) {

          // save token to service
          this.session.firebaseTempAuthToken = data.token;

          // navigate to /login with custom firebase login token
          this.router.navigate(['/login'], { queryParams: { token: 'check' } });
        } else {
          // failed to get auth token so redirect to unauthorized
          this.unauthorized();
        }
      }, (err: any) => {
        console.log(err);
        // failed 2fa so redirect to unauthorized
        this.unauthorized();
      });

  }

  /**
   * Redirects page to 'unauthorized' route
   *
   * @memberof VerifyComponent
   */
  unauthorized() {
    this.router.navigate(['/unauthorized']);
  }

}


ngOnInit() {

    // get authentication code IBMId
    const r = new HttpRequest(
      'POST',
      environment.apiRootUrl + '/sso/portal-login-totp',
      null,
      { withCredentials: true }
    );

    this.confirm2fa.go(r)
      .then((data: any) => {
        if (data.token) {

          // save token to service
          this.session.firebaseTempAuthToken = data.token;

          // navigate to /login with custom firebase login token
          this.router.navigate(['/login'], { queryParams: { token: 'check' } });
        } else {
          // failed to get auth token so redirect to unauthorized
          this.unauthorized();
        }
      }, (err: any) => {
        console.log(err);
        // failed 2fa so redirect to unauthorized
        this.unauthorized();
      });

  }


/**
   * Redirects page to 'unauthorized' route
   *
   * @memberof VerifyComponent
   */
unauthorized() {
    this.router.navigate(['/unauthorized']);
  }


() => {
  const { colorMode, toggleColorMode } = useColorMode();

  const [data, setData] = useState<Sol[]>([]);
  const [tempUnit, setTempUnit] = useState<TemperatureUnit>(
    TemperatureUnit.Celsius
  );

  useEffect(() => {
    getMarsWeather().then((res) =>
      setData(res.slice(0, res.length > 7 ? 7 : res.length))
    );
  }, []);

  const toggleTemperatureUnit = () => {
    setTempUnit(
      tempUnit === TemperatureUnit.Celsius
        ? TemperatureUnit.Fahrenheit
        : TemperatureUnit.Celsius
    );
  };

  return (
    <Fragment>
      <Button onClick={toggleColorMode} pos="absolute" top={8} right={8}>
        {colorMode === 'light' ? <MoonIcon /> : <SunIcon />}


() => {
    getMarsWeather().then((res) =>
      setData(res.slice(0, res.length > 7 ? 7 : res.length))
    );
  }


(res) =>
      setData(res.slice(0, res.length > 7 ? 7 : res.length))


() => {
    setTempUnit(
      tempUnit === TemperatureUnit.Celsius
        ? TemperatureUnit.Fahrenheit
        : TemperatureUnit.Celsius
    );
  }


async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: {
      origin: ['http://localhost:3001', 'http://localhost:3002'],
    },
  });

  // Pipes
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );

  // Interceptors
  app.useGlobalInterceptors(new UnauthorizedInterceptor());

  await app.listen(3000);
}


export class CreateInvoiceDto {
  @ApiProperty({ type: InvoiceDto })
  @IsNotEmpty()
  @ValidateNested({ each: true })
  invoice: InvoiceDto;

  @ApiProperty({ type: OrderDto })
  @IsNotEmpty()
  @ValidateNested({ each: true })
  order: OrderDto;

  @ApiProperty({ type: InvoiceDetailsDto })
  @IsNotEmpty()
  @ValidateNested({ each: true })
  invoiceDetail: InvoiceDetailsDto;
}


@Directive({
  selector: '[ngTransclude]'
})
export class NgTranscludeDirective {
  public viewRef:ViewContainerRef;

  private _ngTransclude:TemplateRef<any>;

  @Input()
  public set ngTransclude(templateRef:TemplateRef<any>) {
    this._ngTransclude = templateRef;
    if (templateRef) {
      this.viewRef.createEmbeddedView(templateRef);
    }
  }

  public get ngTransclude():TemplateRef<any> {
    return this._ngTransclude;
  }

  public constructor(private _viewRef:ViewContainerRef) {
    this.viewRef = _viewRef;
  }
}


export interface KeyAttribute {
  [key:string]:any;
}


async () => {
    await browser.get('/component-harness');
  }


() => {
    let loader: HarnessLoader;

    beforeEach(async () => {
      loader = ProtractorHarnessEnvironment.loader();
    });

    it('should create HarnessLoader', async () => {
      expect(loader).not.toBeNull();
    });

    it('should find required HarnessLoader for child element', async () => {
      const subcomponentsLoader = await loader.getChildLoader('.subcomponents');
      expect(subcomponentsLoader).not.toBeNull();
    });

    it('should error after failing to find required HarnessLoader for child element', async () => {
      try {
        await loader.getChildLoader('error');
        fail('Expected to throw');
      } catch (e) {
        expect(e.message)
          .toBe('Expected to find element matching selector: "error", but none was found');
      }
    });

    it('should find all HarnessLoaders for child elements', async () => {
      const loaders = await loader.getAllChildLoaders('.subcomponents,.counters');
      expect(loaders.length).toBe(2);
    });

    it('should get first matching component for required harness', async () => {
      const harness = await loader.getHarness(SubComponentHarness);
      expect(harness).not.toBeNull();
      expect(await (await harness.title()).text()).toBe('List of test tools');
    });

    it('should throw if no matching component found for required harness', async () => {
      const countersLoader = await loader.getChildLoader('.counters');
      try {
        await countersLoader.getHarness(SubComponentHarness);
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
            'Expected to find element for SubComponentHarness matching selector:' +
            ' "test-sub", but none was found');
      }
    });

    it('should get all matching components for all harnesses', async () => {
      const harnesses = await loader.getAllHarnesses(SubComponentHarness);
      expect(harnesses.length).toBe(2);
    });
  }


async () => {
      loader = ProtractorHarnessEnvironment.loader();
    }


async () => {
      expect(loader).not.toBeNull();
    }


async () => {
      const subcomponentsLoader = await loader.getChildLoader('.subcomponents');
      expect(subcomponentsLoader).not.toBeNull();
    }


async () => {
      try {
        await loader.getChildLoader('error');
        fail('Expected to throw');
      } catch (e) {
        expect(e.message)
          .toBe('Expected to find element matching selector: "error", but none was found');
      }
    }


async () => {
      const loaders = await loader.getAllChildLoaders('.subcomponents,.counters');
      expect(loaders.length).toBe(2);
    }


async () => {
      const harness = await loader.getHarness(SubComponentHarness);
      expect(harness).not.toBeNull();
      expect(await (await harness.title()).text()).toBe('List of test tools');
    }


async () => {
      const countersLoader = await loader.getChildLoader('.counters');
      try {
        await countersLoader.getHarness(SubComponentHarness);
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
            'Expected to find element for SubComponentHarness matching selector:' +
            ' "test-sub", but none was found');
      }
    }


async () => {
      const harnesses = await loader.getAllHarnesses(SubComponentHarness);
      expect(harnesses.length).toBe(2);
    }


() => {
    let harness: MainComponentHarness;

    beforeEach(async () => {
      harness = await ProtractorHarnessEnvironment.loader().getHarness(MainComponentHarness);
    });

    it('should locate a required element based on CSS selector', async () => {
      const title = await harness.title();
      expect(await title.text()).toBe('Main Component');
    });

    it('should throw when failing to locate a required element based on CSS selector', async () => {
      try {
        await harness.errorItem();
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
          'Expected to find element matching selector: "wrong locator", but none was found');
      }
    });

    it('should locate an optional element based on CSS selector', async () => {
      const present = await harness.optionalDiv();
      const missing = await harness.nullItem();
      expect(present).not.toBeNull();
      expect(await present!.text()).toBe('Hello Yi from Angular 2!');
      expect(missing).toBeNull();
    });

    it('should locate all elements based on CSS selector', async () => {
      const labels = await harness.allLabels();
      expect(labels.length).toBe(2);
      expect(await labels[0].text()).toBe('Count:');
      expect(await labels[1].text()).toBe('AsyncCounter:');
    });

    it('should locate required sub harnesses', async () => {
      const items = await harness.getTestTools();
      expect(items.length).toBe(3);
      expect(await items[0].text()).toBe('Protractor');
      expect(await items[1].text()).toBe('TestBed');
      expect(await items[2].text()).toBe('Other');
    });

    it('should throw when failing to locate required sub harnesses', async () => {
      try {
        await harness.errorSubComponent();
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
            'Expected to find element for WrongComponentHarness matching selector:' +
            ' "wrong-selector", but none was found');
      }
    });

    it('should locate optional sub harnesses', async () => {
      const present = await harness.optionalSubComponent();
      const missing = await harness.nullComponentHarness();
      expect(present).not.toBeNull();
      expect(await (await present!.title()).text()).toBe('List of test tools');
      expect(missing).toBeNull();
    });

    it('should locate all sub harnesses', async () => {
      const alllists = await harness.allLists();
      const items1 = await alllists[0].getItems();
      const items2 = await alllists[1].getItems();
      expect(alllists.length).toBe(2);
      expect(items1.length).toBe(3);
      expect(await items1[0].text()).toBe('Protractor');
      expect(await items1[1].text()).toBe('TestBed');
      expect(await items1[2].text()).toBe('Other');
      expect(items2.length).toBe(4);
      expect(await items2[0].text()).toBe('Unit Test');
      expect(await items2[1].text()).toBe('Integration Test');
      expect(await items2[2].text()).toBe('Performance Test');
      expect(await items2[3].text()).toBe('Mutation Test');
    });

    it('should wait for async operation to complete', async () => {
      const asyncCounter = await harness.asyncCounter();
      expect(await asyncCounter.text()).toBe('5');
      await harness.increaseCounter(3);
      expect(await asyncCounter.text()).toBe('8');
    });

    it('can get elements outside of host', async () => {
      const globalEl = await harness.globalEl();
      expect(await globalEl.text()).toBe('I am a sibling!');
    });
  }


async () => {
      harness = await ProtractorHarnessEnvironment.loader().getHarness(MainComponentHarness);
    }


async () => {
      const title = await harness.title();
      expect(await title.text()).toBe('Main Component');
    }


async () => {
      try {
        await harness.errorItem();
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
          'Expected to find element matching selector: "wrong locator", but none was found');
      }
    }


async () => {
      const present = await harness.optionalDiv();
      const missing = await harness.nullItem();
      expect(present).not.toBeNull();
      expect(await present!.text()).toBe('Hello Yi from Angular 2!');
      expect(missing).toBeNull();
    }


async () => {
      const labels = await harness.allLabels();
      expect(labels.length).toBe(2);
      expect(await labels[0].text()).toBe('Count:');
      expect(await labels[1].text()).toBe('AsyncCounter:');
    }


async () => {
      const items = await harness.getTestTools();
      expect(items.length).toBe(3);
      expect(await items[0].text()).toBe('Protractor');
      expect(await items[1].text()).toBe('TestBed');
      expect(await items[2].text()).toBe('Other');
    }


async () => {
      try {
        await harness.errorSubComponent();
        fail('Expected to throw');
      } catch (e) {
        expect(e.message).toBe(
            'Expected to find element for WrongComponentHarness matching selector:' +
            ' "wrong-selector", but none was found');
      }
    }


async () => {
      const present = await harness.optionalSubComponent();
      const missing = await harness.nullComponentHarness();
      expect(present).not.toBeNull();
      expect(await (await present!.title()).text()).toBe('List of test tools');
      expect(missing).toBeNull();
    }


async () => {
      const alllists = await harness.allLists();
      const items1 = await alllists[0].getItems();
      const items2 = await alllists[1].getItems();
      expect(alllists.length).toBe(2);
      expect(items1.length).toBe(3);
      expect(await items1[0].text()).toBe('Protractor');
      expect(await items1[1].text()).toBe('TestBed');
      expect(await items1[2].text()).toBe('Other');
      expect(items2.length).toBe(4);
      expect(await items2[0].text()).toBe('Unit Test');
      expect(await items2[1].text()).toBe('Integration Test');
      expect(await items2[2].text()).toBe('Performance Test');
      expect(await items2[3].text()).toBe('Mutation Test');
    }


async () => {
      const asyncCounter = await harness.asyncCounter();
      expect(await asyncCounter.text()).toBe('5');
      await harness.increaseCounter(3);
      expect(await asyncCounter.text()).toBe('8');
    }


async () => {
      const globalEl = await harness.globalEl();
      expect(await globalEl.text()).toBe('I am a sibling!');
    }


() => {
    let harness: MainComponentHarness;

    beforeEach(async () => {
      harness = await ProtractorHarnessEnvironment.loader().getHarness(MainComponentHarness);
    });

    it('should be able to clear', async () => {
      const input = await harness.input();
      await input.sendKeys('Yi');
      expect(await input.getAttribute('value')).toBe('Yi');

      await input.clear();
      expect(await input.getAttribute('value')).toBe('');
    });

    it('should be able to click', async () => {
      const counter = await harness.counter();
      expect(await counter.text()).toBe('0');
      await harness.increaseCounter(3);
      expect(await counter.text()).toBe('3');
    });

    it('should be able to send key', async () => {
      const input = await harness.input();
      const value = await harness.value();
      await input.sendKeys('Yi');

      expect(await input.getAttribute('value')).toBe('Yi');
      expect(await value.text()).toBe('Input: Yi');
    });

    it('focuses the element before sending key', async () => {
      const input = await harness.input();
      await input.sendKeys('Yi');
      expect(await input.getAttribute('id'))
        .toBe(await browser.driver.switchTo().activeElement().getAttribute('id'));
    });

    it('should be able to hover', async () => {
      const host = await harness.host();
      let classAttr = await host.getAttribute('class');
      expect(classAttr).not.toContain('hovering');
      await host.hover();
      classAttr = await host.getAttribute('class');
      expect(classAttr).toContain('hovering');
    });

    it('should be able to getAttribute', async () => {
      const memoStr = `
        This is an example that shows how to use component harness
        You should use getAttribute('value') to retrieve the text in textarea
      `;
      const memo = await harness.memo();
      await memo.sendKeys(memoStr);
      expect(await memo.getAttribute('value')).toBe(memoStr);
    });

    it('should be able to getCssValue', async () => {
      const title = await harness.title();
      expect(await title.getCssValue('height')).toBe('50px');
    });

    it('should focus and blur element', async () => {
      let button = await harness.button();
      expect(await (await browser.switchTo().activeElement()).getText())
          .not.toBe(await button.text());
      await button.focus();
      expect(await (await browser.switchTo().activeElement()).getText()).toBe(await button.text());
      await button.blur();
      expect(await (await browser.switchTo().activeElement()).getText())
          .not.toBe(await button.text());
    });
  }


async () => {
      const input = await harness.input();
      await input.sendKeys('Yi');
      expect(await input.getAttribute('value')).toBe('Yi');

      await input.clear();
      expect(await input.getAttribute('value')).toBe('');
    }


async () => {
      const counter = await harness.counter();
      expect(await counter.text()).toBe('0');
      await harness.increaseCounter(3);
      expect(await counter.text()).toBe('3');
    }


async () => {
      const input = await harness.input();
      const value = await harness.value();
      await input.sendKeys('Yi');

      expect(await input.getAttribute('value')).toBe('Yi');
      expect(await value.text()).toBe('Input: Yi');
    }


async () => {
      const input = await harness.input();
      await input.sendKeys('Yi');
      expect(await input.getAttribute('id'))
        .toBe(await browser.driver.switchTo().activeElement().getAttribute('id'));
    }


async () => {
      const host = await harness.host();
      let classAttr = await host.getAttribute('class');
      expect(classAttr).not.toContain('hovering');
      await host.hover();
      classAttr = await host.getAttribute('class');
      expect(classAttr).toContain('hovering');
    }


async () => {
      const memoStr = `
        This is an example that shows how to use component harness
        You should use getAttribute('value') to retrieve the text in textarea
      `;
      const memo = await harness.memo();
      await memo.sendKeys(memoStr);
      expect(await memo.getAttribute('value')).toBe(memoStr);
    }


async () => {
      const title = await harness.title();
      expect(await title.getCssValue('height')).toBe('50px');
    }


async () => {
      let button = await harness.button();
      expect(await (await browser.switchTo().activeElement()).getText())
          .not.toBe(await button.text());
      await button.focus();
      expect(await (await browser.switchTo().activeElement()).getText()).toBe(await button.text());
      await button.blur();
      expect(await (await browser.switchTo().activeElement()).getText())
          .not.toBe(await button.text());
    }