text:
title 'Cloud Key Management Service'

gcp_project_id = input('gcp_project_id')
gcp_gke_locations = input('gcp_gke_locations')
cis_version = input('cis_version')
cis_url = input('cis_url')
control_id = '5.3'
control_abbrev = 'networking'

gke_clusters = GKECache(project: gcp_project_id, gke_locations: gcp_gke_locations).gke_clusters_cache

if gke_clusters.nil? || gke_clusters.count.zero?
  control "cis-gke-#{control_id}-#{control_abbrev}" do
    title "[#{control_abbrev.upcase}] Cloud Key Management Service"
    impact 'none'
    describe "[#{gcp_project_id}] does not have any GKE clusters, this section of tests is Not Applicable." do
      skip "[#{gcp_project_id}] does not have any GKE clusters."
    end
  end
else

  # 5.3.1
  sub_control_id = "#{control_id}.1"
  control "cis-gke-#{control_id}-#{control_abbrev}" do
    impact 'medium'

    title "[#{control_abbrev.upcase}] Ensure Kubernetes Secrets are encrypted using keys managed in
    Cloud KMS"

    desc "Encrypt Kubernetes secrets, stored in etcd, at the application-layer using a customer-
    managed key in Cloud KMS."
    desc 'rationale', "By default, GKE encrypts customer content stored at rest, including Secrets. GKE handles
    and manages this default encryption for you without any additional action on your part.
    Application-layer Secrets Encryption provides an additional layer of security for sensitive
    data, such as user defined Secrets and Secrets required for the operation of the cluster,
    such as service account keys, which are all stored in etcd.
    Using this functionality, you can use a key, that you manage in Cloud KMS, to encrypt data
    at the application layer. This protects against attackers in the event that they manage to
    gain access to etcd."

    tag cis_scored: true
    tag cis_level: 1
    tag cis_gke: sub_control_id.to_s
    tag cis_version: cis_version.to_s
    tag project: gcp_project_id.to_s

    ref 'CIS Benchmark', url: cis_url.to_s
    ref 'GCP Docs', url: 'https://cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets'

    gke_clusters.each do |gke_cluster|
      describe "[#{gcp_project_id}] Cluster #{gke_cluster[:location]}/#{gke_cluster[:cluster_name]}" do
        subject { google_container_cluster(project: gcp_project_id, location: gke_cluster[:location], name: gke_cluster[:cluster_name]) }
        its('database_encryption.key_name') { should_not eq nil }
        its('database_encryption.state') { should cmp 'ENCRYPTED' }
      end
    end
  end
end


text:
const { Types } = require('./permission');
const archly = require('./archly');

var Resource = function (id) {
  this.id = id;
};
Resource.prototype.getEntryDescription = function () {
  return this.id;
};
Resource.prototype.getId = function () {
  return this.id;
};
Resource.prototype.retrieveEntry = function (id) {
  return new Resource(id);
};

var Role = function (id) {
  this.id = id;
};
Role.prototype.getEntryDescription = function () {
  return this.id;
};
Role.prototype.getId = function () {
  return this.id;
};
Role.prototype.retrieveEntry = function (id) {
  return new Role(id);
};

test('Resource Registry present', () => {
  var acl = archly.newAcl();
  expect(acl.resources).not.toBeNull();
});

test('Role Registry present', () => {
  var acl = archly.newAcl();
  expect(acl.roles).not.toBeNull();
});

test('Default', function () {
  var A = archly.newAcl(),
      rol1 = 'r1',
      res1 = 'r1';

  expect(A.isAllowed()).toBe(false);
  A.makeDefaultAllow();
  expect(A.isAllowed()).toBe(true);
  A.makeDefaultDeny();
  expect(A.isAllowed()).toBe(false);

  A.resources.add(res1);
  A.roles.add(rol1);
  expect(A.isAllowed(rol1, res1)).toBe(false); // Default false with explicit role and resource.
  expect(A.isAllowed(rol1, res1, Types.ALL)).toBe(false);
  expect(A.isAllowed(rol1, res1, Types.CREATE)).toBe(false);
  expect(A.isAllowed(rol1, res1, Types.READ)).toBe(false);
  expect(A.isAllowed(rol1, res1, Types.UPDATE)).toBe(false);
  expect(A.isAllowed(rol1, res1, Types.DELETE)).toBe(false);
  expect(A.isDenied(rol1, res1)).toBe(true);
  expect(A.isDenied(rol1, res1, Types.ALL)).toBe(true);
  expect(A.isDenied(rol1, res1, Types.CREATE)).toBe(true);
  expect(A.isDenied(rol1, res1, Types.READ)).toBe(true);
  expect(A.isDenied(rol1, res1, Types.UPDATE)).toBe(true);
  expect(A.isDenied(rol1, res1, Types.DELETE)).toBe(true);

  A.makeDefaultAllow();
  expect(A.isAllowed(rol1, res1)).toBe(true); // Default false with explicit role and resource.
  expect(A.isAllowed(rol1, res1, Types.ALL)).toBe(true);
  expect(A.isAllowed(rol1, res1, Types.CREATE)).toBe(true);
  expect(A.isAllowed(rol1, res1, Types.READ)).toBe(true);
  expect(A.isAllowed(rol1, res1, Types.UPDATE)).toBe(true);
  expect(A.isAllowed(rol1, res1, Types.DELETE)).toBe(true);
  expect(A.isDenied(rol1, res1)).toBe(false);
  expect(A.isDenied(rol1, res1, Types.ALL)).toBe(false);
  expect(A.isDenied(rol1, res1, Types.CREATE)).toBe(false);
  expect(A.isDenied(rol1, res1, Types.READ)).toBe(false);
  expect(A.isDenied(rol1, res1, Types.UPDATE)).toBe(false);
  expect(A.isDenied(rol1, res1, Types.DELETE)).toBe(false);
});

test('Test Resource', function () {
  var res1 = new Resource('ACO-1'),
      res1a = new Resource('ACO-1-A'),
      acl = archly.newAcl();

  acl.addResource(res1);
  expect(() => {
    acl.addResource(res1)
  }).toThrow("Entry 'ACO-1' is already in the registry");

  acl.addResource(res1a, res1);
  expect(() => {
    acl.addResource(res1a);
  }).toThrow("Entry 'ACO-1-A' is already in the registry");
  expect(() => {
    acl.addResource(res1a, res1);
  }).toThrow("Entry 'ACO-1-A' is already in the registry");
});

test('Test Role', function () {
  var rol1 = new Role('ARO-1'),
      rol1a = new Role('ARO-1-A'),
      acl = archly.newAcl();

  acl.addRole(rol1);
  expect(() => {
    acl.addRole(rol1);
  }).toThrow("Entry 'ARO-1' is already in the registry");
  acl.addRole(rol1a, rol1);
  expect(() => {
    acl.addRole(rol1a);
  }).toThrow("Entry 'ARO-1-A' is already in the registry");
  expect(() => {
    acl.addRole(rol1a, rol1);
  }).toThrow("Entry 'ARO-1-A' is already in the registry");
});

test('Test Allow', function () {
  var res0 = new Resource('ACO-0'),
      rol0 = new Role('ARO-0'),
      res1 = new Resource('ACO-1'),
      rol1 = new Role('ARO-1'),
      res2 = new Resource('ACO-2'),
      rol2 = new Role('ARO-2'),
      acl = archly.newAcl();

  expect(acl.isAllowed(rol1, res1)).toBe(false); // Permission not set.
  acl.allow(rol1, res1);
  expect(acl.isAllowed(rol1, res1)).toBe(true);

  expect(acl.isAllowed(rol0, res1)).toBe(false); // Permission not set.
  expect(acl.isAllowed(rol0, res2)).toBe(false);
  acl.allowAllResource(rol0);
  expect(acl.isAllowed(rol0, res1)).toBe(true); // Granted via all resource.
  expect(acl.isAllowed(rol0, res2)).toBe(true);
  expect(acl.isAllowed(rol1, res0)).toBe(false);
  expect(acl.isAllowed(rol2, res0)).toBe(false);
  acl.allowAllRole(res0);
  expect(acl.isAllowed(rol1, res0)).toBe(true);
  expect(acl.isAllowed(rol2, res0)).toBe(true);

  expect(acl.isAllowed(rol2, res2, Types.CREATE)); // Permission not set.
  expect(acl.isAllowed(rol2, res2, Types.READ));
  acl.allow(rol2, res2, Types.CREATE);
  expect(acl.isAllowed(rol2, res2, Types.CREATE)); // Role2 allowed CREATE access.
  expect(acl.isAllowed(rol2, res2, Types.READ));

  acl.allowAllResource(rol0); // Repeated addition of roles does not throw error.
  acl.allowAllRole(res0); // Repeated addition of resource does not throw error.
  acl.allow(rol2, res2, Types.CREATE); // Repeated addition of role and resource does not throw error.
});

test('Test Deny', function () {
  var res0 = new Resource('ACO-ZZ'),
      rol0 = new Role('ARO-ZZ'),
      res1 = new Resource('ACO-A'),
      rol1 = new Role('ARO-A'),
      res2 = new Resource('ACO-B'),
      rol2 = new Role('ARO-B'),
      acl = archly.newAcl();

  // Make default allow otherwise isDenied() will also return false
  acl.makeDefaultAllow();
  expect(acl.isDenied(rol1, res1)).toBe(false);
  acl.deny(rol1, res1);
  // Role A denied access to Res A.
  expect(acl.isDenied(rol1, res1)).toBe(true);
  expect(acl.isDenied(rol0, res1)).toBe(false); // Permission not set.
  expect(acl.isDenied(rol0, res2)).toBe(false);

  acl.denyAllResource(rol0);
  expect(acl.isDenied(rol0, res1)).toBe(true); // Denied via all resource.
  expect(acl.isDenied(rol0, res2)).toBe(true);
  expect(acl.isDenied(rol1, res0)).toBe(false); // Permission not set.
  expect(acl.isDenied(rol2, res0)).toBe(false);

  acl.denyAllRole(res0);
  expect(acl.isDenied(rol1, res0)).toBe(true); // Denied via all role.
  expect(acl.isDenied(rol2, res0)).toBe(true);

  expect(acl.isDenied(rol2, res2, Types.CREATE)).toBe(false); // Permission not set.
  expect(acl.isDenied(rol2, res2, Types.READ)).toBe(false);

  acl.deny(rol2, res2, Types.CREATE);
  expect(acl.isDenied(rol2, res2, Types.CREATE)).toBe(true); // Role  2 denied CREATE access to Res 2
  expect(acl.isDenied(rol2, res2, Types.READ)).toBe(false); // Permission not set.

  expect(acl.denyAllResource(rol0)).toBeUndefined(); // Repeated addition of role does not throw error.
});

test('Test Remove', function () {
  var res1 = new Resource('reso-a'),
      rol1 = new Role('role-a'),
      res2 = new Resource('reso-b'),
      rol2 = new Role('role-b'),
      acl = archly.newAcl();

  // Set to default allow to test deny().
  acl.makeDefaultAllow();
  acl.deny(rol2, res2, Types.CREATE);

  expect(acl.isDenied(rol2, res2, Types.CREATE)).toBe(true); // Denied from above.
  expect(acl.isDenied(rol2, res2)).toBe(false); // Default is allow.

  // Permission entry is in the registry.
  expect(acl.permissions.has(rol2.getId() + '::' + res2.getId())).toBe(true);

  acl.remove(rol2, res2, Types.CREATE);
  expect(acl.isDenied(rol2, res2)).toBe(false); // No change.
  // Empty permission entry is removed from the registry.
  expect(acl.permissions.has(rol2.getId() + '::' + res2.getId())).toBe(false);

  acl.deny(rol1, res1);
  expect(acl.isDenied(rol1, res1, Types.CREATE)).toBe(true); // Denied set on ALL.
  expect(acl.isDenied(rol1, res1, Types.READ)).toBe(true);
  expect(acl.isDenied(rol1, res1, Types.UPDATE)).toBe(true);
  expect(acl.isDenied(rol1, res1, Types.DELETE)).toBe(true);
  expect(acl.isDenied(rol1, res1)).toBe(true); // Deny set on ALL.

  acl.remove(rol1, res1, Types.CREATE);
  expect(acl.isDenied(rol1, res1, Types.CREATE)).toBe(false); // CREATE DENY permission removed.
  expect(acl.isDenied(rol1, res1, Types.READ)).toBe(true);
  expect(acl.isDenied(rol1, res1, Types.UPDATE)).toBe(true);
  expect(acl.isDenied(rol1, res1, Types.DELETE)).toBe(true);
  expect(acl.isDenied(rol1, res1)).toBe(false); // CREATE is removed.

  acl.remove(rol1, res1);
  expect(acl.isDenied(rol1, res1, Types.CREATE)).toBe(false); // DENY permissions removed.
  expect(acl.isDenied(rol1, res1, Types.READ)).toBe(false);
  expect(acl.isDenied(rol1, res1, Types.UPDATE)).toBe(false);
  expect(acl.isDenied(rol1, res1, Types.DELETE)).toBe(false);
  expect(acl.isDenied(rol1, res1)).toBe(false);
});

test('Test Hierarchy', function () {
  var res1  = new Resource('RES1'),
      res2  = new Resource('RES2'),
      res3  = new Resource('RES3'),
      res4  = new Resource('RES4'),
      res1a = new Resource('RES1-a'),
      res1b = new Resource('RES1-b'),
      res1c = new Resource('RES1-c'),
      res1a1= new Resource('RES1-a-1'),
      res1a2= new Resource('RES1-a-2'),
      res1b1= new Resource('RES1-b-1'),
      res1c1= new Resource('RES1-c-1'),
      rol1  = new Role('R1'),
      rol2  = new Role('R2'),
      rol3  = new Role('R3'),
      rol4  = new Role('R4'),
      rol1a = new Role('R1-a'),
      rol1b = new Role('R1-b'),
      rol1c = new Role('R1-c'),
      rol1a1= new Role('R1-a-1'),
      rol1a2= new Role('R1-a-2'),
      rol1b1= new Role('R1-b-1'),
      acl = archly.newAcl();

  //add RES1, RES2, RES1-a
  acl.addResource(res1);
  acl.addResource(res2);
  acl.addResource(res1a, res1);
  acl.addResource(res1b, res1);
  acl.addResource(res1c, res1);
  acl.addResource(res1a1, res1a);
  acl.addResource(res1a2, res1a);
  acl.addResource(res1b1, res1b);
  acl.addResource(res1c1, res1c);

  //Add R1, R2, R1-a
  acl.addRole(rol1);
  acl.addRole(rol2);
  acl.addRole(rol1a, rol1);
  acl.addRole(rol1b, rol1);
  acl.addRole(rol1c, rol1);
  acl.addRole(rol1a1, rol1a);
  acl.addRole(rol1a2, rol1a);
  acl.addRole(rol1b1, rol1b);

  acl.makeDefaultDeny();

  // Grant ALL access to res1b, deny ALL to res1c.
  acl.allowAllRole(res1b);
  acl.denyAllRole(res1c);
  acl.allow(rol1, res1);

  //1-1
  expect(acl.isAllowed(rol1,  res1)).toBe(true);      // R1 allow RES1
  expect(acl.isAllowed(rol1,  res1a)).toBe(true);     // RES1-a child of RES1
  expect(acl.isAllowed(rol1,  res1a1)).toBe(true);    // RES1-a-1 descendent of RES1
  expect(acl.isAllowed(rol1,  res1a2)).toBe(true);    // RES1-a-2 descendent of RES1
  expect(acl.isAllowed(rol1,  res1b)).toBe(true);     // RES1-b child of RES1
  expect(acl.isAllowed(rol1,  res1b1)).toBe(true);    // RES1-b-1 descendant of RES1
  //R1 allowed to RES1 - overrides * deny RES1-c
  expect(acl.isAllowed(rol1,  res1c)).toBe(true);     // R1 allow to RES1 overrides * deny to RES1-c
  expect(acl.isAllowed(rol1,  res1c1)).toBe(true);    // R1 allow to RES1 overrides * deny to RES1-c
  //1-2
  expect(acl.isDenied(rol1,     res2)).toBe(true);    // Default deny
  //1-3
  expect(acl.isDenied(rol1,     res3)).toBe(true);    // Default deny
  //2-1
  expect(acl.isDenied(rol2,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol2,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol2,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol2,   res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol2,   res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //2-2 - R2::RES2 should be CREATE-true
  acl.allow(rol2, res2, 'CREATE');
  expect(acl.isDenied(rol2,    res2)).toBe(false);  // To mirror the Java test
  //2-3
  expect(acl.isDenied(rol2,   res3)).toBe(true);      // Default deny
  //3-1
  expect(acl.isDenied(rol3,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol3,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol3,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol3,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol3,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol3,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //3-2
  expect(acl.isDenied(rol3,   res2)).toBe(true);      // Default deny
  //3-3
  expect(acl.isDenied(rol3,   res3)).toBe(true);      // Default deny
  //4-1
  expect(acl.isDenied(rol4,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol4,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol4,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol4,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol4,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol4,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  expect(acl.isDenied(rol4,   res1c)).toBe(true);     // Default deny
  expect(acl.isDenied(rol4,   res1c1)).toBe(true);    // Default deny

  acl.deny(rol1, res1a);

  //1-1
  expect(acl.isAllowed(rol1,  res1)).toBe(true);      // R1 allow RES1
  expect(acl.isDenied(rol1,   res1a)).toBe(true);     // R1 deny RES1-a
  expect(acl.isDenied(rol1,   res1a1)).toBe(true);    // RES1-a-1 descendent of RES1
  expect(acl.isDenied(rol1,   res1a2)).toBe(true);    // RES1-a-2 descendent of RES1
  expect(acl.isAllowed(rol1,  res1b)).toBe(true);     // RES1-b child of RES1
  expect(acl.isAllowed(rol1,  res1b1)).toBe(true);    // RES1-b-1 descendant of RES1
  //R1 allowed to RES1 - overrides * deny RES1-c
  expect(acl.isAllowed(rol1,  res1c)).toBe(true);     // R1 allow to RES1 overrides * deny to RES1-c
  expect(acl.isAllowed(rol1,  res1c1)).toBe(true);    // R1 allow to RES1 overrides * deny to RES1-c
  //1-2
  expect(acl.isDenied(rol1,     res2)).toBe(true); // Default deny
  //1-3
  expect(acl.isDenied(rol1,     res3)).toBe(true); // Default deny
  //2-1
  expect(acl.isDenied(rol2,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol2,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol2,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol2,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol2,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //2-2 - R2::RES2 should be CREATE-true from above
  expect(acl.isDenied(rol2,    res2)).toBe(false);  // To mirror the Java test
  //2-3
  expect(acl.isDenied(rol2,   res3)).toBe(true);      // Default deny
  //3-1
  expect(acl.isDenied(rol3,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol3,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol3,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol3,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol3,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol3,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //3-2
  expect(acl.isDenied(rol3,   res2)).toBe(true);      // Default deny
  //3-3
  expect(acl.isDenied(rol3,   res3)).toBe(true);      // Default deny

  acl.allow(rol1, res1a1);

  //1-1
  expect(acl.isAllowed(rol1,  res1)).toBe(true);      // R1 allow RES1
  expect(acl.isDenied(rol1,   res1a)).toBe(true);     // R1 deny RES1-a
  expect(acl.isAllowed(rol1,  res1a1)).toBe(true);    // R1 allow RES1-a-1
  expect(acl.isDenied(rol1,   res1a2)).toBe(true);    // RES1-a-2 descendent of RES1-a
  expect(acl.isAllowed(rol1,  res1b)).toBe(true);     // RES1-b child of RES1
  expect(acl.isAllowed(rol1,  res1b1)).toBe(true);    // RES1-b-1 descendant of RES1
  //R1 allowed to RES1 - overrides * deny RES1-c
  expect(acl.isAllowed(rol1,  res1c)).toBe(true);     // R1 allow to RES1 overrides * deny to RES1-c
  expect(acl.isAllowed(rol1,  res1c1)).toBe(true);    // R1 allow to RES1 overrides * deny to RES1-c
  //1-2
  expect(acl.isDenied(rol1,   res2)).toBe(true);      // Default deny
  //1-3
  expect(acl.isDenied(rol1,   res3)).toBe(true); // Default deny
  //2-1
  expect(acl.isDenied(rol2,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol2,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol2,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol2,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol2,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //2-2 - R2::RES2 should be CREATE-true from above
  expect(acl.isDenied(rol2,res2)).toBe(false);  // To mirror the Java test
  //2-3
  expect(acl.isDenied(rol2,   res3)).toBe(true);      // Default deny
  //3-1
  expect(acl.isDenied(rol3,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol3,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol3,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol3,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol3,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol3,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //3-2
  expect(acl.isDenied(rol3,   res2)).toBe(true);      // Default deny
  //3-3
  expect(acl.isDenied(rol3,   res3)).toBe(true);      // Default deny

  //deny R2 to RES1-b; test overriding of ALL allow
  acl.deny(rol2, res1b);

  //1-1
  expect(acl.isAllowed(rol1,  res1)).toBe(true);      // R1 allow RES1
  expect(acl.isDenied(rol1,   res1a)).toBe(true);     // R1 deny RES1-a
  expect(acl.isAllowed(rol1,  res1a1)).toBe(true);    // R1 allow RES1-a-1
  expect(acl.isDenied(rol1,   res1a2)).toBe(true);    // RES1-a-2 descendent of RES1-a
  expect(acl.isAllowed(rol1,  res1b)).toBe(true);     // RES1-b child of RES1
  expect(acl.isAllowed(rol1,  res1b1)).toBe(true);    // RES1-b-1 descendant of RES1
  //R1 allowed to RES1 - overrides * deny RES1-c
  expect(acl.isAllowed(rol1,  res1c)).toBe(true);     // R1 allow to RES1 overrides * deny to RES1-c
  expect(acl.isAllowed(rol1,  res1c1)).toBe(true);    // R1 allow to RES1 overrides * deny to RES1-c
  //1-2
  expect(acl.isDenied(rol1,   res2)).toBe(true);      // Default deny
  //1-3
  expect(acl.isDenied(rol1,   res3)).toBe(true);      // Default deny
  //2-1
  expect(acl.isDenied(rol2,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol2,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol2,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1a2)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1b)).toBe(true);     // R2 deny RES1-bb
  expect(acl.isDenied(rol2,   res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //2-2 - R2::RES2 should be CREATE-true from above
  expect(acl.isDenied(rol2,    res2)).toBe(false);  // To mirror the Java test
  //2-3
  expect(acl.isDenied(rol2,   res3)).toBe(true);      // Default deny
  //3-1
  expect(acl.isDenied(rol3,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol3,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol3,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol3,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol3,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol3,  res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //3-2
  expect(acl.isDenied(rol3,   res2)).toBe(true);      // Default deny
  //3-3
  expect(acl.isDenied(rol3,   res3)).toBe(true);      // Default deny

  //deny R3 o RES1-b-1; test specific deny over ALL allow
  acl.deny(rol3, res1b1);

  //1-1
  expect(acl.isAllowed(rol1,  res1)).toBe(true);      // R1 allow RES1
  expect(acl.isDenied(rol1,   res1a)).toBe(true);     // R1 deny RES1-a
  expect(acl.isAllowed(rol1,  res1a1)).toBe(true);    // R1 allow RES1-a-1
  expect(acl.isDenied(rol1,   res1a2)).toBe(true);    // RES1-a-2 descendent of RES1-a
  expect(acl.isAllowed(rol1,  res1b)).toBe(true);     // RES1-b child of RES1
  expect(acl.isAllowed(rol1,  res1b1)).toBe(true);    // RES1-b-1 descendant of RES1
  //R1 allowed to RES1 - overrides * deny RES1-c
  expect(acl.isAllowed(rol1,  res1c)).toBe(true);     // R1 allow to RES1 overrides * deny to RES1-c
  expect(acl.isAllowed(rol1,  res1c1)).toBe(true);    // R1 allow to RES1 overrides * deny to RES1-c
  //1-2
  expect(acl.isDenied(rol1,   res2)).toBe(true);      // Default deny
  //1-3
  expect(acl.isDenied(rol1,   res3)).toBe(true);      // Default deny
  //2-1
  expect(acl.isDenied(rol2,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol2,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol2,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1a2)).toBe(true);    // Default deny
  expect(acl.isDenied(rol2,   res1b)).toBe(true);     // R2 deny RES1-bb
  expect(acl.isDenied(rol2,   res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //2-2 - R2::RES2 should be CREATE-true from above
  expect(acl.isDenied(rol2,    res2)).toBe(false);  // To mirror the Java test
  //2-3
  expect(acl.isDenied(rol2,   res3)).toBe(true);      // Default deny
  //3-1
  expect(acl.isDenied(rol3,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol3,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol3,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol3,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol3,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isDenied(rol3,   res1b1)).toBe(true);    // RES1-b-1 child of RES1-b
  //3-2
  expect(acl.isDenied(rol3,   res2)).toBe(true);      // Default deny
  //3-3
  expect(acl.isDenied(rol3,   res3)).toBe(true);      // Default deny

  //test coverage
  acl.allow(rol4, res1c);
  //4-1
  expect(acl.isDenied(rol4,   res1)).toBe(true);      // Default deny
  expect(acl.isDenied(rol4,   res1a)).toBe(true);     // Default deny
  expect(acl.isDenied(rol4,   res1a1)).toBe(true);    // Default deny
  expect(acl.isDenied(rol4,   res1a2)).toBe(true);    // Default deny
  expect(acl.isAllowed(rol4,  res1b)).toBe(true);     // All access to RES1-b
  expect(acl.isAllowed(rol4,  res1b1)).toBe(true);    // All access to RES1-b
  expect(acl.isAllowed(rol4,  res1c)).toBe(true);     // R4 allow to RES1-c
  expect(acl.isAllowed(rol4,  res1c1)).toBe(true);    // RES1-c-1 child of RES1-c
  expect(acl.isDenied(rol4,   res4)).toBe(true);      // Default deny

  acl.allow(rol4, res4);
  expect(acl.isAllowed(rol4,  res4)).toBe(true);      // Default deny
});

test('Test Remove NULL', function () {
  var rolna = new Role('NA-ROLE'),
      resna = new Resource('NA-RES'),
      nullrol = null,
      nullres = null,
      acl = archly.newAcl();

  expect(acl.isAllowed(rolna, resna)).toBe(false); // Default deny
  expect(acl.isDenied(rolna, resna)).toBe(true); // Default deny

  acl.remove(nullrol, nullres);

  expect(acl.isAllowed(rolna, resna)).toBe(false); // False because the root is removed
  expect(acl.isDenied(rolna, resna)).toBe(false);  // False because the root is removed

  expect(() => {
    acl.remove(nullrol, nullres, Types.CREATE);
  }).toThrow("Permission '*::*' not found on '*' for '*'.");
});

test('Test Remove Resource/Role', function () {
  var resources = ['C1', 'C2', 'C3', 'C4'],
      roles = ['R1', 'R2', 'R3', 'R4'],
      A = archly.newAcl(),
      P = A.permissions,
      RESR = A.resources,
      ROLR = A.roles;

  //create mappings for each key pair
  for (var i = 0; i < resources.length; i++) {
    for (var j = 0; j < roles.length; j++) {
      A.allow(new Role(roles[j]), new Resource(resources[i]));
      expect(A.isAllowed(new Role(roles[j]), new Resource(resources[i]))).toBe(true);
    }
  }

  //add children to both resources and roles
  for (var i = 1; i <= 4; i++) {
    A.addResource(new Resource('CC' + i), new Resource('C' + i));
    A.addRole(new Role('RC' + i), new Role('R' + i));
  }

  //assign permission for child1 to child2
  A.allow(new Role('RC1'), new Resource('CC2'));
  A.allow(new Role('RC2'), new Resource('CC1'));

  //add ALL access
  for (var i = 0; i < resources.length; i++) {
    A.allowAllRole(new Resource(resources[i]));
    expect(A.isAllowed(new Role('*'), new Resource(resources[i])));
  }
  for (var i = 0; i < roles.length; i++) {
    A.allowAllResource(new Role(roles[i]));
    expect(A.isAllowed(new Role(roles[i]), new Resource('*')));
  }

  //4x4 pairs, 2x4 ALL access, 1 child each
  expect(P.size()).toBe(27); // 1 + 4x4 + 4 + 4 + 1 + 1
  expect(RESR.size()).toBe(8); // 4+4; 4 resources each with a child
  expect(ROLR.size()).toBe(8); // 4+4; 4 roles each with a child

  //remove all access on C4
  A.removeResource(new Resource('C4'), false);
  expect(P.size()).toBe(22); // 1 + 4x3 + 4 + 3 + 1 + 1; less C4 but not its child
  expect(RESR.size()).toBe(7); // 3+4; less C4 but not its child
  expect(ROLR.size()).toBe(8); // 4+4

  //remove all access on R4
  A.removeRole(new Role('R4'), false);
  expect(P.size()).toBe(18); // 1 + 3x3 + 3 + 3 + 1 + 1; less R4 but not its child
  expect(RESR.size()).toBe(7); // 3+4
  expect(ROLR.size()).toBe(7); // 3+4; less R4 but not its child

  //remove all access on C3 and child
  A.removeResource(new Resource('C3'), true);
  expect(P.size()).toBe(14); // 1 + 3x2 + 3 + 2 + 1 + 1; less C3 and child
  expect(RESR.size()).toBe(5); // 2+3; less C3 and child
  expect(ROLR.size()).toBe(7); // 3+4

  //remove all access on R3 and child
  A.removeRole(new Role('R3'), true);
  expect(P.size()).toBe(11); // 1 + 2x2 + 2 + 2 + 1 + 1; less R3 and child
  expect(RESR.size()).toBe(5); // 2+3
  expect(ROLR.size()).toBe(5); // 2+3; less R3 and child

  //remove all access on C2 and child
  A.removeResource(new Resource('C2'), true);
  expect(P.size()).toBe(7); // 1 + 2x1 + 2 + 1 + 1 + 0; less child permission
  expect(RESR.size()).toBe(3); // 1+2; less C2 and child
  expect(ROLR.size()).toBe(5); // 2+3

  //remove all access on R2 and child
  A.removeRole(new Role('R2'), true);
  expect(P.size()).toBe(4); // 1 + 1x1 + 1 + 1 + 0 + 0; less child permission
  expect(RESR.size()).toBe(3); // 1+2
  expect(ROLR.size()).toBe(3); // 1+2; less R2 and child

  //remove all access on C1 and child
  A.removeResource('C1', true);
  expect(P.size()).toBe(2); // 1 + 1x0 + 1 + 0 + 0 + 0; less C1 and child
  expect(RESR.size()).toBe(1); // 0+1; less C1 and child
  expect(ROLR.size()).toBe(3); // 1+2

  //remove all access on R1 and child
  A.removeRole('R1', true);
  expect(P.size()).toBe(1); // 1 + 0x0 + 0 + 0 + 0 + 0; less R1 and child
  expect(RESR.size()).toBe(1); // 0+1
  expect(ROLR.size()).toBe(1); // 0+1; less R1 and child

  //test coverage
  expect(() => {
    A.removeResource(null, false);
  }).toThrow("Cannot remove null resource");

  expect(() => {
    A.removeRole(null, false);
  }).toThrow("Cannot remove null role");
});

test('Test Export/Import', function () {
  //test export
  var A = archly.newAcl();
  var resources = A.exportResources();
  var roles = A.exportRoles();
  var perms = A.exportPermissions();

  //verify that the exported data are snapshots
  A.addResource('laser-gun');
  A.addRole('jedi');
  A.deny('jedi', 'laser-gun');

  var newRes = A.exportResources();
  var newRoles = A.exportRoles();
  var newPerms = A.exportPermissions();

  expect(Object.keys(newRes).length > Object.keys(resources).length).toBe(true); // Exported resources is unaffected
  expect(Object.keys(newRoles).length > Object.keys(roles).length).toBe(true); // Exported roles is unaffected
  expect(Object.keys(newPerms).length > Object.keys(perms).length).toBe(true); // Exported permissions is unaffected

  //simulate saved data
  newRes = {
    'laser-gun': '',
    'light-sabre': '',
    'staff': 'light-sabre',
    't': 'light-sabre'
  };
  newRoles = {
    'jedi': '',
    'sith': '',
    'obiwan': 'jedi',
    'luke': 'jedi',
    'darth-vader': 'sith',
    'darth-maul': 'sith'
  };
  newPerms = {
    '*::*': { ALL: false },
    'jedi::light-sabre':    { ALL: true },
    'jedi::laser-gun':      { ALL: false },
    'sith::light-sabre':    { ALL: true },
    'sith::laser-gun':      { ALL: true },
    'luke::laser-gun':      { ALL: true },
    'jedi::t':              { ALL: false }
  };

  //test import
  expect(() => {
    A.importResources(newRes);
  }).toThrow('resources registry is not empty'); // Resources are non-empty.
  expect(() => {
    A.importRoles(newRoles);
  }).toThrow('roles registry is not empty'); // Roles are non-empty.
  expect(() => {
    A.importPermissions(newPerms);
  }).toThrow('permissions registry is not empty'); // Permissions are non-empty.

  A.clear();
  A.importResources(newRes);
  A.importRoles(newRoles);
  A.importPermissions(newPerms);
  expect(A.visualize()).toBeTruthy();
  expect(A.visualizePermissions()).toBeTruthy();
  expect(A.visualizeResources(new Role())).toBeTruthy();
  expect(A.visualizeRoles(new Role())).toBeTruthy();

  //verify that the permissions are correct
  expect(A.isAllowed('jedi',        'light-sabre')).toBe(true);
  expect(A.isDenied('jedi',         'laser-gun')).toBe(true);
  expect(A.isAllowed('luke',        'laser-gun')).toBe(true);
  expect(A.isAllowed('sith',        'laser-gun')).toBe(true);
  expect(A.isDenied('jedi',         't')).toBe(true);

  //change permission
  A.deny('sith', 'laser-gun');
  //add resource, role and permission
  A.addResource('double', 'light-sabre');
  A.addRole('anakin', 'jedi');
  A.allow('jedi', 'double', 'UPDATE');

  //verify permissions are correct
  expect(A.isAllowed('jedi', 'double')).toBe(true); // True because UPDATE on double is redundant.
  expect(A.isAllowed('jedi', 'double', 'UPDATE')).toBe(true); // True because UPDATE on double is redundant.

  //change double to be not redundant
  A.deny('jedi', 'double', 'CREATE');

  expect(A.isAllowed('jedi', 'double')).toBe(false); // False because jedi::double DENY CREATE.
  expect(A.isAllowed('jedi', 'double', 'UPDATE')).toBe(true); // Still true.
  expect(A.isDenied('luke', 'double', 'CREATE')).toBe(true); // True because inherits jedi.
  expect(A.isDenied('sith', 'laser-gun')).toBe(true);
  expect(A.isDenied('jedi', 't')).toBe(true);

  resources = A.exportResources();
  roles = A.exportRoles();
  perms = A.exportPermissions();

  //verify that the maps are disconnected
  expect(Object.keys(newRes).length < Object.keys(resources).length); // Exported resources is unaffected
  expect(Object.keys(newRoles).length < Object.keys(roles).length); // Exported roles is unaffected
  expect(Object.keys(newPerms).length < Object.keys(perms).length); // Exported permissions is unaffected
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Daiquiri\ReservationBundle\Twig;

class UnserializeExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('unserialize', array($this, 'unserializeFilter')),
        );
    }

    public function unserializeFilter($str)
    {
        $unserialize  = unserialize($str);

        return $unserialize;
    }

    public function getName()
    {
        return 'unserialize_extension';
    }
}


text:
export PATH := node_modules/.bin:$(PATH)

npm:
	npm install

scrape:
	@babel-node index.js


text:
package eu.atos.sla.datamodel.bean;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;

import eu.atos.sla.datamodel.IBusinessValueList;
import eu.atos.sla.datamodel.ICompensation.IPenalty;
import eu.atos.sla.datamodel.IGuaranteeTerm;
import eu.atos.sla.datamodel.IPolicy;
import eu.atos.sla.datamodel.IViolation;

/**
 * A POJO Object that stores all the information from a GuaranteeTerm
 *
 */

@Entity
@Table(name = "guarantee_term")
@NamedQueries({ @NamedQuery(name = "GuaranteeTerm.findAll", query = "SELECT p FROM GuaranteeTerm p") })
public class GuaranteeTerm implements IGuaranteeTerm, Serializable {

    private static final long serialVersionUID = -8140757088864002129L;
    private Long id;
    private String name;
    private String serviceName;
    private String serviceScope;
    private String kpiName;
    private String serviceLevel;
    private List<IViolation> violations;
    private List<IPenalty> penalties;
    private List<IPolicy> policies;
    private GuaranteeTermStatusEnum status;
    private IBusinessValueList businessValueList;

    private Date lastSampledDate;
    private Integer  samplingPeriodFactor;

    public GuaranteeTerm() {

        this.status = GuaranteeTermStatusEnum.NON_DETERMINED;
    }

    @Override
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    @Column(name = "name")
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    @Column(name = "service_name")
    public String getServiceName() {
        return serviceName;
    }

    @Override
    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    @Override
    @Column(name = "service_scope")
    public String getServiceScope() {
        return serviceScope;
    }

    @Override
    public void setServiceScope(String serviceScope) {
        this.serviceScope = serviceScope;
    }

    @Override
    @Column(name = "kpi_name")
    public String getKpiName() {
        return kpiName;
    }

    @Override
    public void setKpiName(String kpiName) {
        this.kpiName = kpiName;
    }

    @Override
    @Column(name = "service_level")
    public String getServiceLevel() {
        return serviceLevel;
    }

    @Override
    public void setServiceLevel(String serviceLevel) {
        this.serviceLevel = serviceLevel;
    }

    @Override
    @Fetch(org.hibernate.annotations.FetchMode.SUBSELECT)
    @OneToMany(targetEntity = Policy.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "guarantee_term_id", referencedColumnName = "id", nullable = true)
    public List<IPolicy> getPolicies() {
        return policies;
    }

    @Override
    public void setPolicies(List<IPolicy> policies) {
        this.policies = policies;
    }

    @Override
    @Fetch(org.hibernate.annotations.FetchMode.SUBSELECT)
    @OneToMany(targetEntity = Violation.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "guarantee_term_id", referencedColumnName = "id", nullable = true)
    public List<IViolation> getViolations() {
        return violations;
    }

    @Override
    public void setViolations(List<IViolation> violations) {
        this.violations = violations;
    }

    @Override
    @Fetch(org.hibernate.annotations.FetchMode.SUBSELECT)
    @OneToMany(targetEntity = Penalty.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "guarantee_term_id", referencedColumnName = "id", nullable = true)
    public List<IPenalty> getPenalties() {
        return penalties;
    }

    public void setPenalties(List<IPenalty> penalties) {
        this.penalties = penalties;
    }

    @Override
    @Column(name = "status", nullable = false)
    public GuaranteeTermStatusEnum getStatus() {
        return status;
    }

    @Override
    public void setStatus(GuaranteeTermStatusEnum status) {
        this.status = status;
    }

    @Override
    @OneToOne(targetEntity = BusinessValueList.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "business_value_id")
    public IBusinessValueList getBusinessValueList() {
        return businessValueList;
    }

    @Override
    public void setBusinessValueList(IBusinessValueList businessValueList) {
        this.businessValueList = businessValueList;
    }

    @Override
    @Column(name = "lastSampledDate", nullable = true)
    public Date getLastSampledDate() {
        return lastSampledDate;
    }

    @Override
    public void setLastSampledDate(Date lastSampledDate) {
        this.lastSampledDate = lastSampledDate;
    }

    @Override
    @Column(name = "samplingPeriodFactor", nullable = true)
    public Integer getSamplingPeriodFactor() {
        return samplingPeriodFactor;
    }

    @Override
    public void setSamplingPeriodFactor(Integer samplingPeriodFactor) {
        this.samplingPeriodFactor = samplingPeriodFactor;
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.4/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 1.47 $"/>
		<generation date="$Date: 2006/06/28 01:23:33 $"/>
		<language type="mr"/>
		<territory type="IN"/>
	</identity>
	<delimiters>
		<quotationStart>'</quotationStart>
		<quotationEnd>'</quotationEnd>
		<alternateQuotationStart>"</alternateQuotationStart>
		<alternateQuotationEnd>"</alternateQuotationEnd>
	</delimiters>
	<dates>
		<calendars>
			<calendar type="gregorian">
				<dateFormats>
					<dateFormatLength type="full">
						<dateFormat>
							<pattern>EEEE d MMMM yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="long">
						<dateFormat>
							<pattern>d MMMM yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="medium">
						<dateFormat>
							<pattern>dd-MM-yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="short">
						<dateFormat>
							<pattern>d-M-yy</pattern>
						</dateFormat>
					</dateFormatLength>
				</dateFormats>
				<timeFormats>
					<timeFormatLength type="full">
						<timeFormat>
							<pattern>h:mm:ss a z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="long">
						<timeFormat>
							<pattern>h:mm:ss a z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="medium">
						<timeFormat>
							<pattern>h:mm:ss a</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="short">
						<timeFormat>
							<pattern>h:mm a</pattern>
						</timeFormat>
					</timeFormatLength>
				</timeFormats>
				<dateTimeFormats>
					<availableFormats>
						<dateFormatItem id="MMMMd" draft="provisional">d MMMM</dateFormatItem>
						<dateFormatItem id="MMdd" draft="provisional">dd-MM</dateFormatItem>
						<dateFormatItem id="yyyyMM" draft="provisional">MM-yyyy</dateFormatItem>
						<dateFormatItem id="yyyyMMMM" draft="provisional">MMMM yyyy</dateFormatItem>
					</availableFormats>
				</dateTimeFormats>
			</calendar>
		</calendars>
	</dates>
	<numbers>
		<decimalFormats>
			<decimalFormatLength>
				<decimalFormat>
					<pattern>#,##,##0.###</pattern>
				</decimalFormat>
			</decimalFormatLength>
		</decimalFormats>
		<percentFormats>
			<percentFormatLength>
				<percentFormat>
					<pattern>#,##,##0%</pattern>
				</percentFormat>
			</percentFormatLength>
		</percentFormats>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>¤ #,##,##0.00</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
	</numbers>
</ldml>


text:
---
module: drag
maintainer: Marco Asbreuk
title: Moving multiple items
intro: "Multiple items can be dragged at once by specifying e.relatives inside a before-subscriber to the dd-start event."
---

Drag the items to the dropzones. Use the Ctrl/Cmd button to select multiple items.

drag me nr. 1

drag me nr. 2

drag me nr. 3

drag me nr. 4

drag me nr. 5

Code-example:

```css
<style type="text/css">
    .container.selected {
        border-color: #AAA;
    }

    /* give delegated items the same CSS as [draggable]: */
    .container {
        -moz-user-select: none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        user-select: none;
        float: left;
        position: relative;
    }
</style>
```

```html
<body>
    <div class="base-container" plugin-dd="true" dd-draggable=".container">
        <div class="container">drag me nr. 1</div>
        <div class="container">drag me nr. 2</div>
        <div class="container">drag me nr. 3</div>
        <div class="container">drag me nr. 4</div>
        <div class="container">drag me nr. 5</div>
    </div>
</body>
```

```js
<script src="itsabuild-min.js"></script>
<script>
    ITSA.Event.before('mousedown', function(e) {
        var ctrlPressed = e.ctrlKey || e.metaKey;
        if (!ctrlPressed) {
            document.getAll('.selected').removeClass('selected');
        }
        e.target.toggleClass('selected');
    }, '.container');

    ITSA.Event.before('mousedownoutside', function(e) {
        document.getAll('.selected').removeClass('selected');
    }, '.container');

    ITSA.Event.before('dd', function(e) {
        e.relatives = document.getAll('.selected');
    });
</script>
```


text:
/// 2009 March: btGeneric6DofConstraint refactored by Roman Ponomarev
/// Added support for generic constraint solver through getInfo1/getInfo2 methods

/*
2007-09-09
btGeneric6DofConstraint Refactored by Francisco Le?n
email: projectileman@yahoo.com
http://gimpact.sf.net
*/

#ifndef BT_GENERIC_6DOF_CONSTRAINT_H
#define BT_GENERIC_6DOF_CONSTRAINT_H

#include "LinearMath/btVector3.h"
#include "btJacobianEntry.h"
#include "btTypedConstraint.h"

class btRigidBody;

//! Rotation Limit structure for generic joints
class btRotationalLimitMotor
{
public:
    //! limit_parameters
    //!@{
    btScalar m_loLimit;//!< joint limit
    btScalar m_hiLimit;//!< joint limit
    btScalar m_targetVelocity;//!< target motor velocity
    btScalar m_maxMotorForce;//!< max force on motor
    btScalar m_maxLimitForce;//!< max force on limit
    btScalar m_damping;//!< Damping.
    btScalar m_limitSoftness;//! Relaxation factor
    btScalar m_normalCFM;//!< Constraint force mixing factor
    btScalar m_stopERP;//!< Error tolerance factor when joint is at limit
    btScalar m_stopCFM;//!< Constraint force mixing factor when joint is at limit
    btScalar m_bounce;//!< restitution factor
    bool m_enableMotor;

    //!@}

    //! temp_variables
    //!@{
    btScalar m_currentLimitError;//!  How much is violated this limit
    btScalar m_currentPosition;     //!  current value of angle
    int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit
    btScalar m_accumulatedImpulse;
    //!@}

    btRotationalLimitMotor()
    {
    	m_accumulatedImpulse = 0.f;
        m_targetVelocity = 0;
        m_maxMotorForce = 0.1f;
        m_maxLimitForce = 300.0f;
        m_loLimit = 1.0f;
        m_hiLimit = -1.0f;
		m_normalCFM = 0.f;
		m_stopERP = 0.2f;
		m_stopCFM = 0.f;
        m_bounce = 0.0f;
        m_damping = 1.0f;
        m_limitSoftness = 0.5f;
        m_currentLimit = 0;
        m_currentLimitError = 0;
        m_enableMotor = false;
    }

    btRotationalLimitMotor(const btRotationalLimitMotor & limot)
    {
        m_targetVelocity = limot.m_targetVelocity;
        m_maxMotorForce = limot.m_maxMotorForce;
        m_limitSoftness = limot.m_limitSoftness;
        m_loLimit = limot.m_loLimit;
        m_hiLimit = limot.m_hiLimit;
		m_normalCFM = limot.m_normalCFM;
		m_stopERP = limot.m_stopERP;
		m_stopCFM =	limot.m_stopCFM;
        m_bounce = limot.m_bounce;
        m_currentLimit = limot.m_currentLimit;
        m_currentLimitError = limot.m_currentLimitError;
        m_enableMotor = limot.m_enableMotor;
    }

	//! Is limited
    bool isLimited()
    {
    	if(m_loLimit > m_hiLimit) return false;
    	return true;
    }

	//! Need apply correction
    bool needApplyTorques()
    {
    	if(m_currentLimit == 0 && m_enableMotor == false) return false;
    	return true;
    }

	//! calculates  error
	/*!
	calculates m_currentLimit and m_currentLimitError.
	*/
	int testLimitValue(btScalar test_value);

	//! apply the correction impulses for two bodies
    btScalar solveAngularLimits(btScalar timeStep,btVector3& axis, btScalar jacDiagABInv,btRigidBody * body0, btRigidBody * body1);

};

class btTranslationalLimitMotor
{
public:
	btVector3 m_lowerLimit;//!< the constraint lower limits
    btVector3 m_upperLimit;//!< the constraint upper limits
    btVector3 m_accumulatedImpulse;
    //! Linear_Limit_parameters
    //!@{
    btScalar	m_limitSoftness;//!< Softness for linear limit
    btScalar	m_damping;//!< Damping for linear limit
    btScalar	m_restitution;//! Bounce parameter for linear limit
	btVector3	m_normalCFM;//!< Constraint force mixing factor
    btVector3	m_stopERP;//!< Error tolerance factor when joint is at limit
	btVector3	m_stopCFM;//!< Constraint force mixing factor when joint is at limit
    //!@}
	bool		m_enableMotor[3];
    btVector3	m_targetVelocity;//!< target motor velocity
    btVector3	m_maxMotorForce;//!< max force on motor
    btVector3	m_currentLimitError;//!  How much is violated this limit
    btVector3	m_currentLinearDiff;//!  Current relative offset of constraint frames
    int			m_currentLimit[3];//!< 0=free, 1=at lower limit, 2=at upper limit

    btTranslationalLimitMotor()
    {
    	m_lowerLimit.setValue(0.f,0.f,0.f);
    	m_upperLimit.setValue(0.f,0.f,0.f);
    	m_accumulatedImpulse.setValue(0.f,0.f,0.f);
		m_normalCFM.setValue(0.f, 0.f, 0.f);
		m_stopERP.setValue(0.2f, 0.2f, 0.2f);
		m_stopCFM.setValue(0.f, 0.f, 0.f);

    	m_limitSoftness = 0.7f;
    	m_damping = btScalar(1.0f);
    	m_restitution = btScalar(0.5f);
		for(int i=0; i < 3; i++)
		{
			m_enableMotor[i] = false;
			m_targetVelocity[i] = btScalar(0.f);
			m_maxMotorForce[i] = btScalar(0.f);
		}
    }

    btTranslationalLimitMotor(const btTranslationalLimitMotor & other )
    {
    	m_lowerLimit = other.m_lowerLimit;
    	m_upperLimit = other.m_upperLimit;
    	m_accumulatedImpulse = other.m_accumulatedImpulse;

    	m_limitSoftness = other.m_limitSoftness ;
    	m_damping = other.m_damping;
    	m_restitution = other.m_restitution;
		m_normalCFM = other.m_normalCFM;
		m_stopERP = other.m_stopERP;
		m_stopCFM = other.m_stopCFM;

		for(int i=0; i < 3; i++)
		{
			m_enableMotor[i] = other.m_enableMotor[i];
			m_targetVelocity[i] = other.m_targetVelocity[i];
			m_maxMotorForce[i] = other.m_maxMotorForce[i];
		}
    }

    //! Test limit
	/*!
    - free means upper < lower,
    - locked means upper == lower
    - limited means upper > lower
    - limitIndex: first 3 are linear, next 3 are angular
    */
    inline bool	isLimited(int limitIndex)
    {
       return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]);
    }
    inline bool needApplyForce(int limitIndex)
    {
    	if(m_currentLimit[limitIndex] == 0 && m_enableMotor[limitIndex] == false) return false;
    	return true;
    }
	int testLimitValue(int limitIndex, btScalar test_value);

    btScalar solveLinearAxis(
    	btScalar timeStep,
        btScalar jacDiagABInv,
        btRigidBody& body1,const btVector3 &pointInA,
        btRigidBody& body2,const btVector3 &pointInB,
        int limit_index,
        const btVector3 & axis_normal_on_a,
		const btVector3 & anchorPos);

};

enum bt6DofFlags
{
	BT_6DOF_FLAGS_CFM_NORM = 1,
	BT_6DOF_FLAGS_CFM_STOP = 2,
	BT_6DOF_FLAGS_ERP_STOP = 4
};
#define BT_6DOF_FLAGS_AXIS_SHIFT 3 // bits per axis

/// btGeneric6DofConstraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space
/*!
btGeneric6DofConstraint can leave any of the 6 degree of freedom 'free' or 'locked'.
currently this limit supports rotational motors

 For Linear limits, use btGeneric6DofConstraint.setLinearUpperLimit, btGeneric6DofConstraint.setLinearLowerLimit. You can set the parameters with the btTranslationalLimitMotor structure accsesible through the btGeneric6DofConstraint.getTranslationalLimitMotor method.
At this moment translational motors are not supported. May be in the future.

 For Angular limits, use the btRotationalLimitMotor structure for configuring the limit.
This is accessible through btGeneric6DofConstraint.getLimitMotor method,
This brings support for limit parameters and motors.

 Angulars limits have these possible ranges:

	AXIS
	MIN ANGLE
	MAX ANGLE

	X
	-PI
	PI

	Y
	-PI/2
	PI/2

	Z
	-PI
	PI

*/
class btGeneric6DofConstraint : public btTypedConstraint
{
protected:

	//! relative_frames
    //!@{
	btTransform	m_frameInA;//!< the constraint space w.r.t body A
    btTransform	m_frameInB;//!< the constraint space w.r.t body B
    //!@}

    //! Jacobians
    //!@{
    btJacobianEntry	m_jacLinear[3];//!< 3 orthogonal linear constraints
    btJacobianEntry	m_jacAng[3];//!< 3 orthogonal angular constraints
    //!@}

	//! Linear_Limit_parameters
    //!@{
    btTranslationalLimitMotor m_linearLimits;
    //!@}

    //! hinge_parameters
    //!@{
    btRotationalLimitMotor m_angularLimits[3];
	//!@}

protected:
    //! temporal variables
    //!@{
    btScalar m_timeStep;
    btTransform m_calculatedTransformA;
    btTransform m_calculatedTransformB;
    btVector3 m_calculatedAxisAngleDiff;
    btVector3 m_calculatedAxis[3];
    btVector3 m_calculatedLinearDiff;
	btScalar	m_factA;
	btScalar	m_factB;
	bool		m_hasStaticBody;

	btVector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes

    bool	m_useLinearReferenceFrameA;
	bool	m_useOffsetForConstraintFrame;

	int		m_flags;

    //!@}

    btGeneric6DofConstraint&	operator=(btGeneric6DofConstraint&	other)
    {
        btAssert(0);
        (void) other;
        return *this;
    }

	int setAngularLimits(btConstraintInfo2 *info, int row_offset,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);

	int setLinearLimits(btConstraintInfo2 *info, int row, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);

    void buildLinearJacobian(
        btJacobianEntry & jacLinear,const btVector3 & normalWorld,
        const btVector3 & pivotAInW,const btVector3 & pivotBInW);

    void buildAngularJacobian(btJacobianEntry & jacAngular,const btVector3 & jointAxisW);

	// tests linear limits
	void calculateLinearInfo();

	//! calcs the euler angles between the two bodies.
    void calculateAngleInfo();

public:

	///for backwards compatibility during the transition to 'getInfo/getInfo2'
	bool		m_useSolveConstraintObsolete;

    btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
    btGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB);

	//! Calcs global transform of the offsets
	/*!
	Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies.
	\sa btGeneric6DofConstraint.getCalculatedTransformA , btGeneric6DofConstraint.getCalculatedTransformB, btGeneric6DofConstraint.calculateAngleInfo
	*/
    void calculateTransforms(const btTransform& transA,const btTransform& transB);

	void calculateTransforms();

	//! Gets the global transform of the offset for body A
    /*!
    \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo.
    */
    const btTransform & getCalculatedTransformA() const
    {
    	return m_calculatedTransformA;
    }

    //! Gets the global transform of the offset for body B
    /*!
    \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo.
    */
    const btTransform & getCalculatedTransformB() const
    {
    	return m_calculatedTransformB;
    }

    const btTransform & getFrameOffsetA() const
    {
    	return m_frameInA;
    }

    const btTransform & getFrameOffsetB() const
    {
    	return m_frameInB;
    }

    btTransform & getFrameOffsetA()
    {
    	return m_frameInA;
    }

    btTransform & getFrameOffsetB()
    {
    	return m_frameInB;
    }

	//! performs Jacobian calculation, and also calculates angle differences and axis
    virtual void	buildJacobian();

	virtual void getInfo1 (btConstraintInfo1* info);

	void getInfo1NonVirtual (btConstraintInfo1* info);

	virtual void getInfo2 (btConstraintInfo2* info);

	void getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);

    void	updateRHS(btScalar	timeStep);

	//! Get the rotation axis in global coordinates
	/*!
	\pre btGeneric6DofConstraint.buildJacobian must be called previously.
	*/
    btVector3 getAxis(int axis_index) const;

    //! Get the relative Euler angle
    /*!
	\pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
	*/
    btScalar getAngle(int axis_index) const;

	//! Get the relative position of the constraint pivot
    /*!
	\pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
	*/
	btScalar getRelativePivotPosition(int axis_index) const;

	void setFrames(const btTransform & frameA, const btTransform & frameB);

	//! Test angular limit.
	/*!
	Calculates angular correction and returns true if limit needs to be corrected.
	\pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
	*/
    bool testAngularLimitMotor(int axis_index);

    void	setLinearLowerLimit(const btVector3& linearLower)
    {
    	m_linearLimits.m_lowerLimit = linearLower;
    }

	void	getLinearLowerLimit(btVector3& linearLower)
	{
		linearLower = m_linearLimits.m_lowerLimit;
	}

	void	setLinearUpperLimit(const btVector3& linearUpper)
	{
		m_linearLimits.m_upperLimit = linearUpper;
	}

	void	getLinearUpperLimit(btVector3& linearUpper)
	{
		linearUpper = m_linearLimits.m_upperLimit;
	}

    void	setAngularLowerLimit(const btVector3& angularLower)
    {
		for(int i = 0; i < 3; i++)
			m_angularLimits[i].m_loLimit = btNormalizeAngle(angularLower[i]);
    }

	void	getAngularLowerLimit(btVector3& angularLower)
	{
		for(int i = 0; i < 3; i++)
			angularLower[i] = m_angularLimits[i].m_loLimit;
	}

    void	setAngularUpperLimit(const btVector3& angularUpper)
    {
		for(int i = 0; i < 3; i++)
			m_angularLimits[i].m_hiLimit = btNormalizeAngle(angularUpper[i]);
    }

	void	getAngularUpperLimit(btVector3& angularUpper)
	{
		for(int i = 0; i < 3; i++)
			angularUpper[i] = m_angularLimits[i].m_hiLimit;
	}

	//! Retrieves the angular limit informacion
    btRotationalLimitMotor * getRotationalLimitMotor(int index)
    {
    	return &m_angularLimits[index];
    }

    //! Retrieves the  limit informacion
    btTranslationalLimitMotor * getTranslationalLimitMotor()
    {
    	return &m_linearLimits;
    }

    //first 3 are linear, next 3 are angular
    void setLimit(int axis, btScalar lo, btScalar hi)
    {
    	if(axis<3)
    	{
    		m_linearLimits.m_lowerLimit[axis] = lo;
    		m_linearLimits.m_upperLimit[axis] = hi;
    	}
    	else
    	{
			lo = btNormalizeAngle(lo);
			hi = btNormalizeAngle(hi);
    		m_angularLimits[axis-3].m_loLimit = lo;
    		m_angularLimits[axis-3].m_hiLimit = hi;
    	}
    }

	//! Test limit
	/*!
    - free means upper < lower,
    - locked means upper == lower
    - limited means upper > lower
    - limitIndex: first 3 are linear, next 3 are angular
    */
    bool	isLimited(int limitIndex)
    {
    	if(limitIndex<3)
    	{
			return m_linearLimits.isLimited(limitIndex);

    	}
        return m_angularLimits[limitIndex-3].isLimited();
    }

	virtual void calcAnchorPos(void); // overridable

	int get_limit_motor_info2(	btRotationalLimitMotor * limot,
								const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB,
								btConstraintInfo2 *info, int row, btVector3& ax1, int rotational, int rotAllowed = false);

	// access for UseFrameOffset
	bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; }
	void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; }

	///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
	///If no axis is provided, it uses the default axis for this constraint.
	virtual	void setParam(int num, btScalar value, int axis = -1);
	///return the local value of parameter
	virtual	btScalar getParam(int num, int axis = -1) const;

	void setAxis( const btVector3& axis1, const btVector3& axis2);

	virtual	int	calculateSerializeBufferSize() const;

	///fills the dataBuffer and returns the struct name (and 0 on failure)
	virtual	const char*	serialize(void* dataBuffer, btSerializer* serializer) const;

};

///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btGeneric6DofConstraintData
{
	btTypedConstraintData	m_typeConstraintData;
	btTransformFloatData m_rbAFrame; // constraint axii. Assumes z is hinge axis.
	btTransformFloatData m_rbBFrame;

	btVector3FloatData	m_linearUpperLimit;
	btVector3FloatData	m_linearLowerLimit;

	btVector3FloatData	m_angularUpperLimit;
	btVector3FloatData	m_angularLowerLimit;

	int	m_useLinearReferenceFrameA;
	int m_useOffsetForConstraintFrame;
};

SIMD_FORCE_INLINE	int	btGeneric6DofConstraint::calculateSerializeBufferSize() const
{
	return sizeof(btGeneric6DofConstraintData);
}

	///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE	const char*	btGeneric6DofConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
{

	btGeneric6DofConstraintData* dof = (btGeneric6DofConstraintData*)dataBuffer;
	btTypedConstraint::serialize(&dof->m_typeConstraintData,serializer);

	m_frameInA.serializeFloat(dof->m_rbAFrame);
	m_frameInB.serializeFloat(dof->m_rbBFrame);

	int i;
	for (i=0;i<3;i++)
	{
		dof->m_angularLowerLimit.m_floats[i] =  float(m_angularLimits[i].m_loLimit);
		dof->m_angularUpperLimit.m_floats[i] =  float(m_angularLimits[i].m_hiLimit);
		dof->m_linearLowerLimit.m_floats[i] = float(m_linearLimits.m_lowerLimit[i]);
		dof->m_linearUpperLimit.m_floats[i] = float(m_linearLimits.m_upperLimit[i]);
	}

	dof->m_useLinearReferenceFrameA = m_useLinearReferenceFrameA? 1 : 0;
	dof->m_useOffsetForConstraintFrame = m_useOffsetForConstraintFrame ? 1 : 0;

	return "btGeneric6DofConstraintData";
}

#endif //BT_GENERIC_6DOF_CONSTRAINT_H


text:
id: 587d78b2367417b2b2512b0e
title: Aggiungere elementi ad un array con push() e unshift()
challengeType: 1
forumTopicId: 301151
dashedName: add-items-to-an-array-with-push-and-unshift
---

# --description--

La lunghezza di un array, così come i tipi di dati che può contenere, non è fissata. Gli array possono essere definiti con un numero qualsiasi di elementi, e gli elementi possono essere aggiunti o rimossi nel tempo; in altre parole, gli array sono <dfn>mutabili</dfn>. In questa sfida, esamineremo due metodi con cui possiamo modificare programmaticamente un array: `Array.push()` e `Array.unshift()`.

Entrambi i metodi prendono uno o più elementi come parametri e aggiungono questi elementi all'array su cui il metodo è stato chiamato; il metodo `push()` aggiunge elementi alla fine di un array, e `unshift()` aggiunge elementi all'inizio. Considera quanto segue:

```js
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];

romanNumerals.unshift('XIX', 'XX');
```

`romanNumerals` avrà i valori `['XIX', 'XX', 'XXI', 'XXII']`.

```js
romanNumerals.push(twentyThree);
```

`romanNumerals` avrà i valori `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Nota che possiamo anche passare variabili, il che ci permette una flessibilità ancora maggiore nel modificare dinamicamente i dati del nostro array.

# --instructions--

Abbiamo definito una funzione, `mixedNumbers`, a cui stiamo passando un array come argomento. Modifica la funzione usando `push()` e `unshift()` per aggiungere `'I', 2, 'three'` all'inizio dell'array e `7, 'VIII', 9` alla fine, in modo che l'array restituito contenga le rappresentazioni dei numeri da 1 a 9 in ordine.

# --hints--

`mixedNumbers(["IV", 5, "six"])` adesso dovrebbe restituire `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`

```js
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
  'I',
  2,
  'three',
  'IV',
  5,
  'six',
  7,
  'VIII',
  9
]);
```

La funzione `mixedNumbers` dovrebbe utilizzare il metodo `push()`

```js
assert(mixedNumbers.toString().match(/\.push/));
```

La funzione `mixedNumbers` dovrebbe utilizzare il metodo `unshift()`

```js
assert(mixedNumbers.toString().match(/\.unshift/));
```

# --seed--

## --seed-contents--

```js
function mixedNumbers(arr) {
  // Only change code below this line

  // Only change code above this line
  return arr;
}

console.log(mixedNumbers(['IV', 5, 'six']));
```

# --solutions--

```js
function mixedNumbers(arr) {
  arr.push(7,'VIII',9);
  arr.unshift('I',2,'three');
  return arr;
}
```


text:
import factory

from geotrek.common.utils.testdata import get_dummy_uploaded_image

from . import models

class DataSourceFactory(factory.Factory):
    FACTORY_FOR = models.DataSource

    title = factory.Sequence(lambda n: u"DataSource %s" % n)
    url = factory.Sequence(lambda n: u"http://%s.com" % n)
    type = models.DATA_SOURCE_TYPES.GEOJSON
    pictogram = get_dummy_uploaded_image()


text:
var api         = require('./api'),
    admin       = require('./admin'),
    frontend    = require('./frontend');

module.exports = {
    api: api,
    admin: admin,
    frontend: frontend
};


text:
#pragma once

#include "Element.h"

#include <list>

class CConfigurableDomain;
class CSyncerSet;
class ISyncer;
class CSubsystem;
class CConfigurationAccessContext;
class CParameterAccessContext;
class CAreaConfiguration;

class CConfigurableElement : public CElement
{
    friend class CConfigurableDomain;
    friend class CDomainConfiguration;
    typedef std::list<const CConfigurableDomain*>::const_iterator ConfigurableDomainListConstIterator;
public:
    CConfigurableElement(const std::string& strName = "");
    virtual ~CConfigurableElement();

    // Offset in main blackboard
    void setOffset(uint32_t uiOffset);
    uint32_t getOffset() const;

    // Allocation
    virtual uint32_t getFootPrint() const;

    // Syncer set (me, ascendant or descendant ones)
    void fillSyncerSet(CSyncerSet& syncerSet) const;

    // Belonging domain
    bool belongsTo(const CConfigurableDomain* pConfigurableDomain) const;

    // Belonging domains
    void listBelongingDomains(std::string& strResult, bool bVertical = true) const;

    // Matching check for domain association
    bool hasNoDomainAssociated() const;

    // Matching check for no valid associated domains
    bool hasNoValidDomainAssociated() const;

    // Owning domains
    void listAssociatedDomains(std::string& strResult, bool bVertical = true) const;
    uint32_t getBelongingDomainCount() const;

    // Elements with no domains
    void listRogueElements(std::string& strResult) const;

    // Belonging to no domains
    bool isRogue() const;

    // Footprint as string
    std::string getFootprintAsString() const;

    // Belonging subsystem
    virtual const CSubsystem* getBelongingSubsystem() const;

    // Check element is a parameter
    virtual bool isParameter() const;

    // AreaConfiguration creation
    virtual CAreaConfiguration* createAreaConfiguration(const CSyncerSet* pSyncerSet) const;

    // Parameter access
    virtual bool accessValue(CPathNavigator& pathNavigator, std::string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const;

    /**
     * Get the list of all the ancestors that have a mapping.
     *
     * The mapping is represented as a std::string of all the mapping data (key:value) defined in the
     * context of the element.
     * In this class, the method is generic and calls its parent getListOfElementsWithMappings(...)
     * method.
     *
     * @param[in:out] configurableElementPath List of all the ConfigurableElements found
     * that have a mapping. Elements are added at the end of the list, so the root Element will be
     * the last one.
     *
     */
    virtual void getListOfElementsWithMapping(std::list<const CConfigurableElement*>&
                                               configurableElementPath) const;

    // Used for simulation and virtual subsystems
    virtual void setDefaultValues(CParameterAccessContext& parameterAccessContext) const;

    // Element properties
    virtual void showProperties(std::string& strResult) const;

    // XML configuration settings parsing
    virtual bool serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const;
protected:
    // Syncer (me or ascendant)
    virtual ISyncer* getSyncer() const;
    // Syncer set (descendant)
    virtual void fillSyncerSetFromDescendant(CSyncerSet& syncerSet) const;
    // Configuration Domain local search
    bool containsConfigurableDomain(const CConfigurableDomain* pConfigurableDomain) const;

private:
    // Configurable domain association
    void addAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain);
    void removeAttachedConfigurableDomain(const CConfigurableDomain* pConfigurableDomain);

    // Belonging domain ascending search
    bool belongsToDomainAscending(const CConfigurableDomain* pConfigurableDomain) const;

    // Belonging domains
    void getBelongingDomains(std::list<const CConfigurableDomain*>& configurableDomainList) const;
    void listDomains(const std::list<const CConfigurableDomain*>& configurableDomainList, std::string& strResult, bool bVertical) const;

    // Check parent is still of current type (by structure knowledge)
    bool isOfConfigurableElementType(const CElement* pParent) const;

    // Offset in main blackboard
    uint32_t _uiOffset;

    // Associated configurable domains
    std::list<const CConfigurableDomain*> _configurableDomainList;
};


text:
#ifndef nativeDiag_h
#define nativeDiag_h

#include <stdio.h>
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <assert.h>

#ifdef __cplusplus
extern "C" {
#endif

    //
    // Basic memory diagnostic informations, suchs as the virtual memory
    // and the residental memory size
    //
    struct memory_diagnostic_info {
        unsigned long long vs;      // Virtual Memory Size
        unsigned long long rss;     // Residental Memory Size
    };
    typedef struct memory_diagnostic_info memory_diagnostic_info_t;
    typedef struct memory_diagnostic_info *p_memory_diagnostic_info_t;

    //
    // Extended memory information, including the virual as well as the residental
    // memory size as well but also including some more values regarding peak
    // memory behaviors
    //
    struct memory_extended_diagnostic_info {
        unsigned long long vs;
        unsigned long long rss;
        unsigned long long rss_peak;
    };
    typedef struct memory_extended_diagnostic_info memory_extended_diagnostic_info_t;
    typedef struct memory_extended_diagnostic_info *p_memory_extended_diagnostic_info_t;

    //
    // Structure to hold all native diagnostics that can possibly be retrieved
    //
    struct native_diagnostic_info {
        float cpuusage;
        union {
            memory_diagnostic_info_t memory_info;
            memory_extended_diagnostic_info_t memory_extended_info;
        } memory;
    };
    typedef struct native_diagnostic_info native_diagnostic_info_t;
    typedef struct native_diagnostic_info *p_native_diagnostic_info_t;

    /**
     * Get the CPU Usage for the executing task and all of the tasks threads
     * Each of the devices cores can reach 100% cpu usage, this function will
     * return the sum of the cpu usage of all the cores.
     *
     * @param usage cpu usage in percent
     * @return 0 iff successful, error value otherwise
     */
    int getCPULoad(float *usage);

    /**
     * Get the memory usage for the executing task (the running app itself)
     *
     * @param memory_diag_info pointer to structure to hold information about residental and virtual memory size
     * @return 0 iff requesting the used memory succeeded, error value otherwise
     */
    int getMemoryUsage(memory_diagnostic_info_t *memory_diag_info);

    /**
     * Get extended memory usage diagnostics    for the executing task (the running app itself)
     *
     * @param memory_diag_info pointer to structure to hold information about residental and virtual memory size and peak sizes
     * @return 0 iff requesting the used memory succeeded, error value otherwise
     */
    int getMemoryInformation(memory_extended_diagnostic_info_t *memory_diag_info);

    /**
     * Get the total bytes of residental memory usage on the device
     *
     * @return the resident memory usage in bytes, a negative value if an error occured
     */
    long long getResidentMemory();

	/**
	 * Get the free memory on the device
	 *
	 * @return the free memory in bytes, a negative value if an error occured
	 */
	long long getFreeMemory();

	/**
	 * Get the total used memory by all apps and the os on the device
	 *
	 * @return the total used memory in bytes, a negative value if an error occured
	 */
	long long getTotalUsedMemory();

	/**
	 * Get the active memory on the device
	 *
	 * @return the active memory in bytes, a negative value if an error occured
	 */
	long long getActiveMemory();

	/**
	 * Get the wired memory on the device
	 *
	 * @return the wired memory in bytes, a negative value if an error occured
	 */
	long long getWiredMemory();

	/**
	 * Get the inactive memory on the device
	 *
	 * @return the inactive memory in bytes, a negative value if an error occured
	 */
	long long getInactiveMemory();

#ifdef __cplusplus
}
#endif

#endif /* nativeDiag_h */


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>loglink1.1</title>
	<link rel="stylesheet" type="text/css" href="css/loglink1.1.css" />

Retour

Semantic Nodes

		<button id="initKernelGraph" title="Initialization">0</button>
		<button id="refreshGraph" title="Refresh">!</button>

	ABOUT : loglink1.1 (Beta)

	HELP :

	To add new node, drag existing node

	You can add a link between two nodes

	You can initialize the graph with two nodes [0]

	You can refresh the graph [!]

	You can pan & zoom

	Admin /
	Debug /
	Wiki /
    Contact.


text:
#ifndef MUTEXDIRECT_H
#define MUTEXDIRECT_H

#include "pandabase.h"
#include "mutexTrueImpl.h"
#include "pnotify.h"

class Thread;

#ifndef DEBUG_THREADS

/**
 * This class implements a standard mutex by making direct calls to the
 * underlying implementation layer.  It doesn't perform any debugging
 * operations.
 */
class EXPCL_PANDA_PIPELINE MutexDirect {
protected:
  MutexDirect() = default;
  MutexDirect(const MutexDirect &copy) = delete;
  ~MutexDirect() = default;

  void operator = (const MutexDirect &copy) = delete;

public:
  INLINE void lock();
  INLINE bool try_lock();
  INLINE void unlock();

PUBLISHED:
  BLOCKING INLINE void acquire() const;
  BLOCKING INLINE bool try_acquire() const;
  INLINE void release() const;
  INLINE bool debug_is_locked() const;

  INLINE void set_name(const std::string &name);
  INLINE void clear_name();
  INLINE bool has_name() const;
  INLINE std::string get_name() const;

  void output(std::ostream &out) const;

private:
  mutable MutexTrueImpl _impl;

  friend class ConditionVarDirect;
  friend class ConditionVarFullDirect;
};

INLINE std::ostream &
operator << (std::ostream &out, const MutexDirect &m) {
  m.output(out);
  return out;
}

#include "mutexDirect.I"

#endif  // !DEBUG_THREADS

#endif


text:
void guessing();
bool isWon(int guess, int secret);
std::string processInequality(int guess, int secret);
int processMax(int guess, int rangeMax, int rangeMin, int secret);
int processMin(int guess, int rangeMax, int rangeMin, int secret);
int processClosest(int guess, int closest, int secret);
int processDifference(int guess, int secret);
#endif


text:
#include "CountryCodeStringTable.h"

bool
CountryCodeStringTable::streetNumberFirst(StringTable::countryCode cc,
                                          LangTypes::language_t lang)
{
   init();

   if ( lang != LangTypes::invalidLanguage ) {
      return m_streetNumberFirstLanguage.count( lang ) > 0;
   }
   else {
      return m_streetNumberFirstCountry.count( cc ) > 0;
   }
}

bool
CountryCodeStringTable::streetNumberComma(StringTable::countryCode cc,
                                          LangTypes::language_t lang)
{
   init();

   return m_streetNumberCommaLanguage.count( lang ) > 0;
}

bool CountryCodeStringTable::m_initiated = false;
set<StringTable::countryCode> CountryCodeStringTable::m_streetNumberFirstCountry;
set<StringTable::countryCode> CountryCodeStringTable::m_streetNumberCommaCountry;
set<LangTypes::language_t> CountryCodeStringTable::m_streetNumberFirstLanguage;
set<LangTypes::language_t> CountryCodeStringTable::m_streetNumberCommaLanguage;

void
CountryCodeStringTable::init()
{
   if (! m_initiated) {
      StringTable::countryCode ccarr[] = {
         StringTable::AUSTRALIA_CC,
         StringTable::CANADA_CC,
         StringTable::FRANCE_CC,
         StringTable::ENGLAND_CC,
         StringTable::HONG_KONG_CC,
         StringTable::ISRAEL_CC,
         StringTable::IRELAND_CC,
         StringTable::LUXEMBOURG_CC,
         StringTable::NEW_ZEALAND_CC,
         StringTable::CHINA_CC,
         StringTable::SOUTH_AFRICA_CC,
         StringTable::SOUTH_KOREA_CC,
         StringTable::TAIWAN_CC,
         StringTable::USA_CC,
         StringTable::SINGAPORE_CC,
         StringTable::INDIA_CC
      };

      int nbrCountries = sizeof( ccarr ) / sizeof( ccarr[0] );

      for ( int i = 0; i < nbrCountries; ++i ) {
         m_streetNumberFirstCountry.insert( ccarr[ i ] );
      }

      m_streetNumberFirstLanguage.insert(LangTypes::english);
      m_streetNumberFirstLanguage.insert(LangTypes::french);
   }
   m_initiated = true;
}


text:
"""
Handlers for keys related to number theory: prime, even, odd, etc.
"""
from __future__ import print_function, division

from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
from sympy.ntheory import isprime
from sympy.core import S

class AskPrimeHandler(CommonHandler):
    """
    Handler for key 'prime'
    Test that an expression represents a prime number. When the
    expression is a number the result, when True, is subject to
    the limitations of isprime() which is used to return the result.
    """

    @staticmethod
    def _number(expr, assumptions):
        # helper method
        try:
            i = int(expr.round())
            if not (expr - i).equals(0):
                raise TypeError
        except TypeError:
            return False
        return isprime(i)

    @staticmethod
    def Basic(expr, assumptions):
        # Just use int(expr) once
        # https://github.com/sympy/sympy/issues/4561
        # is solved
        if expr.is_number:
            return AskPrimeHandler._number(expr, assumptions)

    @staticmethod
    def Mul(expr, assumptions):
        if expr.is_number:
            return AskPrimeHandler._number(expr, assumptions)
        for arg in expr.args:
            if ask(Q.integer(arg), assumptions):
                pass
            else:
                break
        else:
            # a product of integers can't be a prime
            return False

    @staticmethod
    def Pow(expr, assumptions):
        """
        Integer**Integer     -> !Prime
        """
        if expr.is_number:
            return AskPrimeHandler._number(expr, assumptions)
        if ask(Q.integer(expr.exp), assumptions) and \
                ask(Q.integer(expr.base), assumptions):
            return False

    @staticmethod
    def Integer(expr, assumptions):
        return isprime(expr)

    Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4

    @staticmethod
    def Float(expr, assumptions):
        return AskPrimeHandler._number(expr, assumptions)

    @staticmethod
    def NumberSymbol(expr, assumptions):
        return AskPrimeHandler._number(expr, assumptions)

class AskCompositeHandler(CommonHandler):
    @staticmethod
    def Basic(expr, assumptions):
        _positive = ask(Q.positive(expr), assumptions)
        if _positive:
            _integer = ask(Q.integer(expr), assumptions)
            if _integer:
                _prime = ask(Q.prime(expr), assumptions)
                if _prime is None:
                    return
                return not _prime
            else:
                return _integer
        else:
            return _positive

class AskEvenHandler(CommonHandler):
    @staticmethod
    def _number(expr, assumptions):
        # helper method
        try:
            i = int(expr.round())
            if not (expr - i).equals(0):
                raise TypeError
        except TypeError:
            return False
        return i % 2 == 0

    @staticmethod
    def Basic(expr, assumptions):
        if expr.is_number:
            return AskEvenHandler._number(expr, assumptions)

    @staticmethod
    def Mul(expr, assumptions):
        """
        Even * Integer    -> Even
        Even * Odd        -> Even
        Integer * Odd     -> ?
        Odd * Odd         -> Odd
        Even * Even       -> Even
        Integer * Integer -> Even if Integer + Integer = Odd
                          -> ? otherwise
        """
        if expr.is_number:
            return AskEvenHandler._number(expr, assumptions)
        even, odd, irrational, acc = False, 0, False, 1
        for arg in expr.args:
            # check for all integers and at least one even
            if ask(Q.integer(arg), assumptions):
                if ask(Q.even(arg), assumptions):
                    even = True
                elif ask(Q.odd(arg), assumptions):
                    odd += 1
                elif not even and acc != 1:
                    if ask(Q.odd(acc + arg), assumptions):
                        even = True
            elif ask(Q.irrational(arg), assumptions):
                # one irrational makes the result False
                # two makes it undefined
                if irrational:
                    break
                irrational = True
            else:
                break
            acc = arg
        else:
            if irrational:
                return False
            if even:
                return True
            if odd == len(expr.args):
                return False

    @staticmethod
    def Add(expr, assumptions):
        """
        Even + Odd  -> Odd
        Even + Even -> Even
        Odd  + Odd  -> Even

        """
        if expr.is_number:
            return AskEvenHandler._number(expr, assumptions)
        _result = True
        for arg in expr.args:
            if ask(Q.even(arg), assumptions):
                pass
            elif ask(Q.odd(arg), assumptions):
                _result = not _result
            else:
                break
        else:
            return _result

    @staticmethod
    def Pow(expr, assumptions):
        if expr.is_number:
            return AskEvenHandler._number(expr, assumptions)
        if ask(Q.integer(expr.exp), assumptions):
            if ask(Q.positive(expr.exp), assumptions):
                return ask(Q.even(expr.base), assumptions)
            elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions):
                return False
            elif expr.base is S.NegativeOne:
                return False

    @staticmethod
    def Integer(expr, assumptions):
        return not bool(expr.p & 1)

    Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4

    @staticmethod
    def Float(expr, assumptions):
        return expr % 2 == 0

    @staticmethod
    def NumberSymbol(expr, assumptions):
        return AskEvenHandler._number(expr, assumptions)

    @staticmethod
    def Abs(expr, assumptions):
        if ask(Q.real(expr.args[0]), assumptions):
            return ask(Q.even(expr.args[0]), assumptions)

    @staticmethod
    def re(expr, assumptions):
        if ask(Q.real(expr.args[0]), assumptions):
            return ask(Q.even(expr.args[0]), assumptions)

    @staticmethod
    def im(expr, assumptions):
        if ask(Q.real(expr.args[0]), assumptions):
            return True

class AskOddHandler(CommonHandler):
    """
    Handler for key 'odd'
    Test that an expression represents an odd number
    """

    @staticmethod
    def Basic(expr, assumptions):
        _integer = ask(Q.integer(expr), assumptions)
        if _integer:
            _even = ask(Q.even(expr), assumptions)
            if _even is None:
                return None
            return not _even
        return _integer


text:
namespace SM2Core.Scenes {
	public class MarkerList {
		public Visualization.Marker Markers {
			get {
				throw new System.NotImplementedException();
			}

			set {
			}
		}
	}
}


text:
<?php

namespace AppBundle\Shell;

/**
 * Shell
 *
 * @author gbprod <contact@gb-prod.fr>
 */
class Shell
{
    /**
     * Execute the command
     *
     * @param string $command
     *
     * @return string execution trace
     */
    public function execute($command, $folder)
    {
        $previousFolder = getcwd();
        chdir($folder);
        $return = shell_exec($command);
        chdir($previousFolder);

        return $return;
    }
}


text:
id: 435
title: Join
date: 2014-08-11T10:01:59+00:00
author: James Wade
layout: page
guid: /?page_id=435
spacious_page_layout:
  - default_layout
---
Interested in becoming a member? You're in the right place!

Potteries Hackspace is a membership organisation (SIC 94990) and as such is funded in most part by membership subscriptions.

**Before you join**

The best way to get involved is to become part of our community online and join the discussions on our mailing list. We'd love to get to know you, so the easiest way to get started is by introducing yourself to us on the [Potteries Hackspace groups mailing list](https://groups.google.com/group/potteries-hackspace).

You can also come on down for one of our [Open Nights](/contact) or any of the other [events](/events) you see on our calendar.

If it's your first time, don't be shy, we're a friendly bunch, simply come along, say hello and introduce yourself.

**Benefits**

There are a number of benefits to becoming a member, they are:

  * Access to our private members only mailing list and resources
  * Vote at meetings or virtually
  * Storage space for your projects (35L box)*
  * Use of the Hackspace tools & equipment*
  * 24 hour access to the Hackspace*
  * WiFi Internet access*
  * Use of shared components, consumables, donated items including tea and coffee*
  * Access to special offers, discounts and cheap rates
  * Opportunity to attend and host workshops
  * Can attend the AGM and be elected on to the Management Committee
  * Guests are welcome

Note: Items marked with a star will depend on a physical space and are subject to availability, please check the mailing list for the current status and access.

**Membership Rules**

The membership rules and regulations differ from the the hackspace rules as all members are subject to certain rules and legal obligations.

  * Members are subject to the [Potteries Hackspace Constitution](https://docs.google.com/document/d/1n_r_CWQdehnsC863m5AqWtzrILA6IF8CT7PReLStWqw/pub).
  * All members must pay a membership fee each month in order to remain a voting member
  * You are required by law to provide your real name and address to become a member
  * Sorry, members cannot be under the age of 18, guests can but members must be responsible for their guests

**Membership Fees**

Potteries Hackspace is entirely funded by it's members and without you we wouldn't be able to make this happen.

Every month we need to pay bills, as well as raising funds for equipment and supplies. Our main source of income is membership fees.

We have a very simple policy for membership fees:

  * Members pay what they like for membership on a monthly basis.
  * If you are paying less than you are taking from the Hackspace you'll be politely asked to increase your monthly payments.

A subscription of £15 per month is recommended, a minimum of £5 per month is encouraged.

Become a member


text:
package poweraqua.fusion;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import poweraqua.core.model.myrdfmodel.RDFEntity;
import poweraqua.powermap.triplePhase.OntoTripleBean;
import poweraqua.powermap.triplePhase.TripleSimilarityService;
import poweraqua.ranking.SynsetClusterRanking;

public class RDFEntityClusterSynsetComparator
  implements Comparator<RDFEntityCluster>
{
  FusedAnswerBean fusedAnswerBean;

  public RDFEntityClusterSynsetComparator(FusedAnswerBean bean)
  {
    this.fusedAnswerBean = bean;
  }

  public int compare(RDFEntityCluster c1, RDFEntityCluster c2)
    throws ClassCastException
  {
    String[] tmp = new String[2];

    ArrayList<OntoTripleBean> beans = new ArrayList();
    for (RDFEntityEntry entry : c1.getEntries()) {
      beans.add(entry.getOntoTripleBean());
    }
    int r1 = this.fusedAnswerBean.getFusionService().getTripleSimilarityService().getSynsetClusterRanking().getSynsetPopularity(beans).intValue();
    c1.setRankingValue(r1);
    beans.clear();
    for (RDFEntityEntry entry : c2.getEntries()) {
      beans.add(entry.getOntoTripleBean());
    }
    int r2 = this.fusedAnswerBean.getFusionService().getTripleSimilarityService().getSynsetClusterRanking().getSynsetPopularity(beans).intValue();
    c2.setRankingValue(r2);
    if (r1 != r2) {
      return r2 - r1;
    }
    try
    {
      tmp[0] = ((RDFEntityEntry)c1.getEntries().get(0)).getValue().getLabel().toLowerCase();
      tmp[1] = ((RDFEntityEntry)c2.getEntries().get(0)).getValue().getLabel().toLowerCase();
      for (int i = 0; i < 2; i++) {
        while ((tmp[i].charAt(0) < 'a') || (tmp[i].charAt(0) > 'z')) {
          tmp[i] = tmp[i].substring(1);
        }
      }
      return tmp[0].compareToIgnoreCase(tmp[1]);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return 0;
  }
}


text:
var models = require('../server/models');
var Promise = require('bluebird');
var axios = require('axios');
var logger = require('debug')('textcapade');
var config = require('getconfig');

//look for messages ten times a second
exports.INTERVAL = 100;

var sendNextMessage = function (character) {

    models.Histories.query(function (qb) {

        qb.where({
            message_type: 'send',
            sent: false,
            from_phone: 'slack'
        })
        .whereNotNull('from_phone')
        .andWhere('time', '<=', Math.floor(Date.now() / 1000))
        .orderByRaw('time ASC, seq ASC, id ASC');
    }).fetchOne({ require: true }).then(function (history) {

        return history.related('user').fetch().then(function (user) {

            var payload = {
                to: user.get('slack_username'),
                from: history.get('from_character'),
                message: history.get('message')
            };
            logger('slack request %s %j', config.slack.apiUrl, payload);

            var opts = { headers: {} };
            //opts.headers.authorization = 'Basic ' + new Buffer(config.slack.username + ':' + config.slack.password).toString('base64');

            return axios.post(config.slack.apiUrl, payload, opts).then(function (response) {

                if (response.status >= 400) {
                    throw new Error('BadRequest: ' + response.status + ' ' + response.data);
                }
                logger('slack response %j', response);
                return response;
            }).then(function () {

                return history.save({
                    sent: true
                });
            }).then(function () {

                return user.attemptAdvance();
            });
        });
    }).catch(function (e) {

        if (e.message === 'EmptyResponse') {
            //logger('Nothing to send for slack');
        } else {
            throw e;
        }
    }).catch(function (e) {

        logger('Error sending messages for slack: %j', e);
    }).then(function () {

        setTimeout(sendNextMessage, exports.INTERVAL);

    });
};

logger('Starting slack worker');
sendNextMessage();


text:
<html>
    <head>
        <script data-main="Background" src="Shared/require.js"></script>
    </head>
    <body>
    </body>
</html>


text:
function removeElsWithClass(className)
{
    var els = document.querySelectorAll('.' + className);
    for (var i = 0; i < els.length; i++) {
        els[i].parentNode.removeChild(els[i]);
    }
}

function submitRecrasForm(formID, subdomain, basePath, redirect)
{
    removeElsWithClass('recras-error');

    var formEl = document.getElementById('recras-form' + formID);
    var formElements = formEl.querySelectorAll('input, textarea, select');
    var elements = {};
    for (var i = 0; i < formElements.length; i++) {
        if (formElements[i].type === 'submit') {
            continue;
        }
        if (formElements[i].value === '' && formElements[i].required === false) {
            formElements[i].value = null;
        }
        if (formElements[i].type === 'radio') {
            var selected = document.querySelector('input[name="' + formElements[i].name + '"]:checked');
            elements[formElements[i].name] = selected.value;
        } else if (formElements[i].type === 'checkbox') {
            elements[formElements[i].name] = [];
            var checked = document.querySelectorAll('input[name="' + formElements[i].name + '"]:checked');
            if (checked.length === 0) {
                var isRequired = document.querySelector('input[name="' + formElements[i].name + '"][data-required="1"]');
                if (isRequired) {
                    formEl
                        .querySelector('[name="' + formElements[i].name + '"]')
                        .parentNode
                        .insertAdjacentHTML('beforeend', '' + recras_l10n.checkboxRequired + '');
                    return false;
                }
            }
            for (var j = 0; j < checked.length; j++) {
                elements[formElements[i].name].push(checked[j].value);
            }
        } else {
            elements[formElements[i].name] = formElements[i].value;
        }
    }
    if (elements['boeking.arrangement'] === '0') {
        delete elements['boeking.arrangement'];
    }

    var submitEl = formEl.querySelector('[type="submit"]');
    submitEl.parentNode.insertAdjacentHTML('beforeend', '');
    submitEl.disabled = true;

    var realFormID = formEl.getAttribute('data-formid'); // IE < 11 compatibility
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://' + subdomain + '.recras.nl/api2.php/contactformulieren/' + realFormID + '/opslaan');
    xhr.send(JSON.stringify(elements));
    xhr.onreadystatechange = function(){
        if (xhr.readyState === 4) {
            removeElsWithClass('recras-loading');
            submitEl.disabled = false;
            var response = JSON.parse(xhr.response);
            if (response.success) {
                if (redirect) {
                    window.location = redirect;
                } else {
                    formEl.reset();
                    formEl.querySelector('[type="submit"]').parentNode.insertAdjacentHTML('beforeend', '
' + recras_l10n.sent_success + '
');
                }
            } else if (response.error) {
                var errors = response.error.messages;
                for (var key in errors) {
                    if (errors.hasOwnProperty(key)) {
                        formEl.querySelector('[name="' + key + '"]').parentNode.insertAdjacentHTML('beforeend', '' + errors[key] + '');
                    }
                }
                formEl.querySelector('[type="submit"]').parentNode.insertAdjacentHTML('beforeend', '
' + recras_l10n.sent_error + '
');
            } else {
                console.log('Unknown response: ', response);
            }
        }
    };
    return false;
}

var dateToString = function(date) {
    var x = new Date(date.getTime() - (date.getTimezoneOffset() * 60 * 1000)); // Fix off-by-1 errors
    return x.toISOString().substr(0, 10); // Format as 2018-03-13
};

var initPikaday = function(dateInput) {
    dateInput.setAttribute('type', 'text');

    var pikadayOptions = {
        firstDay: 1, // Monday
        numberOfMonths: 2,
        reposition: false,
        toString: function(date) {
            return dateToString(date);
        },
        field: dateInput,
        i18n: recras_l10n.pikaday,
    };
    if (dateInput.dataset.mindate) {
        pikadayOptions.minDate = new Date(dateInput.dataset.mindate);
    }

    new Pikaday(pikadayOptions);
};

document.addEventListener('DOMContentLoaded', function(){
    if (typeof Pikaday === 'function') {
        var dateEls = document.querySelectorAll('.recras-input-date');
        for (var i = 0; i < dateEls.length; i++) {
            initPikaday(dateEls[i]);
        }
    }
});


text:
package org.apache.pdfbox.pdmodel.common;

import org.apache.pdfbox.cos.COSBase;

/**
 * This is an interface used to get/create the underlying COSObject.
 *
 * @author Ben Litchfield
 */
public interface COSObjectable
{
    /**
     * Convert this standard java object to a COS object.
     *
     * @return The cos object that matches this Java object.
     */
    COSBase getCOSObject();
}


text:
/**
 * A basic cowork order
 * @bg info
 * @param {string} authToken
 @ @returns {object}
 */
module.exports = (authToken = 'non', context, callback) => {
  const firebase = require('firebase-admin')
  const firebaseConfig = {
    type: process.env.firebase_type,
    project_id: process.env.firebase_project_id,
    private_key_id: process.env.firebase_private_key_id,
    private_key: process.env.firebase_private_key,
    client_email: process.env.firebase_client_email,
    client_id: process.env.firebase_client_id,
    auth_uri: process.env.firebase_auth_uri,
    token_uri: process.env.firebase_token_uri,
    auth_provider_x509_cert_url: process.env.firebase_auth_provider_x509_cert_url,
    client_x509_cert_url: process.env.firebase_client_x509_cert_url
  }
  if (firebase.apps.length === 0) {
    firebase.initializeApp({
      credential: firebase.credential.cert(firebaseConfig),
      databaseURL: 'https://coweb-bc478.firebaseio.com'
    })
  }

  if (authToken === 'non') {
    callback(null, {
      code: 'non'
    })
  }

  if (authToken !== 'non') {
    const db = firebase.database()
    const ref = db.ref('server')
    const orders = ref.child('orders')
    const subscribersRef = ref.child('subscribers')
    const localdoor = db.ref('localblackdoor')

    subscribersRef.once('value', function (data) {
      let dataRef = data.val()
      let confirmSubArr = Object.entries(dataRef)
      let authSub = confirmSubArr.find(x => x[1].authToken === authToken)
      if (authSub === undefined) {
        callback(null, {
          code: 'Probably you are missing access rights'
        })
      }

      if (authSub) {
        orders.once('value', function (data) {
          let ordersRef = data.val()
          let now = Date.now()
          let year = new Date(now).getUTCFullYear()
          let month = new Date(now).getUTCMonth()
          let day = new Date(now).getUTCDate()
          let dateToday = new Date(Date.UTC(year, month, day)).getTime()
          if (!ordersRef[dateToday]) {
            callback(null, {
              code: 'Not booked yet'
            })
          }

          if (ordersRef[dateToday]) {
            let orderDateToday = ordersRef[dateToday]
            let openDoor = orderDateToday.find(x => x === authSub[0])

            if (openDoor === undefined) {
              callback(null, {
                code: 'Missing access rights for this day'
              })
            }

            if (openDoor) {
              let openEvent = { [Date.now()]: authSub[0] }
              localdoor.update(openEvent, function (errorDoor) {
                if (errorDoor) {
                  callback(null, {
                    error: errorDoor,
                    code: 'whatever'
                  })
                }

                if (!errorDoor) {
                  callback(null, {
                    code: 'Pull the door'
                  })
                }
              })
            }
          }
        })
      }
    })
  }
}