text:
var assert = require('assert');
var url = require('url');

// Lib includes
var testutil = require('../../framework/util');
var SR = testutil.libRequire('common/util/sr');
var TestSuite = require('../../framework/test-suite');

var azure = testutil.libRequire('azure-storage');

var Constants = azure.Constants;
var FileUtilities = azure.FileUtilities;
var HttpConstants = Constants.HttpConstants;

var shares = [];
var shareNamesPrefix = 'share-test-share-';

var fileService;
var shareName;

var suite = new TestSuite('fileservice-share-tests');
var runOrSkip = suite.isMocked ? it.skip : it;
var timeout = (suite.isRecording || !suite.isMocked) ? 30000 : 10;

describe('FileShare', function () {
  before(function (done) {
    if (suite.isMocked) {
      testutil.POLL_REQUEST_INTERVAL = 0;
    }
    suite.setupSuite(function () {
      fileService = azure.createFileService().withFilter(new azure.ExponentialRetryPolicyFilter());
      done();
    });
  });

  after(function (done) {
    suite.teardownSuite(done);
  });

  beforeEach(function (done) {
    shareName = suite.getName(shareNamesPrefix);
    suite.setupTest(done);
  });

  afterEach(function (done) {
    fileService.deleteShareIfExists(shareName, function (deleteError) {
      assert.equal(deleteError, null);
      suite.teardownTest(done);
    });
  });

  describe('doesShareExist', function () {
    it('should work', function (done) {
      fileService.doesShareExist(shareName, function (existsError, exists) {
        assert.equal(existsError, null);
        assert.strictEqual(exists, false);

        fileService.createShare(shareName, function (createError, share1, createShareResponse) {
          assert.equal(createError, null);
          assert.notEqual(share1, null);
          assert.equal(createShareResponse.statusCode, HttpConstants.HttpResponseCodes.Created);

          fileService.doesShareExist(shareName, function (existsError, exists) {
            assert.equal(existsError, null);
            assert.strictEqual(exists, true);
            done();
          });
        });
      });
    });
  });

  describe('createShare', function () {
    it('should detect incorrect share names', function (done) {
      assert.throws(function () { fileService.createShare(null, function () { }); },
        /Required argument share for function createShare is not defined/);

      assert.throws(function () { fileService.createShare('', function () { }); },
        /Required argument share for function createShare is not defined/);

      assert.throws(function () { fileService.createShare('as', function () { }); },
        /Share name must be between 3 and 63 characters long./);

      assert.throws(function () { fileService.createShare('a--s', function () { }); },
        /Share name format is incorrect./);

      assert.throws(function () { fileService.createShare('cont-', function () { }); },
        /Share name format is incorrect./);

      assert.throws(function () { fileService.createShare('conTain', function () { }); },
        /Share name format is incorrect./);

      done();
    });

    it('should work with options', function (done) {
      var quotaValue = 10;
      var options = { quota: quotaValue };
      fileService.createShare(shareName, options, function (createError, share1, createShareResponse) {
        assert.equal(createError, null);
        assert.notEqual(share1, null);
        if (share1) {
          assert.notEqual(share1.name, null);
          assert.notEqual(share1.etag, null);
          assert.notEqual(share1.lastModified, null);
        }

        assert.equal(createShareResponse.statusCode, HttpConstants.HttpResponseCodes.Created);

        // creating again will result in a duplicate error
        fileService.createShare(shareName, function (createError2, share2) {
          assert.equal(createError2.code, Constants.FileErrorCodeStrings.SHARE_ALREADY_EXISTS);
          assert.equal(share2, null);

          fileService.getShareProperties(shareName, function (getError, shareResult, getResponse) {
            assert.equal(getError, null);
            assert.notEqual(shareResult, null);
            assert.notEqual(shareResult.requestId, null);
            assert.equal(shareResult.quota, quotaValue);

            assert.notEqual(getResponse, null);
            assert.equal(getResponse.isSuccessful, true);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });
  });

  describe('createShareIfNotExists', function() {
    it('should create a share if not exists', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        fileService.doesShareExist(shareName, function (existsError, exists) {
          assert.equal(existsError, null);
          assert.equal(exists, true);

          fileService.createShareIfNotExists(shareName, function (createError2, created2) {
            assert.equal(createError2, null);
            assert.equal(created2, false);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              fileService.createShareIfNotExists(shareName, function (createError3) {
                assert.notEqual(createError3, null);
                assert.equal(createError3.code, 'ShareBeingDeleted');
                done();
              });
            });
          });
        });
      });
    });

    it('should throw if called without a callback', function (done) {
      assert.throws(function () { fileService.createShareIfNotExists('name'); },
        Error
      );

      done();
    });
  });

  describe('deleteShareIfExists', function() {
    it('should delete a share if exists', function (done) {
      fileService.doesShareExist(shareName, function(existsError, exists){
        assert.equal(existsError, null);
        assert.strictEqual(exists, false);

        fileService.deleteShareIfExists(shareName, function (deleteError, deleted) {
          assert.equal(deleteError, null);
          assert.strictEqual(deleted, false);

          fileService.createShare(shareName, function (createError, share1, createShareResponse) {
            assert.equal(createError, null);
            assert.notEqual(share1, null);
            assert.notEqual(share1.name, null);
            assert.notEqual(share1.etag, null);
            assert.notEqual(share1.lastModified, null);

            assert.equal(createShareResponse.statusCode, HttpConstants.HttpResponseCodes.Created);

            // delete if exists should succeed
            fileService.deleteShareIfExists(shareName, function (deleteError2, deleted2) {
              assert.equal(deleteError2, null);
              assert.strictEqual(deleted2, true);

              fileService.doesShareExist(shareName, function(existsError, exists){
                assert.equal(existsError, null);
                assert.strictEqual(exists, false);
                done();
              });
            });
          });
        });
      });
    });

    it('should throw if called without a callback', function (done) {
      assert.throws(function () { fileService.deleteShareIfExists('name'); },
        Error
      );
      done();
    });
  });

  describe('setShareProperties', function () {
    it('should work', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        var quotaValue = 30;
        var properties = { quota: quotaValue };
        fileService.setShareProperties(shareName, properties, function (setPropError, setPropResult, setPropResponse) {
          assert.equal(setPropError, null);
          assert.ok(setPropResponse.isSuccessful);

          fileService.getShareProperties(shareName, function (getError, share2, getResponse) {
            assert.equal(getError, null);
            assert.notEqual(share2, null);
            assert.notEqual(null, share2.requestId);
            assert.equal(share2.quota, quotaValue);

            assert.notEqual(getResponse, null);
            assert.equal(getResponse.isSuccessful, true);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });
  });

  describe('getShareProperties', function () {
    it('should work', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        var metadata = { 'Color': 'Blue' };
        fileService.setShareMetadata(shareName, metadata, function (setMetadataError, setMetadataResult, setMetadataResponse) {
          assert.equal(setMetadataError, null);
          assert.ok(setMetadataResponse.isSuccessful);

          fileService.getShareProperties(shareName, function (getError, share2, getResponse) {
            assert.equal(getError, null);
            assert.notEqual(share2, null);
            assert.notEqual(null, share2.requestId);
            assert.strictEqual(share2.metadata.color, metadata.Color);

            assert.notEqual(getResponse, null);
            assert.equal(getResponse.isSuccessful, true);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });
  });

  describe('setShareMetadata', function () {
    it('should work', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        var metadata = { 'class': 'test' };
        fileService.setShareMetadata(shareName, metadata, function (setMetadataError, setMetadataResult, setMetadataResponse) {
          assert.equal(setMetadataError, null);
          assert.ok(setMetadataResponse.isSuccessful);

          fileService.getShareMetadata(shareName, function (getMetadataError, shareMetadata, getMetadataResponse) {
            assert.equal(getMetadataError, null);
            assert.notEqual(shareMetadata, null);
            assert.notEqual(shareMetadata.metadata, null);
            assert.equal(shareMetadata.metadata.class, 'test');
            assert.ok(getMetadataResponse.isSuccessful);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });

    it('should merge the metadata', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        var metadata = { color: 'blue', Color: 'Orange', COLOR: 'Red' };
        fileService.setShareMetadata(shareName, metadata, function (setMetadataError, setMetadataResult, setMetadataResponse) {
          assert.equal(setMetadataError, null);
          assert.ok(setMetadataResponse.isSuccessful);

          fileService.getShareMetadata(shareName, function (getMetadataError, shareMetadata, getMetadataResponse) {
            assert.equal(getMetadataError, null);
            assert.notEqual(shareMetadata, null);
            assert.notEqual(shareMetadata.metadata, null);
            assert.equal(shareMetadata.metadata.color, 'blue,Orange,Red');
            assert.ok(getMetadataResponse.isSuccessful);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });

    it('should ignore the metadata in the options', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        var metadata = { color: 'blue', Color: 'Orange', COLOR: 'Red' };
        var options = { metadata: { color: 'White', Color: 'Black', COLOR: 'yellow' } };
        fileService.setShareMetadata(shareName, metadata, options, function (setMetadataError, setMetadataResult, setMetadataResponse) {
          assert.equal(setMetadataError, null);
          assert.ok(setMetadataResponse.isSuccessful);

          fileService.getShareMetadata(shareName, function (getMetadataError, shareMetadata, getMetadataResponse) {
            assert.equal(getMetadataError, null);
            assert.notEqual(shareMetadata, null);
            assert.notEqual(shareMetadata.metadata, null);
            assert.strictEqual(shareMetadata.metadata.color, 'blue,Orange,Red');
            assert.ok(getMetadataResponse.isSuccessful);

            fileService.deleteShare(shareName, function (deleteError) {
              assert.equal(deleteError, null);
              done();
            });
          });
        });
      });
    });
  });

  describe('setShareMetadataThrows', function () {
    it('should work', function (done) {
      function setShareMetadata(shareName, metadata) {
        fileService.setShareMetadata(shareName, metadata, function(){});
      }

      assert.throws( function() { setShareMetadata(shareName, {'' : 'value1'}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_KEY_INVALID});
      assert.throws( function() { setShareMetadata(shareName, {' ' : 'value1'}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_KEY_INVALID});
      assert.throws( function() { setShareMetadata(shareName, {'\n\t' : 'value1'}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_KEY_INVALID});

      assert.throws( function() { setShareMetadata(shareName, {'key1' : null}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_VALUE_INVALID});
      assert.throws( function() { setShareMetadata(shareName, {'key1' : ''}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_VALUE_INVALID});
      assert.throws( function() { setShareMetadata(shareName, {'key1' : '\n\t'}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_VALUE_INVALID});
      assert.throws( function() { setShareMetadata(shareName, {'key1' : ' '}); },
        function (err) {return (err instanceof Error) && err.message === SR.METADATA_VALUE_INVALID});

      done();
    });
  });

  describe('listShares', function () {
    it('shouldWork', function (done) {
      var shareName1 = suite.getName(shareNamesPrefix);
      var metadata1 = {
        color: 'orange',
        sharenumber: '01',
        somemetadataname: 'SomeMetadataValue'
      };

      var shareName2 = suite.getName(shareNamesPrefix);
      var metadata2 = {
        color: 'pink',
        sharenumber: '02',
        somemetadataname: 'SomeMetadataValue'
      };

      var shareName3 = suite.getName(shareNamesPrefix);
      var metadata3 = {
        color: 'brown',
        sharenumber: '03',
        somemetadataname: 'SomeMetadataValue'
      };

      var shareName4 = suite.getName(shareNamesPrefix);
      var metadata4 = {
        color: 'blue',
        sharenumber: '04',
        somemetadataname: 'SomeMetadataValue'
      };

      var validateAndDeleteShares = function (shares, entries, callback) {
        var count = shares.length;
        shares.forEach(function (share) {
          if (share.name == shareName1) {
            assert.equal(share.metadata.color, metadata1.color);
            assert.equal(share.metadata.sharenumber, metadata1.sharenumber);
            assert.equal(share.metadata.somemetadataname, metadata1.somemetadataname);
            entries.push(share.name);

            fileService.deleteShare(share.name, function (deleteError1) {
              count--;
              assert.equal(null, deleteError1);
            });
          } else if (share.name == shareName2) {
            assert.equal(share.metadata.color, metadata2.color);
            assert.equal(share.metadata.sharenumber, metadata2.sharenumber);
            assert.equal(share.metadata.somemetadataname, metadata2.somemetadataname);
            entries.push(share.name);
            fileService.deleteShare(share.name, function (deleteError2) {
              count--;
              assert.equal(null, deleteError2);
            });
          } else if (share.name == shareName3) {
            assert.equal(share.metadata.color, metadata3.color);
            assert.equal(share.metadata.sharenumber, metadata3.sharenumber);
            assert.equal(share.metadata.somemetadataname, metadata3.somemetadataname);
            entries.push(share.name);
            fileService.deleteShare(share.name, function (deleteError3) {
              count--;
              assert.equal(null, deleteError3);
            });
          } else if (share.name == shareName4) {
            assert.equal(share.metadata.color, metadata4.color);
            assert.equal(share.metadata.sharenumber, metadata4.sharenumber);
            assert.equal(share.metadata.somemetadataname, metadata4.somemetadataname);
            entries.push(share.name);
            fileService.deleteShare(share.name, function (deleteError4) {
              count--;
              assert.equal(null, deleteError4);
            });
          }
        });

        var wait = function () {
          if (count > 0) {
            setTimeout(wait, 1000);
          } else {
            callback();
          }
        };

        wait();

        return entries;
      };

      fileService.createShare(shareName1, { metadata: metadata1 }, function (createError1, createShare1, createResponse1) {
        assert.equal(createError1, null);
        assert.notEqual(createShare1, null);
        assert.ok(createResponse1.isSuccessful);

        fileService.createShare(shareName2, { metadata: metadata2 }, function (createError2, createShare2, createResponse2) {
          assert.equal(createError2, null);
          assert.notEqual(createShare2, null);
          assert.ok(createResponse2.isSuccessful);

          fileService.createShare(shareName3, { metadata: metadata3 }, function (createError3, createShare3, createResponse3) {
            assert.equal(createError3, null);
            assert.notEqual(createShare3, null);
            assert.ok(createResponse3.isSuccessful);

            fileService.createShare(shareName4, { metadata: metadata4 }, function (createError4, createShare4, createResponse4) {
              assert.equal(createError4, null);
              assert.notEqual(createShare4, null);
              assert.ok(createResponse4.isSuccessful);

              var options = {
                'maxResults': 3,
                'include': 'metadata',
              };

              shares.length = 0;
              listShares(shareNamesPrefix, options, null, function () {
                var entries = [];
                validateAndDeleteShares(shares, entries, done);
                assert.equal(entries.length, 4);
              });
            });
          });
        });
      });
    });

    it('noPrefix', function (done) {
      var listSharesWithoutPrefix = function (options, token, callback) {
        fileService.listSharesSegmented(token, options, function(error, result) {
          assert.equal(error, null);
          shares.push.apply(shares, result.entries);
          var token = result.continuationToken;
          if(token) {
            listSharesWithoutPrefix(options, token, callback);
          } else {
            callback();
          }
        });
      };

      listSharesWithoutPrefix(null, null, function () {
        done();
      });
    });

    it('strangePrefix', function (done) {
      shares.length = 0;
      listShares('中文', null, null, function () {
        assert.equal(shares.length, 0);
        done();
      });
    });
  });

  describe('shared access signature', function () {
    it('should work with shared access policy', function (done) {
      var share = 'testshare';
      var directoryName = "testdir";
      var fileName = "testfile";
      var fileServiceassert = azure.createFileService('storageAccount', 'storageAccessKey', 'host.com:80');
      var sharedAccessPolicy = {
        AccessPolicy: {
          Expiry: new Date('February 12, 2015 11:03:40 am GMT')
        }
      };

      var fileUrl = fileServiceassert.getUrl(share, directoryName, fileName, fileServiceassert.generateSharedAccessSignature(share, directoryName, fileName, sharedAccessPolicy));
      var parsedUrl = url.parse(fileUrl);
      assert.strictEqual(parsedUrl.protocol, 'https:');
      assert.strictEqual(parsedUrl.port, '80');
      assert.strictEqual(parsedUrl.hostname, 'host.com');
      assert.strictEqual(parsedUrl.pathname, '/' + share + '/' + directoryName + '/' + fileName);
      assert.strictEqual(parsedUrl.query, 'se=2015-02-12T11%3A03%3A40Z&sv=2015-04-05&sr=f&sig=5OSCfNVVRD6mBv3apBKKe3sWWrFQEhaq4om3xuxZVO4%3D');

      done();
    });

    // Skip this case in nock because the signing key is different between live run and mocked run
    runOrSkip('should work with share and file policies', function (done) {
      var sharePolicy = {
        AccessPolicy: {
          Permissions: 'rw',
          Expiry: new Date('2016-10-01')
        }
      };

      var filePolicy = {
        AccessPolicy: {
          Permissions: 'd',
          Expiry: new Date('2016-10-10')
        }
      };

      fileService.createShareIfNotExists(shareName, function (createError, share, createResponse) {
        var fileName = suite.getName("file-");
        var directoryName = '.';
        var shareSas = fileService.generateSharedAccessSignature(shareName, directoryName, null, sharePolicy);
        var fileServiceShareSas = azure.createFileServiceWithSas(fileService.host, shareSas);
        fileServiceShareSas.createFile(shareName, directoryName, fileName, 5, function (createError, file, createResponse) {
          assert.equal(createError, null);
          assert.strictEqual(file.share, shareName);
          assert.strictEqual(file.directory, directoryName);
          assert.strictEqual(file.name, fileName);
          var fileSas = fileService.generateSharedAccessSignature(shareName, directoryName, fileName, filePolicy);
          var fileServiceFileSas = azure.createFileServiceWithSas(fileService.host, fileSas);
          fileServiceFileSas.deleteFile(shareName, directoryName, fileName, function (deleteError) {
            assert.equal(deleteError, null);

            done();
          });
        });
      });

    });
  });

  describe('getShareAcl', function () {
    it('should work', function (done) {
      fileService.createShareIfNotExists(shareName, function () {
        fileService.getShareAcl(shareName, function (shareAclError, shareResult, shareAclResponse) {
          assert.equal(shareAclError, null);
          assert.notEqual(shareResult, null);
          if (shareResult) {
            assert.equal(shareResult.publicAccessLevel, FileUtilities.SharePublicAccessType.OFF);
          }
          assert.equal(shareAclResponse.isSuccessful, true);
          done();
        });
      });
    });
  });

  describe('setShareAcl', function () {
    it('should work with policies', function (done) {
      var readWriteStartDate = new Date(Date.UTC(2012, 10, 10));
      var readWriteExpiryDate = new Date(readWriteStartDate);
      readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10);
      readWriteExpiryDate.setMilliseconds(999);

      var readWriteSharedAccessPolicy = {
        Id: 'readwrite',
        AccessPolicy: {
          Start: readWriteStartDate,
          Expiry: readWriteExpiryDate,
          Permissions: 'rw'
        }
      };

      var readSharedAccessPolicy = {
        Id: 'read',
        AccessPolicy: {
          Expiry: readWriteStartDate,
          Permissions: 'r'
        }
      };

      fileService.createShareIfNotExists(shareName, function () {
        var directoryName = suite.getName('dir-');
        var fileName = suite.getName('file-');
        var fileText = 'Hello World!';

        fileService.createDirectoryIfNotExists(shareName, directoryName, function (directoryError, directoryResult, directoryResponse) {
          assert.equal(directoryError, null);
          assert.notEqual(directoryResult, null);

          var signedIdentifiers = [readWriteSharedAccessPolicy, readSharedAccessPolicy];
          fileService.setShareAcl(shareName, signedIdentifiers, function (setAclError, setAclShare1, setResponse1) {
            assert.equal(setAclError, null);
            assert.notEqual(setAclShare1, null);
            assert.ok(setResponse1.isSuccessful);

            setTimeout(function () {
              fileService.getShareAcl(shareName, function (getAclError, getAclShare1, getResponse1) {
                assert.equal(getAclError, null);
                assert.notEqual(getAclShare1, null);
                assert.equal(getAclShare1.publicAccessLevel, FileUtilities.SharePublicAccessType.OFF);
                assert.equal(getAclShare1.signedIdentifiers[0].AccessPolicy.Expiry.getTime(), readWriteExpiryDate.getTime());
                assert.ok(getResponse1.isSuccessful);

                fileService.setShareAcl(shareName, [], function (setAclError2, setAclShare2, setResponse2) {
                  assert.equal(setAclError2, null);
                  assert.notEqual(setAclShare2, null);
                  assert.ok(setResponse2.isSuccessful);

                  setTimeout(function () {
                    fileService.getShareAcl(shareName, function (getAclError2, getAclShare2, getResponse3) {
                      assert.equal(getAclError2, null);
                      assert.notEqual(getAclShare2, null);
                      assert.equal(getAclShare2.publicAccessLevel, FileUtilities.SharePublicAccessType.OFF);
                      assert.ok(getResponse3.isSuccessful);
                      done();
                    });
                  }, timeout);
                });
              });
            }, timeout);
          });
        });
      });
    });

    it('should work with signed identifiers', function (done) {
      var signedIdentifiers = [
        {
          Id: 'id1',
          AccessPolicy: {
            Start: '2009-10-10T00:00:00.123Z',
            Expiry: '2009-10-11T00:00:00.456Z',
            Permissions: 'r'
          }
        },
        {
          Id: 'id2',
          AccessPolicy: {
            Start: '2009-11-10T00:00:00.006Z',
            Expiry: '2009-11-11T00:00:00.4Z',
            Permissions: 'w'
          }
        }];

      fileService.createShareIfNotExists(shareName, function () {
        var directoryName = suite.getName('dir-');
        var fileName = suite.getName('file-');
        var fileText = 'Hello World!';

        fileService.createDirectoryIfNotExists(shareName, directoryName, function (directoryError, directoryResult, directoryResponse) {
          assert.equal(directoryError, null);
          assert.notEqual(directoryResult, null);
          fileService.setShareAcl(shareName, signedIdentifiers, function (setAclError, setAclShare, setAclResponse) {
            assert.equal(setAclError, null);
            assert.notEqual(setAclShare, null);
            assert.ok(setAclResponse.isSuccessful);
            setTimeout(function () {
              fileService.getShareAcl(shareName, function (getAclError, shareAcl, getAclResponse) {
                assert.equal(getAclError, null);
                assert.notEqual(shareAcl, null);
                assert.notEqual(getAclResponse, null);

                if (getAclResponse) {
                  assert.equal(getAclResponse.isSuccessful, true);
                }

                var entries = 0;
                shareAcl.signedIdentifiers.forEach(function (identifier) {
                  if (identifier.Id === 'id1') {
                    assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-10-10T00:00:00.123Z').getTime());
                    assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-10-11T00:00:00.456Z').getTime());
                    assert.equal(identifier.AccessPolicy.Permissions, 'r');
                    entries += 1;
                  } else if (identifier.Id === 'id2') {
                    assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-11-10T00:00:00.006Z').getTime());
                    assert.equal(identifier.AccessPolicy.Start.getMilliseconds(), 6);
                    assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-11-11T00:00:00.4Z').getTime());
                    assert.equal(identifier.AccessPolicy.Expiry.getMilliseconds(), 400);
                    assert.equal(identifier.AccessPolicy.Permissions, 'w');
                    entries += 2;
                  }
                });
                assert.equal(entries, 3);
                done();
              });
            }, timeout);
          });
        });
      });
    });
  });

  describe('getShareStats', function () {
    it('should work', function (done) {
      fileService.createShareIfNotExists(shareName, function (createError, created) {
        assert.equal(createError, null);
        assert.equal(created, true);

        fileService.getShareStats(shareName, function (getError, stats, getResponse) {
          assert.equal(getError, null);
          assert.equal(stats.sharestats.shareusage, 0);

          var fileText = 'hi there';
          var fileName = suite.getName("file-");
          fileService.createFileFromText(shareName, '', fileName, fileText, function (uploadErr) {
            assert.equal(uploadErr, null);

            fileService.getShareStats(shareName, function (getError, stats, getResponse) {
              assert.equal(getError, null);
              assert.equal(stats.sharestats.shareusage, 1);

              fileService.deleteShare(shareName, function (deleteError) {
                assert.equal(deleteError, null);
                done();
              });
            });
          });
        });
      });
    });
  });

});

function listShares (prefix, options, token, callback) {
  fileService.listSharesSegmentedWithPrefix(prefix, token, options, function(error, result) {
    assert.equal(error, null);
    shares.push.apply(shares, result.entries);
    var token = result.continuationToken;
    if(token) {
      listShares(prefix, options, token, callback);
    } else {
      callback();
    }
  });
}


text:
namespace WorkoutApp.Helpers
{
    using System;
    using System.Threading.Tasks;
    using Windows.Storage;

    public class GetRandomExercise
    {
        Random random = new Random();

        public async Task<Tuple<string, string>> GetRandomExerciseAsync()
        {
            var desiredFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            desiredFolder = await desiredFolder.GetFolderAsync("Assets");

            var file = await desiredFolder.GetFileAsync("Exercises.txt");

            var fileContent = await FileIO.ReadTextAsync(file);
            var splittedFileContent = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            int id = random.Next(0, splittedFileContent.Length);

            var output = splittedFileContent[id].Split(',');
            return new Tuple<string, string>(output[0], output[1]);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using NHibernate.Validator.Constraints;
using SharpArch.Core.DomainModel;

namespace Northwind.Core
{
    public class Category : Entity
    {
        public Category() { }

        /// <summary>
        /// Creates valid domain object
        /// </summary>
        public Category(string name) {
            CategoryName = name;
        }

        [DomainSignature]
        [NotNullNotEmpty]
        public virtual string CategoryName { get; protected set; }
    }
}


text:
@interface MBPageBinder()

@property (nonatomic, retain) MBBuildState *state;
@property (nonatomic, retain) NSMutableDictionary *childViewBinders;

@end

@implementation MBPageBinder

- (MBBuildState *)state
{
    if (!_state) {
        _state = [[MBBuildState alloc] init];
    }
    return _state;
}

- (NSMutableDictionary *)childViewBinders
{
    if (!_childViewBinders) {
        _childViewBinders = [[NSMutableDictionary alloc] init];
    }
    return _childViewBinders;
}

- (instancetype)initWithViewController:(MBBasicViewController *)viewController
{
    self = [super initWithBindingIdentifier:nil];
    if (self) {
        self.state.mainViewBinder = self;
        self.state.view           = viewController.view;
        self.state.component      = viewController.page;
        self.state.element        = viewController.page.document;
        self.state.document       = viewController.page.document;
    }
    return self;
}

+ (instancetype)binderWithViewController:(MBBasicViewController *)viewController
{
    return [[[MBPageBinder alloc] initWithViewController:viewController] autorelease];
}

- (void)bind
{
    [self bindView:self.state];
}

- (UIView *)findSpecificView:(MBBuildState *)state
{
    id<MBViewBinder> binder = self.childViewBinders[state.component.name];
    return [binder bindView:state];
}

- (void)registerBinder:(id<MBViewBinder>)binder
{
    assert([binder respondsToSelector:@selector(identifier)]);
    self.childViewBinders[[(id)binder identifier]] = binder;
}

- (void)dealloc
{
    self.state = nil;
    self.childViewBinders = nil;
    [super dealloc];
}

@end


text:
namespace {

base::LazyInstance<std::set<Profile*> > g_profiles_evaluated =
    LAZY_INSTANCE_INITIALIZER;

// Layout constants.
const int kExtensionListPadding = 10;
const int kInsetBottomRight = 13;
const int kInsetLeft = 14;
const int kInsetTop = 9;
const int kHeadlineMessagePadding = 4;
const int kHeadlineRowPadding = 10;
const int kMessageBubblePadding = 11;

// How many extensions to show in the bubble (max).
const size_t kMaxExtensionsToShow = 7;

// How long to wait until showing the bubble (in seconds).
const int kBubbleAppearanceWaitTime = 5;

}  // namespace

namespace extensions {

ExtensionMessageBubbleView::ExtensionMessageBubbleView(
    views::View* anchor_view,
    views::BubbleBorder::Arrow arrow_location,
    scoped_ptr<extensions::ExtensionMessageBubbleController> controller)
    : BubbleDelegateView(anchor_view, arrow_location),
      controller_(controller.Pass()),
      anchor_view_(anchor_view),
      headline_(NULL),
      learn_more_(NULL),
      dismiss_button_(NULL),
      link_clicked_(false),
      action_taken_(false),
      weak_factory_(this) {
  DCHECK(anchor_view->GetWidget());
  set_close_on_deactivate(controller_->CloseOnDeactivate());
  set_close_on_esc(true);

  // Compensate for built-in vertical padding in the anchor view's image.
  set_anchor_view_insets(gfx::Insets(5, 0, 5, 0));
}

void ExtensionMessageBubbleView::OnActionButtonClicked(
    const base::Closure& callback) {
  action_callback_ = callback;
}

void ExtensionMessageBubbleView::OnDismissButtonClicked(
    const base::Closure& callback) {
  dismiss_callback_ = callback;
}

void ExtensionMessageBubbleView::OnLinkClicked(
    const base::Closure& callback) {
  link_callback_ = callback;
}

void ExtensionMessageBubbleView::Show() {
  // Not showing the bubble right away (during startup) has a few benefits:
  // We don't have to worry about focus being lost due to the Omnibox (or to
  // other things that want focus at startup). This allows Esc to work to close
  // the bubble and also solves the keyboard accessibility problem that comes
  // with focus being lost (we don't have a good generic mechanism of injecting
  // bubbles into the focus cycle). Another benefit of delaying the show is
  // that fade-in works (the fade-in isn't apparent if the the bubble appears at
  // startup).
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&ExtensionMessageBubbleView::ShowBubble,
                 weak_factory_.GetWeakPtr()),
      base::TimeDelta::FromSeconds(kBubbleAppearanceWaitTime));
}

void ExtensionMessageBubbleView::OnWidgetDestroying(views::Widget* widget) {
  // To catch Esc, we monitor destroy message. Unless the link has been clicked,
  // we assume Dismiss was the action taken.
  if (!link_clicked_ && !action_taken_)
    dismiss_callback_.Run();
}

////////////////////////////////////////////////////////////////////////////////
// ExtensionMessageBubbleView - private.

ExtensionMessageBubbleView::~ExtensionMessageBubbleView() {}

void ExtensionMessageBubbleView::ShowBubble() {
  GetWidget()->Show();
}

void ExtensionMessageBubbleView::Init() {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  layout->SetInsets(kInsetTop, kInsetLeft,
                    kInsetBottomRight, kInsetBottomRight);
  SetLayoutManager(layout);

  ExtensionMessageBubbleController::Delegate* delegate =
      controller_->delegate();

  const int headline_column_set_id = 0;
  views::ColumnSet* top_columns = layout->AddColumnSet(headline_column_set_id);
  top_columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
                         0, views::GridLayout::USE_PREF, 0, 0);
  top_columns->AddPaddingColumn(1, 0);
  layout->StartRow(0, headline_column_set_id);

  headline_ = new views::Label(delegate->GetTitle(),
                               rb.GetFontList(ui::ResourceBundle::MediumFont));
  layout->AddView(headline_);

  layout->AddPaddingRow(0, kHeadlineRowPadding);

  const int text_column_set_id = 1;
  views::ColumnSet* upper_columns = layout->AddColumnSet(text_column_set_id);
  upper_columns->AddColumn(
      views::GridLayout::LEADING, views::GridLayout::LEADING,
      0, views::GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, text_column_set_id);

  views::Label* message = new views::Label();
  message->SetMultiLine(true);
  message->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  message->SetText(delegate->GetMessageBody(
      anchor_view_->id() == VIEW_ID_BROWSER_ACTION));
  message->SizeToFit(views::Widget::GetLocalizedContentsWidth(
      IDS_EXTENSION_WIPEOUT_BUBBLE_WIDTH_CHARS));
  layout->AddView(message);

  if (delegate->ShouldShowExtensionList()) {
    const int extension_list_column_set_id = 2;
    views::ColumnSet* middle_columns =
        layout->AddColumnSet(extension_list_column_set_id);
    middle_columns->AddPaddingColumn(0, kExtensionListPadding);
    middle_columns->AddColumn(
        views::GridLayout::LEADING, views::GridLayout::CENTER,
        0, views::GridLayout::USE_PREF, 0, 0);

    layout->StartRowWithPadding(0, extension_list_column_set_id,
        0, kHeadlineMessagePadding);
    views::Label* extensions = new views::Label();
    extensions->SetMultiLine(true);
    extensions->SetHorizontalAlignment(gfx::ALIGN_LEFT);

    std::vector<base::string16> extension_list;
    base::char16 bullet_point = 0x2022;

    std::vector<base::string16> suspicious = controller_->GetExtensionList();
    size_t i = 0;
    for (; i < suspicious.size() && i < kMaxExtensionsToShow; ++i) {
      // Add each extension with bullet point.
      extension_list.push_back(
          bullet_point + base::ASCIIToUTF16(" ") + suspicious[i]);
    }

    if (i > kMaxExtensionsToShow) {
      base::string16 difference = base::IntToString16(i - kMaxExtensionsToShow);
      extension_list.push_back(bullet_point + base::ASCIIToUTF16(" ") +
          delegate->GetOverflowText(difference));
    }

    extensions->SetText(JoinString(extension_list, base::ASCIIToUTF16("\n")));
    extensions->SizeToFit(views::Widget::GetLocalizedContentsWidth(
        IDS_EXTENSION_WIPEOUT_BUBBLE_WIDTH_CHARS));
    layout->AddView(extensions);
  }

  base::string16 action_button = delegate->GetActionButtonLabel();

  const int action_row_column_set_id = 3;
  views::ColumnSet* bottom_columns =
      layout->AddColumnSet(action_row_column_set_id);
  bottom_columns->AddColumn(views::GridLayout::LEADING,
      views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0);
  bottom_columns->AddPaddingColumn(1, 0);
  bottom_columns->AddColumn(views::GridLayout::TRAILING,
      views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0);
  if (!action_button.empty()) {
    bottom_columns->AddColumn(views::GridLayout::TRAILING,
        views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0);
  }
  layout->StartRowWithPadding(0, action_row_column_set_id,
                              0, kMessageBubblePadding);

  learn_more_ = new views::Link(delegate->GetLearnMoreLabel());
  learn_more_->set_listener(this);
  layout->AddView(learn_more_);

  if (!action_button.empty()) {
    action_button_ = new views::LabelButton(this, action_button.c_str());
    action_button_->SetStyle(views::Button::STYLE_BUTTON);
    layout->AddView(action_button_);
  }

  dismiss_button_ = new views::LabelButton(this,
      delegate->GetDismissButtonLabel());
  dismiss_button_->SetStyle(views::Button::STYLE_BUTTON);
  layout->AddView(dismiss_button_);
}

void ExtensionMessageBubbleView::ButtonPressed(views::Button* sender,
                                               const ui::Event& event) {
  if (sender == action_button_) {
    action_taken_ = true;
    action_callback_.Run();
  } else {
    DCHECK_EQ(dismiss_button_, sender);
  }
  GetWidget()->Close();
}

void ExtensionMessageBubbleView::LinkClicked(views::Link* source,
                                             int event_flags) {
  DCHECK_EQ(learn_more_, source);
  link_clicked_ = true;
  link_callback_.Run();
  GetWidget()->Close();
}

void ExtensionMessageBubbleView::GetAccessibleState(
    ui::AXViewState* state) {
  state->role = ui::AX_ROLE_ALERT;
}

void ExtensionMessageBubbleView::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add && details.child == this)
    NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true);
}

////////////////////////////////////////////////////////////////////////////////
// ExtensionMessageBubbleFactory

ExtensionMessageBubbleFactory::ExtensionMessageBubbleFactory(
    Profile* profile,
    ToolbarView* toolbar_view)
    : profile_(profile),
      toolbar_view_(toolbar_view),
      shown_suspicious_extensions_bubble_(false),
      shown_startup_override_extensions_bubble_(false),
      shown_proxy_override_extensions_bubble_(false),
      shown_dev_mode_extensions_bubble_(false),
      is_observing_(false),
      stage_(STAGE_START),
      container_(NULL),
      anchor_view_(NULL) {}

ExtensionMessageBubbleFactory::~ExtensionMessageBubbleFactory() {
  MaybeStopObserving();
}

void ExtensionMessageBubbleFactory::MaybeShow(views::View* anchor_view) {
#if defined(OS_WIN)
  bool is_initial_check = IsInitialProfileCheck(profile_->GetOriginalProfile());
  RecordProfileCheck(profile_->GetOriginalProfile());

  // The list of suspicious extensions takes priority over the dev mode bubble
  // and the settings API bubble, since that needs to be shown as soon as we
  // disable something. The settings API bubble is shown on first startup after
  // an extension has changed the startup pages and it is acceptable if that
  // waits until the next startup because of the suspicious extension bubble.
  // The dev mode bubble is not time sensitive like the other two so we'll catch
  // the dev mode extensions on the next startup/next window that opens. That
  // way, we're not too spammy with the bubbles.
  if (!shown_suspicious_extensions_bubble_ &&
      MaybeShowSuspiciousExtensionsBubble(anchor_view))
    return;

  if (!shown_startup_override_extensions_bubble_ &&
      is_initial_check &&
      MaybeShowStartupOverrideExtensionsBubble(anchor_view))
    return;

  if (!shown_proxy_override_extensions_bubble_ &&
      MaybeShowProxyOverrideExtensionsBubble(anchor_view))
    return;

  if (!shown_dev_mode_extensions_bubble_)
    MaybeShowDevModeExtensionsBubble(anchor_view);
#endif  // OS_WIN
}

bool ExtensionMessageBubbleFactory::MaybeShowSuspiciousExtensionsBubble(
    views::View* anchor_view) {
  DCHECK(!shown_suspicious_extensions_bubble_);

  scoped_ptr<SuspiciousExtensionBubbleController> suspicious_extensions(
      new SuspiciousExtensionBubbleController(profile_));
  if (!suspicious_extensions->ShouldShow())
    return false;

  shown_suspicious_extensions_bubble_ = true;
  SuspiciousExtensionBubbleController* weak_controller =
      suspicious_extensions.get();
  ExtensionMessageBubbleView* bubble_delegate =
      new ExtensionMessageBubbleView(anchor_view,
                                     views::BubbleBorder::TOP_RIGHT,
                                     suspicious_extensions.Pass());

  views::BubbleDelegateView::CreateBubble(bubble_delegate);
  weak_controller->Show(bubble_delegate);

  return true;
}

bool ExtensionMessageBubbleFactory::MaybeShowStartupOverrideExtensionsBubble(
    views::View* anchor_view) {
#if !defined(OS_WIN)
  return false;
#else
  DCHECK(!shown_startup_override_extensions_bubble_);

  const Extension* extension = GetExtensionOverridingStartupPages(profile_);
  if (!extension)
    return false;

  scoped_ptr<SettingsApiBubbleController> settings_api_bubble(
      new SettingsApiBubbleController(profile_,
                                      BUBBLE_TYPE_STARTUP_PAGES));
  if (!settings_api_bubble->ShouldShow(extension->id()))
    return false;

  shown_startup_override_extensions_bubble_ = true;
  PrepareToHighlightExtensions(settings_api_bubble.Pass(), anchor_view);
  return true;
#endif
}

bool ExtensionMessageBubbleFactory::MaybeShowProxyOverrideExtensionsBubble(
    views::View* anchor_view) {
#if !defined(OS_WIN)
  return false;
#else
  DCHECK(!shown_proxy_override_extensions_bubble_);

  const Extension* extension = GetExtensionOverridingProxy(profile_);
  if (!extension)
    return false;

  scoped_ptr<ProxyOverriddenBubbleController> proxy_bubble(
      new ProxyOverriddenBubbleController(profile_));
  if (!proxy_bubble->ShouldShow(extension->id()))
    return false;

  shown_proxy_override_extensions_bubble_ = true;
  PrepareToHighlightExtensions(proxy_bubble.Pass(), anchor_view);
  return true;
#endif
}

bool ExtensionMessageBubbleFactory::MaybeShowDevModeExtensionsBubble(
    views::View* anchor_view) {
  DCHECK(!shown_dev_mode_extensions_bubble_);

  // Check the Developer Mode extensions.
  scoped_ptr<DevModeBubbleController> dev_mode_extensions(
      new DevModeBubbleController(profile_));

  // Return early if we have none to show.
  if (!dev_mode_extensions->ShouldShow())
    return false;

  shown_dev_mode_extensions_bubble_ = true;
  PrepareToHighlightExtensions(dev_mode_extensions.Pass(), anchor_view);
  return true;
}

void ExtensionMessageBubbleFactory::MaybeObserve() {
  if (!is_observing_) {
    is_observing_ = true;
    container_->AddObserver(this);
  }
}

void ExtensionMessageBubbleFactory::MaybeStopObserving() {
  if (is_observing_) {
    is_observing_ = false;
    container_->RemoveObserver(this);
  }
}

void ExtensionMessageBubbleFactory::RecordProfileCheck(Profile* profile) {
  g_profiles_evaluated.Get().insert(profile);
}

bool ExtensionMessageBubbleFactory::IsInitialProfileCheck(Profile* profile) {
  return g_profiles_evaluated.Get().count(profile) == 0;
}

void ExtensionMessageBubbleFactory::OnBrowserActionsContainerAnimationEnded() {
  MaybeStopObserving();
  if (stage_ == STAGE_START) {
    HighlightExtensions();
  } else if (stage_ == STAGE_HIGHLIGHTED) {
    ShowHighlightingBubble();
  } else {  // We shouldn't be observing if we've completed the process.
    NOTREACHED();
    Finish();
  }
}

void ExtensionMessageBubbleFactory::OnBrowserActionsContainerDestroyed() {
  // If the container associated with the bubble is destroyed, abandon the
  // process.
  Finish();
}

void ExtensionMessageBubbleFactory::PrepareToHighlightExtensions(
    scoped_ptr<ExtensionMessageBubbleController> controller,
    views::View* anchor_view) {
  // We should be in the start stage (i.e., should not have a pending attempt to
  // show a bubble).
  DCHECK_EQ(stage_, STAGE_START);

  // Prepare to display and highlight the extensions before showing the bubble.
  // Since this is an asynchronous process, set member variables for later use.
  controller_ = controller.Pass();
  anchor_view_ = anchor_view;
  container_ = toolbar_view_->browser_actions();

  if (container_->animating())
    MaybeObserve();
  else
    HighlightExtensions();
}

void ExtensionMessageBubbleFactory::HighlightExtensions() {
  DCHECK_EQ(STAGE_START, stage_);
  stage_ = STAGE_HIGHLIGHTED;

  const ExtensionIdList extension_list = controller_->GetExtensionIdList();
  DCHECK(!extension_list.empty());
  ExtensionToolbarModel::Get(profile_)->HighlightExtensions(extension_list);
  if (container_->animating())
    MaybeObserve();
  else
    ShowHighlightingBubble();
}

void ExtensionMessageBubbleFactory::ShowHighlightingBubble() {
  DCHECK_EQ(stage_, STAGE_HIGHLIGHTED);
  stage_ = STAGE_COMPLETE;

  views::View* reference_view = NULL;
  if (container_->num_toolbar_actions() > 0u)
    reference_view = container_->GetToolbarActionViewAt(0);
  if (reference_view && reference_view->visible())
    anchor_view_ = reference_view;

  ExtensionMessageBubbleController* weak_controller = controller_.get();
  ExtensionMessageBubbleView* bubble_delegate =
      new ExtensionMessageBubbleView(
          anchor_view_,
          views::BubbleBorder::TOP_RIGHT,
          scoped_ptr<ExtensionMessageBubbleController>(
              controller_.release()));
  views::BubbleDelegateView::CreateBubble(bubble_delegate);
  weak_controller->Show(bubble_delegate);

  Finish();
}

void ExtensionMessageBubbleFactory::Finish() {
  MaybeStopObserving();
  controller_.reset();
  anchor_view_ = NULL;
  container_ = NULL;
}

}  // namespace extensions


text:
from distutils.core import setup

setup(
    name='GitSync',
    version='0.1.0',
    author='Jachin Rupe',
    author_email='jachin@clockwork.net',
    packages=['gitsync'],
    scripts=['bin/git_sync'],
    url='http://pypi.python.org/pypi/GitSync/',
    license='LICENSE.txt',
    description='Use git to sync a project directory on an OS X client with a'
                ' remote server.',
    long_description=open('README.txt').read(),
    install_requires=[
        "Fabric >= 1.8.0",
        "MacFSEvents >= 0.3",
        "PyYAML >= 3.10",
    ],
)


text:
package org.apache.lucene.index;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;

/**
 * Byte[] referencing is used because a new norm object needs
 * to be created for each clone, and the byte array is all
 * that is needed for sharing between cloned readers.  The
 * current norm referencing is for sharing between readers
 * whereas the byte[] referencing is for copy on write which
 * is independent of reader references (i.e. incRef, decRef).
 */

final class SegmentNorms implements Cloneable {

  /** norms header placeholder */
  static final byte[] NORMS_HEADER = new byte[]{'N','R','M',-1};

  int refCount = 1;

  // If this instance is a clone, the originalNorm
  // references the Norm that has a real open IndexInput:
  private SegmentNorms origNorm;

  private IndexInput in;
  private long normSeek;

  // null until bytes is set
  private AtomicInteger bytesRef;
  private byte[] bytes;
  private int number;

  boolean dirty;
  boolean rollbackDirty;

  private final SegmentReader owner;

  public SegmentNorms(IndexInput in, int number, long normSeek, SegmentReader owner) {
    this.in = in;
    this.number = number;
    this.normSeek = normSeek;
    this.owner = owner;
  }

  public synchronized void incRef() {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);
    refCount++;
  }

  private void closeInput() throws IOException {
    if (in != null) {
      if (in != owner.singleNormStream) {
        // It's private to us -- just close it
        in.close();
      } else {
        // We are sharing this with others -- decRef and
        // maybe close the shared norm stream
        if (owner.singleNormRef.decrementAndGet() == 0) {
          owner.singleNormStream.close();
          owner.singleNormStream = null;
        }
      }

      in = null;
    }
  }

  public synchronized void decRef() throws IOException {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);

    if (--refCount == 0) {
      if (origNorm != null) {
        origNorm.decRef();
        origNorm = null;
      } else {
        closeInput();
      }

      if (bytes != null) {
        assert bytesRef != null;
        bytesRef.decrementAndGet();
        bytes = null;
        bytesRef = null;
      } else {
        assert bytesRef == null;
      }
    }
  }

  // Load bytes but do not cache them if they were not
  // already cached
  public synchronized void bytes(byte[] bytesOut, int offset, int len) throws IOException {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);
    if (bytes != null) {
      // Already cached -- copy from cache:
      assert len <= owner.maxDoc();
      System.arraycopy(bytes, 0, bytesOut, offset, len);
    } else {
      // Not cached
      if (origNorm != null) {
        // Ask origNorm to load
        origNorm.bytes(bytesOut, offset, len);
      } else {
        // We are orig -- read ourselves from disk:
        synchronized(in) {
          in.seek(normSeek);
          in.readBytes(bytesOut, offset, len, false);
        }
      }
    }
  }

  // Load & cache full bytes array.  Returns bytes.
  public synchronized byte[] bytes() throws IOException {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);
    if (bytes == null) {                     // value not yet read
      assert bytesRef == null;
      if (origNorm != null) {
        // Ask origNorm to load so that for a series of
        // reopened readers we share a single read-only
        // byte[]
        bytes = origNorm.bytes();
        bytesRef = origNorm.bytesRef;
        bytesRef.incrementAndGet();

        // Once we've loaded the bytes we no longer need
        // origNorm:
        origNorm.decRef();
        origNorm = null;

      } else {
        // We are the origNorm, so load the bytes for real
        // ourself:
        final int count = owner.maxDoc();
        bytes = new byte[count];

        // Since we are orig, in must not be null
        assert in != null;

        // Read from disk.
        synchronized(in) {
          in.seek(normSeek);
          in.readBytes(bytes, 0, count, false);
        }

        bytesRef = new AtomicInteger(1);
        closeInput();
      }
    }

    return bytes;
  }

  // Only for testing
  AtomicInteger bytesRef() {
    return bytesRef;
  }

  // Called if we intend to change a norm value.  We make a
  // private copy of bytes if it's shared with others:
  public synchronized byte[] copyOnWrite() throws IOException {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);
    bytes();
    assert bytes != null;
    assert bytesRef != null;
    if (bytesRef.get() > 1) {
      // I cannot be the origNorm for another norm
      // instance if I'm being changed.  Ie, only the
      // "head Norm" can be changed:
      assert refCount == 1;
      final AtomicInteger oldRef = bytesRef;
      bytes = owner.cloneNormBytes(bytes);
      bytesRef = new AtomicInteger(1);
      oldRef.decrementAndGet();
    }
    dirty = true;
    return bytes;
  }

  // Returns a copy of this Norm instance that shares
  // IndexInput & bytes with the original one
  @Override
  public synchronized Object clone() {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0);

    SegmentNorms clone;
    try {
      clone = (SegmentNorms) super.clone();
    } catch (CloneNotSupportedException cnse) {
      // Cannot happen
      throw new RuntimeException("unexpected CloneNotSupportedException", cnse);
    }
    clone.refCount = 1;

    if (bytes != null) {
      assert bytesRef != null;
      assert origNorm == null;

      // Clone holds a reference to my bytes:
      clone.bytesRef.incrementAndGet();
    } else {
      assert bytesRef == null;
      if (origNorm == null) {
        // I become the origNorm for the clone:
        clone.origNorm = this;
      }
      clone.origNorm.incRef();
    }

    // Only the origNorm will actually readBytes from in:
    clone.in = null;

    return clone;
  }

  // Flush all pending changes to the next generation
  // separate norms file.
  public void reWrite(SegmentInfo si) throws IOException {
    assert refCount > 0 && (origNorm == null || origNorm.refCount > 0): "refCount=" + refCount + " origNorm=" + origNorm;

    // NOTE: norms are re-written in regular directory, not cfs
    si.advanceNormGen(this.number);
    final String normFileName = si.getNormFileName(this.number);
    IndexOutput out = owner.directory().createOutput(normFileName);
    boolean success = false;
    try {
      try {
        out.writeBytes(SegmentNorms.NORMS_HEADER, 0, SegmentNorms.NORMS_HEADER.length);
        out.writeBytes(bytes, owner.maxDoc());
      } finally {
        out.close();
      }
      success = true;
    } finally {
      if (!success) {
        try {
          owner.directory().deleteFile(normFileName);
        } catch (Throwable t) {
          // suppress this so we keep throwing the
          // original exception
        }
      }
    }
    this.dirty = false;
  }
}


text:
from flask import get_flashed_messages, request

def api_cache_key(namespace, *args, **kwargs):
    def gen_key(**kwargs):
        path = request.path
        reqstr = ""
        if request.args:
            for k,v in request.args.items():
                reqstr += "&{}={}".format(str(k), str(v))
        key = namespace + ":" + path + reqstr
        cache_key = key.encode('utf-8')

        if get_flashed_messages():
            msgs = "|".join([msg[0] for msg in get_flashed_messages(with_categories=True)])
            cache_key += "/"+msgs

        return cache_key
    return gen_key


text:
"""Support for VersaSense sensor peripheral."""
from __future__ import annotations

import logging

from homeassistant.components.sensor import SensorEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import DOMAIN
from .const import (
    KEY_CONSUMER,
    KEY_IDENTIFIER,
    KEY_MEASUREMENT,
    KEY_PARENT_MAC,
    KEY_PARENT_NAME,
    KEY_UNIT,
)

_LOGGER = logging.getLogger(__name__)

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the sensor platform."""
    if discovery_info is None:
        return None

    consumer = hass.data[DOMAIN][KEY_CONSUMER]

    sensor_list = []

    for entity_info in discovery_info.values():
        peripheral = hass.data[DOMAIN][entity_info[KEY_PARENT_MAC]][
            entity_info[KEY_IDENTIFIER]
        ]
        parent_name = entity_info[KEY_PARENT_NAME]
        unit = entity_info[KEY_UNIT]
        measurement = entity_info[KEY_MEASUREMENT]

        sensor_list.append(
            VSensor(peripheral, parent_name, unit, measurement, consumer)
        )

    async_add_entities(sensor_list)

class VSensor(SensorEntity):
    """Representation of a Sensor."""

    def __init__(self, peripheral, parent_name, unit, measurement, consumer):
        """Initialize the sensor."""
        self._state = None
        self._available = True
        self._name = f"{parent_name} {measurement}"
        self._parent_mac = peripheral.parentMac
        self._identifier = peripheral.identifier
        self._unit = unit
        self._measurement = measurement
        self.consumer = consumer

    @property
    def unique_id(self):
        """Return the unique id of the sensor."""
        return f"{self._parent_mac}/{self._identifier}/{self._measurement}"

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def native_value(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def native_unit_of_measurement(self):
        """Return the unit of measurement."""
        return self._unit

    @property
    def available(self):
        """Return if the sensor is available."""
        return self._available

    async def async_update(self):
        """Fetch new state data for the sensor."""
        samples = await self.consumer.fetchPeripheralSample(
            None, self._identifier, self._parent_mac
        )

        if samples is not None:
            for sample in samples:
                if sample.measurement == self._measurement:
                    self._available = True
                    self._state = sample.value
                    break
        else:
            _LOGGER.error("Sample unavailable")
            self._available = False
            self._state = None


text:
$(function(){
  var $navbtn = $('#nav-btn'),
      $userbtn = $('#user-btn'),
      $exitlogin = $('#exit-login'),
      $navcont = $('#navigation-container'),
      $loadingPanel = $('#loading-panel'),
      $logincont = $('#login-container');

  var NavDisOn = {
    "opacity": 1,
    "right": "10%",
  },
  NavDisOff = {
    "opacity": 0,
    "right": "-10%"
  }
  var ctr = 0;
  var processing = false;

  //~~~~~~~~~~ Nav animation
  $navbtn.click(function(){
    if(0 === ctr % 2 && processing == false){
      ctr++;
      processing = true;
      //$loadingPanel.show();
      console.log(ctr + ": even");
      $navbtn.removeClass('not');
      $navbtn.addClass('active');
      $navcont.animate(NavDisOn, 1250, function(){
        console.log("open" + ": "+processing);
        processing = false;
        //$loadingPanel.hide();
      });
    }else if(1 ==ctr % 2 && processing == false){
      ctr++;
      processing = true;
      //$loadingPanel.show();
      $navbtn.removeClass('active');
      $navbtn.addClass('not');
        $navcont.animate(NavDisOff,550, function(){
          console.log('closed'+ ": "+processing);
          processing = false;
          //$loadingPanel.hide();
        });
      console.log(ctr + ": odd")
    }else{
      //$loadingPanel.show()
      processing == true;
      if(processing == false){
        alert('error!');
      }
    }
  })
  //~~~~~~~~ end of Nav animation
  //~~~~~~~~ Beginning userlogin
  var open = false;
  $userbtn.click(function(){
    if(open == false){
      console.log('we got clicks: ')
      $logincont.css({"display": "block"});
      open = true;
      if(open == true){
        $exitlogin.click(function(){
          console.log('clicked')
          $logincont.css({"display": "none"});
          open = false;
        });
      }
    }
  })
  //~~~~~~~ end of userlogin
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //end of navigation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //Beginning of goal list collapsable
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var $collapsableBtn = $("#activate-nd-list"),
    $fadeIn = $(".fadeIn"),
    $faded = $(".faded"),
    $theLi = $(".refLi"),
    $goalOl =$("#goal-jump-list");

    var collaspedOl = {
      "width": "10%",
      "height": "10%"
    },
    expandedOl = {
      "width": "15%",
      "height": "100%"
    };

    var clpsd = 0,
        inprog = false;
    $collapsableBtn.click(function(){
      $('#empty-li').remove();
      if(0 == clpsd % 2 && inprog == false){
        inprog = true;
        console.log('expand');
        $goalOl.children().show();
        $goalOl.animate(expandedOl, 500, function(){
          $goalOl.children().animate({"opacity": 1}, 1000, function(){
            inprog = false;
            $collapsableBtn.animate({color: '#91AA9D'}, 500, function(){
              console.log('completed');
            });
          });
        });
        clpsd++;
      }else if(1 === clpsd % 2 && inprog == false){
        inprog = true;
        console.log('clicked');
        $goalOl.children().animate({"opacity": 0}, 500, function(){
          $goalOl.children().hide();
          $goalOl.animate(collaspedOl, 500, function(){
            $collapsableBtn.animate({color: "#193441"}, 500, function(){
              console.log('reverted');
            });
          });
          inprog = false;
        });
        clpsd++;
      }else{
        console.log('inprogress, please wait');
      }
    });
    //
    //
    //
    var quotes = ["Computers make excellent and efficient servants, but I have no wish to serve under them.", "The needs of the many outweigh the needs of the few, or the one.", "Change is the essential process of all existence.", "It is curious how often you humans manage to obtain that which you do not want.", "If I seem insensitive to what you're going through, Captain, understand – it's the way I am.", "May I say that I have not thoroughly enjoyed serving with Humans? I find their illogic and foolish emotions a constant irritant."],
        grabQuote1 = [],
        grabQuote2 = [],
        dld = false;
    swal.setDefaults({
      confirmButtonColor: 'none'
    });
    $('#pf-title').on('click', function(){
      if(dld == false){
        $('#pf-title > a').removeAttr('id');
        swal({
          title: "You've downloaded my Résumé!",
          text: "Thank you for finding my site, I hope you enjoy it.",
          timer: 3000,
          showConfirmButton: false
        });
        dld = true;
      }else{
        if(dld == true){
          $('#pf-title > a').removeAttr("download").removeAttr('href');
        }
        grabQuote1 = quotes[Math.floor(Math.random() * quotes.length)];
        grabQuote2 = quotes[Math.floor(Math.random() * quotes.length)];
        if(grabQuote1 === grabQuote2){
          console.log('ran');
          grabQuote2 = quotes[Math.floor(Math.random() * quotes.length)];
          if(grabQuote2 === grabQuote1){
            console.log('ran inner');
            grabQuote2 = quotes[Math.floor(Math.random() * quotes.length)];
          }
        }

        swal({
          title: grabQuote1,
          text: grabQuote2,
          showConfirmButton: true
        })
      }
    })
    // $('#portfolio-container ul li:nth-child(2)').mouseover(function(){
    //   $('footer').animate({'opacity': 0}, 2000, function(){
    //       $('footer').remove();
    //   })
    // });
    // $(".quickRef").click(function(e){
    //   e.preventDefault();
    //   console.log('clicked');
    // });

  // console.log($(".refLi"));
  // function goToByScroll(id){
  //          // Reove "link" from the ID
  //        id = id.replace("link", "");
  //          // Scroll
  //        $('#goals-ul > li').animate({
  //            scrollTop: $("#"+id).offset().top},
  //            'slow');
  //    };
  // $("li > a").click(function() {
  //       // Prevent a page reload when a link is pressed
  //     e.preventDefault();
  //       // Call the scroll function
  //     console.log('clicked');
  //     goToByScroll($(this).attr("href"));
  // });
  // console.log('passed the shit');
});


text:
@(account: Option[model.Account])(implicit context: app.Context)
@import context._

  @if(account.nonEmpty && account.get.image.nonEmpty){

  } else {

      Gravatar is used

  }

@if(account.nonEmpty && account.get.image.nonEmpty){

    <input type="checkbox" name="clearImage"/> Clear image

}
<input type="hidden" name="fileId" value=""/>
@if(account.isEmpty || account.get.image.isEmpty){

}


text:
/** Automatically generated file. DO NOT MODIFY */
package com.neopixl.restpixlsample;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Genea gardnerii Gilkey

### Remarks
null


text:
require 'active_support/concern'
require 'devise_pkcs12_authenticatable/strategy'

module Devise
  module Models
    module PKCS12Authenticatable
      extend ActiveSupport::Concern
      include Devise::Models::DatabaseAuthenticatable

      def valid_common_name?(common_name)
        return false if self[::Devise.pkcs12_common_name_field].blank?
        self[::Devise.pkcs12_common_name_field] == common_name
      end

      module ClassMethods
        def find_for_pkcs12_authentication(conditions)
          find_for_authentication(conditions)
        end
      end
    end
  end
end


text:
package uk.ac.ebi.gxa.utils;

import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;

import java.util.Map;
import java.util.HashMap;

/**
 * @author pashky
 */
public class CollectionUtilTest {
    @Test
    public void test_makeMap() {
        Map<String,Integer> map = CollectionUtil.makeMap("a", 1, "b", 2, "c", 3, "d", 4);
        assertNotNull(map);
        assertEquals(4, map.size());
        assertEquals(1, map.get("a"), 0.0);
        assertEquals(2, map.get("b"), 0.0);
        assertEquals(3, map.get("c"), 0.0);
        assertEquals(4, map.get("d"), 0.0);
    }

    @Test
    public void test_addMap() {
        Map<String,Integer> map = new HashMap<String, Integer>();
        map.put("a", 1);
        map.put("b", 2);
        Map<String,Integer> map2 = CollectionUtil.addMap(map, "c", 3, "d", 4, "a", 5);
        assertNotNull(map2);
        assertEquals(4, map2.size());
        assertEquals(5, map2.get("a"), 0.0); // check replace
        assertEquals(2, map2.get("b"), 0.0);
        assertEquals(3, map2.get("c"), 0.0);
        assertEquals(4, map2.get("d"), 0.0);
    }
}


text:
<ruleset name="Modified-PSR2">
    <description>Description of your coding standard</description>

    <rule ref="PSR2">
        <exclude name="PSR2.Methods.MethodDeclaration.Underscore"/>
        <exclude name="PSR2.Classes.PropertyDeclaration.Underscore"/>
        <exclude name="Generic.Files.LineEndings.InvalidEOLChar"/>
    </rule>
</ruleset>


text:
package main

import (
	//	"fmt"
	"io"
	"io/ioutil"
	"github.com/mattimo/lmail"
	"log"
	"net/http"
	_ "net/http/pprof"
)

type PrintHandler struct {
	active bool
}

func (h *PrintHandler) HandleMail(mail *lmail.Mail) (int, error) {
	log.Printf("Handling new mail from %s", mail.From)
	for i := 0; i < 5; i++ {
		go func() {
			_, err := mail.MimeMessage()
			if err != nil {
				log.Println("Error getting mail:", err)
			}
			buf := make([]byte, 1024)
			mail.RawReader().Read(buf)
			_, err = io.Copy(ioutil.Discard, mail.RawReader())
			if err != nil {
				log.Println("Error reading message:", err)
			}
		}()
	}
	_, err := io.Copy(ioutil.Discard, mail.RawReader())
	if err != nil {
		log.Println("Error reading message:", err)
	}

	return 250, nil
}

func main() {
	log.Println("Starting lmail")
	// Start pprof for debugging purposus
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	// Get a new default Mux Handler that only routes mails to given addresses
	mux := lmail.NewDefaultMuxer()
	// get the Dummy Print Handler
	handler := &PrintHandler{}
	// Register the Print Handler with a given Address at the mux
	mux.AddRcptHandler("matti@localhost", handler)
	// Get a new Maildir instance in the current der
	maildir, err := lmail.NewMaildir("./maildir/")
	if err != nil {
		log.Fatal("Error during initialization:", err)
	}
	// Register The maildir at the muxer
	mux.AddRcptHandler("doof@localhost", maildir)
	// listen on port 2525 with the muxer
	lmail.ListenAndServe(":2525", mux)
}


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder
  xmlns:ui="urn:ui:com.google.gwt.uibinder"
  xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
  xmlns:bh="urn:import:org.gwtbootstrap3.client.ui.html"
  xmlns:g="urn:import:com.google.gwt.user.client.ui"
>
  <bh:Div>
    <b:Heading
      size="H4"
      text="Add More People"
      addStyleNames="margin-top-40 font-weight-700"
    />
    <bh:Paragraph marginBottom="10">
      <bh:Italic>
        Search for a Synapse user or team below.  Click on the user or team
        name, then adjust their access level above before clicking Save.
      </bh:Italic>
    </bh:Paragraph>
    <bh:Div>
      <bh:Div marginBottom="20">
        <b:FormGroup>
          <b:FormLabel>Name</b:FormLabel>
          <bh:Div ui:field="suggestBoxPanel" />
        </b:FormGroup>
      </bh:Div>
      <bh:Div
        addStyleNames="flexcontainer-row flexcontainer-justify-space-between flexcontainer-align-items-center"
        marginBottom="20"
      >
        <b:Button ui:field="makePublicButton" type="DEFAULT" icon="GLOBE">
          Make Public
        </b:Button>
        <b:Tooltip placement="BOTTOM" ui:field="notifyTooltip">
          <b:CheckBox
            ui:field="notifyPeopleCheckBox"
            addStyleNames="margin-0-imp"
          >
            Notify people via email
          </b:CheckBox>
        </b:Tooltip>
      </bh:Div>
    </bh:Div>
  </bh:Div>
</ui:UiBinder>


text:
using System;
using Farada.TestDataGeneration.ValueProviders.Context;
using JetBrains.Annotations;

namespace Farada.TestDataGeneration.ValueProviders
{
  //REVIEW: Is this ok?
  public abstract class RangedValueProvider<TMember> : ValueProvider<TMember, RangedValueProviderContext<TMember>>
  {
    protected override RangedValueProviderContext<TMember> CreateContext (ValueProviderObjectContext objectContext)
    {
      return new RangedValueProviderContext<TMember> (objectContext, CreateConstraints(objectContext));
    }

    protected abstract GenericRangeConstraints<TMember> CreateConstraints (ValueProviderObjectContext objectContext);
  }

  public abstract class AttributeBasedRangedValueProvider<TMember, TAttribute>:RangedValueProvider<TMember>
      where TAttribute : Attribute
  {
    protected override sealed GenericRangeConstraints<TMember> CreateConstraints(ValueProviderObjectContext objectContext)
    {
      var attribute = objectContext.Member?.GetCustomAttribute<TAttribute>();
      if (attribute == null)
        throw new ArgumentException ($"Did not find {nameof (TAttribute)} attribute on '{objectContext.Member}'.");

      return CreateConstraints (attribute);
    }

    protected abstract GenericRangeConstraints<TMember> CreateConstraints (TAttribute attribute);
  }

  public abstract class DirectRangedValueProvider<TMember>:RangedValueProvider<TMember>
  {
    private readonly TMember _from;
    private readonly TMember _to;

    protected DirectRangedValueProvider (TMember from, TMember to)
    {
      _from = from;
      _to = to;
    }

    protected override GenericRangeConstraints<TMember> CreateConstraints (ValueProviderObjectContext objectContext)
    {
      return new GenericRangeConstraints<TMember> (_from, _to);
    }
  }

  public class GenericRangeConstraints<TMember>
  {
    public TMember From { get; }
    public TMember To { get; }
    public GenericRangeConstraints (TMember from, TMember to)
    {
      From = from;
      To = to;
    }
  }

  public class RangedValueProviderContext<TMember> : ValueProviderContext<TMember>
  {
    public GenericRangeConstraints<TMember> RangeConstraints { get; }

    public RangedValueProviderContext ([NotNull] ValueProviderObjectContext objectContext, GenericRangeConstraints<TMember>  rangeConstraints)
        : base(objectContext)
    {
      RangeConstraints = rangeConstraints;
    }
  }
}


text:
import { Component, Input } from '@angular/core';

@Component({
    selector: 'toggle-button-group',
    templateUrl: 'toggle-button-group.component.html',
    styleUrls: ['toggle-button-group.component.scss']
})
export class ToggleButtonGroupComponent {
    @Input('items') items: string[];
    @Input('name') name: string;

    constructor() { }
}


text:
package testPullUpGen.test18.expectedresult;

public class B extends S <String> {
    @Override
    <T> String m(T i){
        return "foo";
    }
}


text: Copy icon by Sergey Ershov, Bold icons family Multimedia pack, from iconfinder.com, Creative Commons (Attribution 3.0 Unported)


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false">
	<display-name>Web System</display-name>

	<description>code generator site</description>

	<session-config>
		<session-timeout>-1</session-timeout>
	</session-config>

	<welcome-file-list>
		<welcome-file>/index.html</welcome-file>
	</welcome-file-list>
</web-app>


text:
Timebox
=======

Timebox is a simplistic time logging tool.

Requirements
------------

.NET Framework 2.0
SQLite3


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Pogonia vargasii C.Schweinf.

### Remarks
null


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/embedding/browser/webBrowser/nsIWebBrowserFocus.idl
 */

#ifndef __gen_nsIWebBrowserFocus_h__
#define __gen_nsIWebBrowserFocus_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMWindow; /* forward declaration */

class nsIDOMElement; /* forward declaration */

/* starting interface:    nsIWebBrowserFocus */
#define NS_IWEBBROWSERFOCUS_IID_STR "9c5d3c58-1dd1-11b2-a1c9-f3699284657a"

#define NS_IWEBBROWSERFOCUS_IID \
  {0x9c5d3c58, 0x1dd1, 0x11b2, \
    { 0xa1, 0xc9, 0xf3, 0x69, 0x92, 0x84, 0x65, 0x7a }}

/**
 * nsIWebBrowserFocus
 * Interface that embedders use for controlling and interacting
 * with the browser focus management. The embedded browser can be focused by
 * clicking in it or tabbing into it. If the browser is currently focused and
 * the embedding application's top level window is disabled, deactivate() must
 * be called, and activate() called again when the top level window is
 * reactivated for the browser's focus memory to work correctly.
 */
class NS_NO_VTABLE NS_SCRIPTABLE nsIWebBrowserFocus : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWEBBROWSERFOCUS_IID)

  /**
   * MANDATORY
   * activate() is a mandatory call that must be made to the browser
   * when the embedding application's window is activated *and* the
   * browser area was the last thing in focus.  This method can also be called
   * if the embedding application wishes to give the browser area focus,
   * without affecting the currently focused element within the browser.
   *
   * @note
   * If you fail to make this call, mozilla focus memory will not work
   * correctly.
   */
  /* void activate (); */
  NS_SCRIPTABLE NS_IMETHOD Activate(void) = 0;

  /**
   * MANDATORY
   * deactivate() is a mandatory call that must be made to the browser
   * when the embedding application's window is deactivated *and* the
   * browser area was the last thing in focus.  On non-windows platforms,
   * deactivate() should also be called when focus moves from the browser
   * to the embedding chrome.
   *
   * @note
   * If you fail to make this call, mozilla focus memory will not work
   * correctly.
   */
  /* void deactivate (); */
  NS_SCRIPTABLE NS_IMETHOD Deactivate(void) = 0;

  /**
   * Give the first element focus within mozilla
   * (i.e. TAB was pressed and focus should enter mozilla)
   */
  /* void setFocusAtFirstElement (); */
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtFirstElement(void) = 0;

  /**
   * Give the last element focus within mozilla
   * (i.e. SHIFT-TAB was pressed and focus should enter mozilla)
   */
  /* void setFocusAtLastElement (); */
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtLastElement(void) = 0;

  /**
   * The currently focused nsDOMWindow when the browser is active,
   * or the last focused nsDOMWindow when the browser is inactive.
   */
  /* attribute nsIDOMWindow focusedWindow; */
  NS_SCRIPTABLE NS_IMETHOD GetFocusedWindow(nsIDOMWindow **aFocusedWindow) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetFocusedWindow(nsIDOMWindow *aFocusedWindow) = 0;

  /**
   * The currently focused nsDOMElement when the browser is active,
   * or the last focused nsDOMElement when the browser is inactive.
   */
  /* attribute nsIDOMElement focusedElement; */
  NS_SCRIPTABLE NS_IMETHOD GetFocusedElement(nsIDOMElement **aFocusedElement) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetFocusedElement(nsIDOMElement *aFocusedElement) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIWebBrowserFocus, NS_IWEBBROWSERFOCUS_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIWEBBROWSERFOCUS \
  NS_SCRIPTABLE NS_IMETHOD Activate(void); \
  NS_SCRIPTABLE NS_IMETHOD Deactivate(void); \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtFirstElement(void); \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtLastElement(void); \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedWindow(nsIDOMWindow **aFocusedWindow); \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedWindow(nsIDOMWindow *aFocusedWindow); \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedElement(nsIDOMElement **aFocusedElement); \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedElement(nsIDOMElement *aFocusedElement);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIWEBBROWSERFOCUS(_to) \
  NS_SCRIPTABLE NS_IMETHOD Activate(void) { return _to Activate(); } \
  NS_SCRIPTABLE NS_IMETHOD Deactivate(void) { return _to Deactivate(); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtFirstElement(void) { return _to SetFocusAtFirstElement(); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtLastElement(void) { return _to SetFocusAtLastElement(); } \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedWindow(nsIDOMWindow **aFocusedWindow) { return _to GetFocusedWindow(aFocusedWindow); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedWindow(nsIDOMWindow *aFocusedWindow) { return _to SetFocusedWindow(aFocusedWindow); } \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedElement(nsIDOMElement **aFocusedElement) { return _to GetFocusedElement(aFocusedElement); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedElement(nsIDOMElement *aFocusedElement) { return _to SetFocusedElement(aFocusedElement); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIWEBBROWSERFOCUS(_to) \
  NS_SCRIPTABLE NS_IMETHOD Activate(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Activate(); } \
  NS_SCRIPTABLE NS_IMETHOD Deactivate(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Deactivate(); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtFirstElement(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFocusAtFirstElement(); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusAtLastElement(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFocusAtLastElement(); } \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedWindow(nsIDOMWindow **aFocusedWindow) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFocusedWindow(aFocusedWindow); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedWindow(nsIDOMWindow *aFocusedWindow) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFocusedWindow(aFocusedWindow); } \
  NS_SCRIPTABLE NS_IMETHOD GetFocusedElement(nsIDOMElement **aFocusedElement) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFocusedElement(aFocusedElement); } \
  NS_SCRIPTABLE NS_IMETHOD SetFocusedElement(nsIDOMElement *aFocusedElement) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFocusedElement(aFocusedElement); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsWebBrowserFocus : public nsIWebBrowserFocus
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIWEBBROWSERFOCUS

  nsWebBrowserFocus();

private:
  ~nsWebBrowserFocus();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsWebBrowserFocus, nsIWebBrowserFocus)

nsWebBrowserFocus::nsWebBrowserFocus()
{
  /* member initializers and constructor code */
}

nsWebBrowserFocus::~nsWebBrowserFocus()
{
  /* destructor code */
}

/* void activate (); */
NS_IMETHODIMP nsWebBrowserFocus::Activate()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void deactivate (); */
NS_IMETHODIMP nsWebBrowserFocus::Deactivate()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setFocusAtFirstElement (); */
NS_IMETHODIMP nsWebBrowserFocus::SetFocusAtFirstElement()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setFocusAtLastElement (); */
NS_IMETHODIMP nsWebBrowserFocus::SetFocusAtLastElement()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsIDOMWindow focusedWindow; */
NS_IMETHODIMP nsWebBrowserFocus::GetFocusedWindow(nsIDOMWindow **aFocusedWindow)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsWebBrowserFocus::SetFocusedWindow(nsIDOMWindow *aFocusedWindow)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsIDOMElement focusedElement; */
NS_IMETHODIMP nsWebBrowserFocus::GetFocusedElement(nsIDOMElement **aFocusedElement)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsWebBrowserFocus::SetFocusedElement(nsIDOMElement *aFocusedElement)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIWebBrowserFocus_h__ */


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Like based votes for any content
 */
class BxDolVoteReactions extends BxTemplVote
{
    protected static $_sCounterStyleDivided = 'divided';
    protected static $_sCounterStyleCompound = 'compound';

    protected $_sMenuDoVote; //--- Do vote (reaction)  menu name.

    protected $_sDataList; //--- Reactions list name.
    protected $_aDataList; //--- Reactions list with all reactions.

    protected $_sDefault; //--- Default reaction name.

    public function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
    {
        parent::__construct($sSystem, $iId, $iInit, $oTemplate);

        $this->_oQuery = new BxDolVoteReactionsQuery($this);
        $this->_sType = BX_DOL_VOTE_TYPE_REACTIONS;

        $this->_sMenuDoVote = 'sys_vote_reactions_do';

        $this->_sDataList = 'sys_vote_reactions';
        $this->_aDataList = array();

        $this->_sDefault = 'default';
    }

    public function init($iId)
    {
        if(!parent::init($iId))
            return false;

        $aReactions = BxDolFormQuery::getDataItems($this->_sDataList, false, BX_DATA_VALUES_ALL);

        foreach($aReactions as $sReaction => $aReaction) {
            $aData = !empty($aReaction['Data']) ? unserialize($aReaction['Data']) : array();

            $this->_aDataList[$sReaction] = array(
                'name' => $sReaction,
                'title' => $aReaction['LKey'],
                'title_aux' => $aReaction['LKey2'],
                'icon' => isset($aData['icon']) ? $aData['icon'] : '',
                'color' => isset($aData['color']) ? $aData['color'] : '',
                'weight' => isset($aData['weight']) ? $aData['weight'] : 1,
            );
        }

        if(!empty($this->_aDataList)) {
            $this->_aDataList[$this->_sDefault] = reset($this->_aDataList);
            $this->_aDataList[$this->_sDefault]['color'] = '';
        }
    }
    /**
     * Interface functions for outer usage
     */
    public function getValue()
    {
        return (int)$this->_aSystem['min_value'];
    }

    public function getDefault()
    {
        return $this->_sDefault;
    }

    public function getReaction($sName)
    {
        if(empty($this->_aDataList))
            $this->getReactions();

        return !empty($this->_aDataList[$sName]) ? $this->_aDataList[$sName] : false;
    }

    public function getReactions($bFullInfo = false)
    {
        return $bFullInfo ? $this->_aDataList : array_keys($this->_aDataList);
    }

    public function getTrackBy($aParams)
    {
        return $this->_oQuery->getTrackBy($aParams);
    }

    public function getIcon($sReaction, $bWithColor = true)
    {
        $aReaction = isset($this->_aDataList[$sReaction]) ? $this->_aDataList[$sReaction] : $this->_aDataList[$this->_sDefault];

    	return $aReaction['icon'] . ($bWithColor && !empty($aReaction['color']) ? ' ' . $aReaction['color'] : '');
    }

    /**
     * Actions functions
     */
    public function actionGetDoVotePopup()
    {
        if(!$this->isEnabled())
           return '';

        return $this->_getDoVotePopup((int)bx_get('value'));
    }

    public function actionGetVotedBy()
    {
        if(!$this->isEnabled())
           return '';

        $aParams = array();

        $sReaction = bx_get('reaction');
        if($sReaction !== false) {
            $sReaction = bx_process_input($sReaction);

            $aReactions = $this->getReactions();
            if(!in_array($sReaction, $aReactions))
                $sReaction = $this->_sDefault;

            $aParams['reaction'] = $sReaction;
        }

        return $this->_getVotedBy($aParams);
    }

    /**
     * Internal functions
     */
    protected function _isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted)
    {
        return $bVoted && !$this->isUndo();
    }

    protected function _isCount($aVote = array())
    {
        if(empty($aVote))
            $aVote = $this->_getVote();

        foreach($aVote as $sKey => $mixedValue)
            if(substr($sKey, 0, 5) == 'count' && (int)$mixedValue != 0)
                return true;

        return false;
    }

    protected function _getVoteData()
    {
        $aData = parent::_getVoteData();
        if($aData === false)
            return false;

        $sReaction = bx_get('reaction');
        if($sReaction === false)
            return false;

        $aData['reaction'] = bx_process_input($sReaction);
        return $aData;
    }

    protected function _returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bVoted, $aParams = array())
    {
        $aReactions = $this->getReactions();
        $sReaction = $aData['reaction'];

        $bUndo = $this->isUndo();
        $bDisabled = $bVoted && !$bUndo;

        $aVote = $this->_getVote($iObjectId, true);
        $aTrack = $bVoted ? $this->_getTrack($iObjectId, $iAuthorId) : array();

        $sJsClick = '';
        if(!$bDisabled)
            $sJsClick = $bVoted && $bUndo ? $this->getJsClickDo($sReaction) : $this->getJsClick();

        $iTotalC = $iTotalS = 0;
        foreach($aReactions as $sName) {
            $iTotalC += (int)$aVote['count_' . $sName];
            $iTotalS += (int)$aVote['sum_' . $sName];
        }
        $fTotalR = $iTotalC != 0 ? round($iTotalS / $iTotalC, 2) : 0;

        $iCount = (int)$aVote['count_' . $sReaction];
        $aResult = array(
            'code' => 0,
            'reaction' => $sReaction,
            'rate' => $aVote['rate_' . $sReaction],
            'count' => $iCount,
            'countf' => $iCount > 0 ? $this->_getCounterLabel($iCount, array('reaction' => $sReaction)) : '',
            'label_icon' => $this->_getIconDoWithTrack($bVoted, $aTrack),
            'label_title' => _t($this->_getTitleDoWithTrack($bVoted, $aTrack)),
            'label_click' => $sJsClick,
            'disabled' => $bVoted && !$this->isUndo(),
            'total' => array(
                'rate' => $fTotalR,
                'count' => $iTotalC,
                'countf' => $iTotalC > 0 ? $this->_getCounterLabel($iTotalC, array('show_counter_label_icon' => false, 'reaction' => '')) : '',
            )
        );

        return $aResult;
    }

    protected function _getIconDoWithTrack($bVoted, $aTrack = array())
    {
        $sReaction = $bVoted ? $aTrack['reaction'] : $this->_sDefault;

    	return $this->getIcon($sReaction);
    }

    protected function _getTitleDoWithTrack($bVoted, $aTrack = array())
    {
        $sReaction = $bVoted ? $aTrack['reaction'] : $this->_sDefault;

    	return $this->_aDataList[$sReaction]['title'];
    }

    protected function _getTitleDoBy($aParams = array())
    {
        if(isset($aParams['show_counter_style']) && $aParams['show_counter_style'] == self::$_sCounterStyleCompound)
            return _t('_vote_do_by_reactions');

        $sReaction = !empty($aParams['reaction']) ? $aParams['reaction'] : $this->_sDefault;
    	return _t('_vote_do_by_x_reaction', _t($this->_aDataList[$sReaction]['title']));
    }
}

/** @} */


text:
export * from './general-constants';
export * from './bg-constants';


text:
<?php

namespace Nilead\OmniNganLuong\Message;

use Nilead\OmniNganLuong\Message\CaptureRequest;
use Omnipay\Tests\TestCase;

class CaptureRequestTest extends TestCase
{
    /**
     * @var \Nilead\OmniNganLuong\Message\CaptureRequest
     */
    private $request;

    public function setUp()
    {
        $client = $this->getHttpClient();
        $request = $this->getHttpRequest();
        $this->request = new CaptureRequest($client, $request);
    }

    public function testGetData()
    {
        $this->request->setTransactionReference('ABC-123');
        $this->request->setAmount('1.23');
        $this->request->setCurrency('USD');
        $this->request->setUsername('testuser');
        $this->request->setPassword('testpass');
        $this->request->setSignature('SIG');
        $this->request->setSubject('SUB');

        $expected = array();
        $expected['METHOD'] = 'DoCapture';
        $expected['AUTHORIZATIONID'] = 'ABC-123';
        $expected['AMT'] = '1.23';
        $expected['CURRENCYCODE'] = 'USD';
        $expected['COMPLETETYPE'] = 'Complete';
        $expected['USER'] = 'testuser';
        $expected['PWD'] = 'testpass';
        $expected['SIGNATURE'] = 'SIG';
        $expected['SUBJECT'] = 'SUB';
        $expected['VERSION'] = CaptureRequest::API_VERSION;

        $this->assertEquals($expected, $this->request->getData());
    }
}


text:
which rsvg-convert || brew install librsvg

CACHEBREAKER="6-2018"

for VERSION in release beta dev; do
    rm -rf "./$VERSION"
    rm -rf "./$VERSION-extension"
    mkdir "$VERSION"
    mkdir "$VERSION-extension"
    rsvg-convert -w 16 -h 16 -o "$VERSION-extension/icon16.png" "favicon-$VERSION.svg"
    rsvg-convert -w 16 -h 16 -o "$VERSION/favicon-16x16.png" "favicon-$VERSION.svg"
    rsvg-convert -w 19 -h 19 -o "$VERSION-extension/icon19.png" "favicon-$VERSION.svg"
    rsvg-convert -w 32 -h 32 -o "$VERSION/favicon-32x32.png" "favicon-$VERSION.svg"
    rsvg-convert -w 38 -h 38 -o "$VERSION-extension/icon38.png" "favicon-$VERSION.svg"
    rsvg-convert -w 48 -h 48 -o "$VERSION-extension/icon48.png" "favicon-$VERSION.svg"
    rsvg-convert -w 96 -h 96 -o "$VERSION/favicon-96x96.png" "favicon-$VERSION.svg"
    rsvg-convert -w 128 -h 128 -o "$VERSION-extension/icon128.png" "favicon-$VERSION.svg"
    rsvg-convert -w 180 -h 180 -o "$VERSION/apple-touch-icon.png" "apple-touch-icon-$VERSION.svg"
    rsvg-convert -w 180 -h 180 -o "$VERSION/apple-touch-icon-$CACHEBREAKER.png" "apple-touch-icon-$VERSION.svg"
    rsvg-convert -w 192 -h 192 -o "$VERSION/android-chrome-192x192-$CACHEBREAKER.png" "android-icon-$VERSION.svg"
    rsvg-convert -w 512 -h 512 -o "$VERSION/android-chrome-512x512-$CACHEBREAKER.png" "android-icon-$VERSION.svg"
done