示例#1
0
文件: 2.ts 项目: Tatamo/comp
import * as fs from "fs";

let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const [d, x] = input[1].split(" ").map((x: string): number => +x);
const a: Array<number> = [];
for (let i = 0; i < n; i++) {
	a.push(+input[i + 2]);
}

let sum = x;
for (const delta of a) {
	sum += 1 + Math.floor((d - 1) / delta);
}

console.log(sum);
function readFileContents(testCase: string, fileName: string): string
{
	const fullFileName = getCaseFileName(testCase, fileName);
	return fs.readFileSync(fullFileName).toString();
}
示例#3
0
async function _renderUniversal(
  options: BuildWebpackAppShellSchema,
  context: BuilderContext,
  browserResult: BrowserBuilderOutput,
  serverResult: ServerBuilderOutput,
): Promise<BrowserBuilderOutput> {
  const browserIndexOutputPath = path.join(browserResult.outputPath || '', 'index.html');
  const indexHtml = fs.readFileSync(browserIndexOutputPath, 'utf8');
  const serverBundlePath = await _getServerModuleBundlePath(options, context, serverResult);

  const root = context.workspaceRoot;
  requireProjectModule(root, 'zone.js/dist/zone-node');

  const renderModuleFactory = requireProjectModule(
    root,
    '@angular/platform-server',
  ).renderModuleFactory;
  const AppServerModuleNgFactory = require(serverBundlePath).AppServerModuleNgFactory;
  const outputIndexPath = options.outputIndexPath
    ? path.join(root, options.outputIndexPath)
    : browserIndexOutputPath;

  // Render to HTML and overwrite the client index file.
  const html = await renderModuleFactory(AppServerModuleNgFactory, {
    document: indexHtml,
    url: options.route,
  });

  fs.writeFileSync(outputIndexPath, html);

  const browserTarget = targetFromTargetString(options.browserTarget);
  const rawBrowserOptions = await context.getTargetOptions(browserTarget);
  const browserBuilderName = await context.getBuilderNameForTarget(browserTarget);
  const browserOptions = await context.validateOptions<JsonObject & BrowserBuilderSchema>(
    rawBrowserOptions,
    browserBuilderName,
  );

  if (browserOptions.serviceWorker) {
    const host = new NodeJsSyncHost();
    // Create workspace.
    const registry = new schema.CoreSchemaRegistry();
    registry.addPostTransform(schema.transforms.addUndefinedDefaults);

    const workspace = await experimental.workspace.Workspace.fromPath(
      host,
      normalize(context.workspaceRoot),
      registry,
    );
    const projectName = context.target ? context.target.project : workspace.getDefaultProjectName();

    if (!projectName) {
      throw new Error('Must either have a target from the context or a default project.');
    }
    const projectRoot = resolve(
      workspace.root,
      normalize(workspace.getProject(projectName).root),
    );

    await augmentAppWithServiceWorker(
      host,
      normalize(root),
      projectRoot,
      join(normalize(root), browserOptions.outputPath),
      browserOptions.baseHref || '/',
      browserOptions.ngswConfigPath,
    );
  }

  return browserResult;
}
示例#4
0
文件: test.ts 项目: IllusionMH/tslint
export function runTest(testDirectory: string, rulesDirectory?: string | string[]): TestResult {
    const filesToLint = glob.sync(path.join(testDirectory, `**/*${MARKUP_FILE_EXTENSION}`));
    const tslintConfig = Linter.findConfiguration(path.join(testDirectory, "tslint.json"), "").results;
    const tsConfig = path.join(testDirectory, "tsconfig.json");
    let compilerOptions: ts.CompilerOptions = { allowJs: true };
    const hasConfig = fs.existsSync(tsConfig);
    if (hasConfig) {
        const {config, error} = ts.readConfigFile(tsConfig, ts.sys.readFile);
        if (error !== undefined) {
            throw new Error(JSON.stringify(error));
        }

        const parseConfigHost = {
            fileExists: fs.existsSync,
            readDirectory: ts.sys.readDirectory,
            readFile: (file: string) => fs.readFileSync(file, "utf8"),
            useCaseSensitiveFileNames: true,
        };
        compilerOptions = ts.parseJsonConfigFileContent(config, parseConfigHost, testDirectory).options;
    }
    const results: TestResult = { directory: testDirectory, results: {} };

    for (const fileToLint of filesToLint) {
        const isEncodingRule = path.basename(testDirectory) === "encoding";

        const fileCompileName = denormalizeWinPath(path.resolve(fileToLint.replace(/\.lint$/, "")));
        let fileText = isEncodingRule ? readBufferWithDetectedEncoding(fs.readFileSync(fileToLint)) : fs.readFileSync(fileToLint, "utf-8");
        const tsVersionRequirement = parse.getTypescriptVersionRequirement(fileText);
        if (tsVersionRequirement !== undefined) {
            const tsVersion = new semver.SemVer(ts.version);
            // remove prerelease suffix when matching to allow testing with nightly builds
            if (!semver.satisfies(`${tsVersion.major}.${tsVersion.minor}.${tsVersion.patch}`, tsVersionRequirement)) {
                results.results[fileToLint] = {
                    requirement: tsVersionRequirement,
                    skipped: true,
                };
                continue;
            }
            // remove the first line from the file before continuing
            const lineBreak = fileText.search(/\n/);
            fileText = lineBreak === -1 ? "" : fileText.substr(lineBreak + 1);
        }
        const fileTextWithoutMarkup = parse.removeErrorMarkup(fileText);
        const errorsFromMarkup = parse.parseErrorsFromMarkup(fileText);

        let program: ts.Program | undefined;
        if (hasConfig) {
            const compilerHost: ts.CompilerHost = {
                fileExists: (file) => file === fileCompileName || fs.existsSync(file),
                getCanonicalFileName: (filename) => filename,
                getCurrentDirectory: () => process.cwd(),
                getDefaultLibFileName: () => ts.getDefaultLibFileName(compilerOptions),
                getDirectories: (dir) => fs.readdirSync(dir),
                getNewLine: () => "\n",
                getSourceFile(filenameToGet) {
                    const target = compilerOptions.target === undefined ? ts.ScriptTarget.ES5 : compilerOptions.target;
                    if (filenameToGet === ts.getDefaultLibFileName(compilerOptions)) {
                        const fileContent = fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions), "utf8");
                        return ts.createSourceFile(filenameToGet, fileContent, target);
                    } else if (denormalizeWinPath(filenameToGet) === fileCompileName) {
                        return ts.createSourceFile(filenameToGet, fileTextWithoutMarkup, target, true);
                    }
                    const text = fs.readFileSync(filenameToGet, "utf8");
                    return ts.createSourceFile(filenameToGet, text, target, true);
                },
                readFile: (x) => x,
                useCaseSensitiveFileNames: () => true,
                writeFile: () => null,
            };

            program = ts.createProgram([fileCompileName], compilerOptions, compilerHost);
        }

        const lintOptions = {
            fix: false,
            formatter: "prose",
            formattersDirectory: "",
            rulesDirectory,
        };
        const linter = new Linter(lintOptions, program);
        // Need to use the true path (ending in '.lint') for "encoding" rule so that it can read the file.
        linter.lint(isEncodingRule ? fileToLint : fileCompileName, fileTextWithoutMarkup, tslintConfig);
        const failures = linter.getResult().failures;
        const errorsFromLinter: LintError[] = failures.map((failure) => {
            const startLineAndCharacter = failure.getStartPosition().getLineAndCharacter();
            const endLineAndCharacter = failure.getEndPosition().getLineAndCharacter();

            return {
                endPos: {
                    col: endLineAndCharacter.character,
                    line: endLineAndCharacter.line,
                },
                message: failure.getFailure(),
                startPos: {
                    col: startLineAndCharacter.character,
                    line: startLineAndCharacter.line,
                },
            };
        });

        // test against fixed files
        let fixedFileText = "";
        let newFileText = "";
        try {
            const fixedFile = fileToLint.replace(/\.lint$/, FIXES_FILE_EXTENSION);
            const stat = fs.statSync(fixedFile);
            if (stat.isFile()) {
                fixedFileText = fs.readFileSync(fixedFile, "utf8");
                const fixes = mapDefined(failures, (f) => f.getFix());
                newFileText = Replacement.applyFixes(fileTextWithoutMarkup, fixes);
            }
        } catch (e) {
            fixedFileText = "";
            newFileText = "";
        }

        results.results[fileToLint] = {
            errorsFromLinter,
            errorsFromMarkup,
            fixesFromLinter: newFileText,
            fixesFromMarkup: fixedFileText,
            markupFromLinter: parse.createMarkupFromErrors(fileTextWithoutMarkup, errorsFromMarkup),
            markupFromMarkup: parse.createMarkupFromErrors(fileTextWithoutMarkup, errorsFromLinter),
            skipped: false,
        };
    }

    return results;
}
// magnet uri with torrent name
parseTorrent('magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves%20of%20Grass%20by%20Walt%20Whitman.epub')
// { xt: 'urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
//   dn: 'Leaves of Grass by Walt Whitman.epub',
//   infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
//   name: 'Leaves of Grass by Walt Whitman.epub' }

// magnet uri with trackers
parseTorrent('magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&tr=http%3A%2F%2Ftracker.example.com%2Fannounce')
// { xt: 'urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
//   tr: 'http://tracker.example.com/announce',
//   infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
//   announce: [ 'http://tracker.example.com/announce' ] }

// .torrent file (as a Buffer)
parseTorrent(fs.readFileSync(__dirname + '/torrents/leaves.torrent'))
// { info:
//    { length: 362017,
//      name: <Buffer 4c 65 61 76 65 73 20 6f 66 20 47 72 61 73 73 20 62 79 20 57 61 6c 74 20 57 68 69 74 6d 61 6e 2e 65 70 75 62>,
//      'piece length': 16384,
//      pieces: <Buffer 1f 9c 3f 59 be ec 07 97 15 ec 53 32 4b de 85 69 e4 a0 b4 eb ec 42 30 7d 4c e5 55 7b 5d 39 64 c5 ef 55 d3 54 cf 4a 6e cc 7b f1 bc af 79 d1 1f a5 e0 be 06 ...> },
//   infoBuffer: <Buffer 64 36 3a 6c 65 6e 67 74 68 69 33 36 32 30 31 37 65 34 3a 6e 61 6d 65 33 36 3a 4c 65 61 76 65 73 20 6f 66 20 47 72 61 73 73 20 62 79 20 57 61 6c 74 20 57 ...>,
//   infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36',
//   name: 'Leaves of Grass by Walt Whitman.epub',
//   private: false,
//   created: Thu Aug 01 2013 06:27:46 GMT-0700 (PDT),
//   comment: 'Downloaded from http://TheTorrent.org',
//   announce:
//    [ 'http://tracker.example.com/announce' ],
//   urlList: [],
//   files:
function getExtractor(fileName: string, password?: string) {
  let buf = fs.readFileSync(`./testFiles/${fileName}`);
  let arrBuf = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  return unrar.createExtractorFromData(arrBuf, password);
}
示例#7
0
 private _getFile(): any {
   const contents = fs.readFileSync(this.p, 'utf8');
   return JSON.parse(contents);
 }
示例#8
0
文件: userdump.ts 项目: icecondor/api
require('source-map-support').install()
import * as Db from '../lib/db-lmdb'
import * as fs from 'fs'

let settings = JSON.parse(fs.readFileSync("settings.json", 'utf8'))

console.log('storage', settings.storage)
let db = new Db.Db(settings.storage)

let email = process.argv[2]
if (email) {
  console.log('user dump', email)
  db.connect(async () => {
    let user
    try {
      user = await db.find_user_by({ email: email })
    } catch (e) {
      try {
        user = await db.find_user_by({ username: email })
      } catch (e) {
      }
    }
    if (user) {
      console.log(JSON.stringify(user, null, 2))
      let friending = await db.friending_me(user.id)
      console.log(user.friends.length, 'friends', friending.length, 'friending')
    } else {
      console.log(email, 'not found')
    }
  })
} else {
    "Do unto others as you would have them do unto you.",
    assert.ifError);

fs.write(1234, "test");

fs.writeFile("Harry Potter",
    "\"You be wizzing, Harry,\" jived Dumbledore.",
    {
        encoding: "ascii"
    },
    assert.ifError);

var content: string,
    buffer: Buffer;

content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', {encoding : 'utf8'});
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', {flag : 'r'});
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data);

class Networker extends events.EventEmitter {
    constructor() {
        super();

        this.emit("mingling");
    }
}
示例#10
0
QUnit.test("extract multline tag text", function () {
    var comments: d2t.DocComment[] = new d2t.Parser(fs.readFileSync("test/fixtures/comment2.js", 'utf8')).exec();
    QUnit.scapeEqual(comments[0].tags[1].text, '{String} desc A description of the assertion. This will become\r\n\
    the text of the Error thrown if the assertion fails.');
});