file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
service.py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os import errno import subprocess from subprocess import PIPE import time from selenium.common.exceptions import WebDriverException from selenium.webdriver.common import utils class Service(object): """ Object that manages the starting and stopping of the ChromeDriver """ def __init__(self, executable_path, port=0, service_args=None, log_path=None, env=None):
def start(self): """ Starts the ChromeDriver Service. :Exceptions: - WebDriverException : Raised either when it cannot find the executable, when it does not have permissions for the executable, or when it cannot connect to the service. - Possibly other Exceptions in rare circumstances (OSError, etc). """ env = self.env or os.environ try: self.process = subprocess.Popen([ self.path, "--port=%d" % self.port] + self.service_args, env=env, stdout=PIPE, stderr=PIPE) except OSError as err: docs_msg = "Please see " \ "https://sites.google.com/a/chromium.org/chromedriver/home" if err.errno == errno.ENOENT: raise WebDriverException( "'%s' executable needs to be in PATH. %s" % ( os.path.basename(self.path), docs_msg) ) elif err.errno == errno.EACCES: raise WebDriverException( "'%s' executable may have wrong permissions. %s" % ( os.path.basename(self.path), docs_msg) ) else: raise count = 0 while not utils.is_connectable(self.port): count += 1 time.sleep(1) if count == 30: raise WebDriverException("Can not connect to the '" + os.path.basename(self.path) + "'") @property def service_url(self): """ Gets the url of the ChromeDriver Service """ return "http://localhost:%d" % self.port def stop(self): """ Tells the ChromeDriver to stop and cleans up the process """ #If its dead dont worry if self.process is None: return #Tell the Server to die! try: from urllib import request as url_request except ImportError: import urllib2 as url_request url_request.urlopen("http://127.0.0.1:%d/shutdown" % self.port) count = 0 while utils.is_connectable(self.port): if count == 30: break count += 1 time.sleep(1) #Tell the Server to properly die in case try: if self.process: self.process.stdout.close() self.process.stderr.close() self.process.kill() self.process.wait() except OSError: # kill may not be available under windows environment pass
""" Creates a new instance of the Service :Args: - executable_path : Path to the ChromeDriver - port : Port the service is running on - service_args : List of args to pass to the chromedriver service - log_path : Path for the chromedriver service to log to""" self.port = port self.path = executable_path self.service_args = service_args or [] if log_path: self.service_args.append('--log-path=%s' % log_path) if self.port == 0: self.port = utils.free_port() self.env = env
identifier_body
service.py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os import errno import subprocess from subprocess import PIPE import time from selenium.common.exceptions import WebDriverException from selenium.webdriver.common import utils class Service(object): """ Object that manages the starting and stopping of the ChromeDriver """ def __init__(self, executable_path, port=0, service_args=None, log_path=None, env=None): """ Creates a new instance of the Service :Args: - executable_path : Path to the ChromeDriver - port : Port the service is running on - service_args : List of args to pass to the chromedriver service - log_path : Path for the chromedriver service to log to""" self.port = port self.path = executable_path self.service_args = service_args or [] if log_path: self.service_args.append('--log-path=%s' % log_path) if self.port == 0: self.port = utils.free_port() self.env = env def start(self): """ Starts the ChromeDriver Service. :Exceptions: - WebDriverException : Raised either when it cannot find the executable, when it does not have permissions for the executable, or when it cannot connect to the service. - Possibly other Exceptions in rare circumstances (OSError, etc). """ env = self.env or os.environ try: self.process = subprocess.Popen([ self.path, "--port=%d" % self.port] + self.service_args, env=env, stdout=PIPE, stderr=PIPE) except OSError as err: docs_msg = "Please see " \ "https://sites.google.com/a/chromium.org/chromedriver/home" if err.errno == errno.ENOENT: raise WebDriverException( "'%s' executable needs to be in PATH. %s" % ( os.path.basename(self.path), docs_msg) ) elif err.errno == errno.EACCES: raise WebDriverException( "'%s' executable may have wrong permissions. %s" % ( os.path.basename(self.path), docs_msg) ) else: raise count = 0 while not utils.is_connectable(self.port): count += 1 time.sleep(1) if count == 30: raise WebDriverException("Can not connect to the '" + os.path.basename(self.path) + "'") @property def service_url(self): """ Gets the url of the ChromeDriver Service """ return "http://localhost:%d" % self.port def
(self): """ Tells the ChromeDriver to stop and cleans up the process """ #If its dead dont worry if self.process is None: return #Tell the Server to die! try: from urllib import request as url_request except ImportError: import urllib2 as url_request url_request.urlopen("http://127.0.0.1:%d/shutdown" % self.port) count = 0 while utils.is_connectable(self.port): if count == 30: break count += 1 time.sleep(1) #Tell the Server to properly die in case try: if self.process: self.process.stdout.close() self.process.stderr.close() self.process.kill() self.process.wait() except OSError: # kill may not be available under windows environment pass
stop
identifier_name
runtimeversionmanager-tests.js
/** * Copyright 2011 Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var assert = require('assert'); var sinon = require('sinon'); // Test includes var testutil = require('../util/util'); // Lib includes var NamedPipeInputChannel = testutil.libRequire('serviceruntime/namedpipeinputchannel'); var RuntimeVersionProtocolClient = testutil.libRequire('serviceruntime/runtimeversionprotocolclient'); var RuntimeVersionManager = testutil.libRequire('serviceruntime/runtimeversionmanager'); suite('runtimeversionmanager-tests', function () { test('getRuntimeClient', function (done) { var versionsEndpointPath = 'versionsEndpointPath'; var inputChannel = new NamedPipeInputChannel(); var stub = sinon.stub(inputChannel, '_readData'); stub.withArgs(versionsEndpointPath).callsArgWith(1, undefined, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<RuntimeServerDiscovery xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + "<RuntimeServerEndpoints>" + "<RuntimeServerEndpoint version=\"2011-03-08\" path=\"SomePath.GoalState\" />" + "</RuntimeServerEndpoints>" +
var runtimeKernel = { getGoalStateClient: function () { return {}; }, getCurrentStateClient: function () { return {}; } }; var runtimeVersionManager = new RuntimeVersionManager(runtimeVersionProtocolClient, runtimeKernel); runtimeVersionManager.getRuntimeClient(versionsEndpointPath, function (error, runtimeClient) { assert.equal(error, undefined); assert.notEqual(runtimeClient, null); done(); }); }); });
"</RuntimeServerDiscovery>" ); var runtimeVersionProtocolClient = new RuntimeVersionProtocolClient(inputChannel);
random_line_split
job.py
from disco.core import Disco, result_iterator from disco.settings import DiscoSettings from disco.func import chain_reader from discodex.objects import DataSet from freequery.document import docparse from freequery.document.docset import Docset from freequery.index.tf_idf import TfIdf class IndexJob(object): def __init__(self, spec, discodex, disco_addr="disco://localhost", profile=False): # TODO(sqs): refactoring potential with PagerankJob
def start(self): results = self.__run_job(self.__index_job()) self.__run_discodex_index(results) def __run_job(self, job): results = job.wait() if self.profile: self.__profile_job(job) return results def __index_job(self): return self.disco.new_job( name="index_tfidf", input=['tag://' + self.docset.ddfs_tag], map_reader=docparse, map=TfIdf.map, reduce=TfIdf.reduce, sort=True, partitions=self.nr_partitions, partition=TfIdf.partition, merge_partitions=False, profile=self.profile, params=dict(doc_count=self.docset.doc_count)) def __run_discodex_index(self, results): opts = { 'parser': 'disco.func.chain_reader', 'demuxer': 'freequery.index.tf_idf.TfIdf_demux', 'nr_ichunks': 1, # TODO(sqs): after disco#181 fixed, increase this } ds = DataSet(input=results, options=opts) origname = self.discodex.index(ds) self.disco.wait(origname) # origname is also the disco job name self.discodex.clone(origname, self.spec.invindex_name)
self.spec = spec self.discodex = discodex self.docset = Docset(spec.docset_name) self.disco = Disco(DiscoSettings()['DISCO_MASTER']) self.nr_partitions = 8 self.profile = profile
identifier_body
job.py
from disco.core import Disco, result_iterator from disco.settings import DiscoSettings from disco.func import chain_reader from discodex.objects import DataSet from freequery.document import docparse from freequery.document.docset import Docset from freequery.index.tf_idf import TfIdf class
(object): def __init__(self, spec, discodex, disco_addr="disco://localhost", profile=False): # TODO(sqs): refactoring potential with PagerankJob self.spec = spec self.discodex = discodex self.docset = Docset(spec.docset_name) self.disco = Disco(DiscoSettings()['DISCO_MASTER']) self.nr_partitions = 8 self.profile = profile def start(self): results = self.__run_job(self.__index_job()) self.__run_discodex_index(results) def __run_job(self, job): results = job.wait() if self.profile: self.__profile_job(job) return results def __index_job(self): return self.disco.new_job( name="index_tfidf", input=['tag://' + self.docset.ddfs_tag], map_reader=docparse, map=TfIdf.map, reduce=TfIdf.reduce, sort=True, partitions=self.nr_partitions, partition=TfIdf.partition, merge_partitions=False, profile=self.profile, params=dict(doc_count=self.docset.doc_count)) def __run_discodex_index(self, results): opts = { 'parser': 'disco.func.chain_reader', 'demuxer': 'freequery.index.tf_idf.TfIdf_demux', 'nr_ichunks': 1, # TODO(sqs): after disco#181 fixed, increase this } ds = DataSet(input=results, options=opts) origname = self.discodex.index(ds) self.disco.wait(origname) # origname is also the disco job name self.discodex.clone(origname, self.spec.invindex_name)
IndexJob
identifier_name
job.py
from disco.core import Disco, result_iterator from disco.settings import DiscoSettings from disco.func import chain_reader from discodex.objects import DataSet from freequery.document import docparse from freequery.document.docset import Docset from freequery.index.tf_idf import TfIdf class IndexJob(object): def __init__(self, spec, discodex, disco_addr="disco://localhost", profile=False): # TODO(sqs): refactoring potential with PagerankJob self.spec = spec self.discodex = discodex self.docset = Docset(spec.docset_name) self.disco = Disco(DiscoSettings()['DISCO_MASTER']) self.nr_partitions = 8 self.profile = profile def start(self): results = self.__run_job(self.__index_job()) self.__run_discodex_index(results) def __run_job(self, job): results = job.wait() if self.profile:
return results def __index_job(self): return self.disco.new_job( name="index_tfidf", input=['tag://' + self.docset.ddfs_tag], map_reader=docparse, map=TfIdf.map, reduce=TfIdf.reduce, sort=True, partitions=self.nr_partitions, partition=TfIdf.partition, merge_partitions=False, profile=self.profile, params=dict(doc_count=self.docset.doc_count)) def __run_discodex_index(self, results): opts = { 'parser': 'disco.func.chain_reader', 'demuxer': 'freequery.index.tf_idf.TfIdf_demux', 'nr_ichunks': 1, # TODO(sqs): after disco#181 fixed, increase this } ds = DataSet(input=results, options=opts) origname = self.discodex.index(ds) self.disco.wait(origname) # origname is also the disco job name self.discodex.clone(origname, self.spec.invindex_name)
self.__profile_job(job)
conditional_block
job.py
from disco.core import Disco, result_iterator from disco.settings import DiscoSettings from disco.func import chain_reader from discodex.objects import DataSet from freequery.document import docparse from freequery.document.docset import Docset from freequery.index.tf_idf import TfIdf class IndexJob(object): def __init__(self, spec, discodex, disco_addr="disco://localhost", profile=False): # TODO(sqs): refactoring potential with PagerankJob self.spec = spec self.discodex = discodex self.docset = Docset(spec.docset_name) self.disco = Disco(DiscoSettings()['DISCO_MASTER']) self.nr_partitions = 8 self.profile = profile def start(self): results = self.__run_job(self.__index_job()) self.__run_discodex_index(results) def __run_job(self, job): results = job.wait() if self.profile: self.__profile_job(job) return results def __index_job(self): return self.disco.new_job( name="index_tfidf", input=['tag://' + self.docset.ddfs_tag], map_reader=docparse, map=TfIdf.map, reduce=TfIdf.reduce, sort=True, partitions=self.nr_partitions, partition=TfIdf.partition, merge_partitions=False, profile=self.profile, params=dict(doc_count=self.docset.doc_count)) def __run_discodex_index(self, results): opts = { 'parser': 'disco.func.chain_reader', 'demuxer': 'freequery.index.tf_idf.TfIdf_demux', 'nr_ichunks': 1, # TODO(sqs): after disco#181 fixed, increase this
ds = DataSet(input=results, options=opts) origname = self.discodex.index(ds) self.disco.wait(origname) # origname is also the disco job name self.discodex.clone(origname, self.spec.invindex_name)
}
random_line_split
module_unittest.py
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for the module module, which contains Module and related classes.""" import os import unittest from tvcm import fake_fs from tvcm import module from tvcm import resource_loader from tvcm import project as project_module class
(unittest.TestCase): def test_module(self): fs = fake_fs.FakeFS() fs.AddFile('/src/x.html', """ <!DOCTYPE html> <link rel="import" href="/y.html"> <link rel="import" href="/z.html"> <script> 'use strict'; </script> """) fs.AddFile('/src/y.html', """ <!DOCTYPE html> <link rel="import" href="/z.html"> """) fs.AddFile('/src/z.html', """ <!DOCTYPE html> """) fs.AddFile('/src/tvcm.html', '<!DOCTYPE html>') with fs: project = project_module.Project([os.path.normpath('/src/')]) loader = resource_loader.ResourceLoader(project) x_module = loader.LoadModule('x') self.assertEquals([loader.loaded_modules['y'], loader.loaded_modules['z']], x_module.dependent_modules) already_loaded_set = set() load_sequence = [] x_module.ComputeLoadSequenceRecursive(load_sequence, already_loaded_set) self.assertEquals([loader.loaded_modules['z'], loader.loaded_modules['y'], x_module], load_sequence) def testBasic(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> }); """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> }); """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='src.my_module') dep_names = [x.name for x in my_module.dependent_modules] self.assertEquals(['tvcm.foo'], dep_names) def testDepsExceptionContext(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> <link rel="import" href="missing.html"> """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: exc = None try: loader.LoadModule(module_name='src.my_module') assert False, 'Expected an exception' except module.DepsException, e: exc = e self.assertEquals( ['src.my_module', 'tvcm.foo'], exc.context) def testGetAllDependentFilenamesRecursive(self): fs = fake_fs.FakeFS() fs.AddFile('/x/y/z/foo.html', """ <!DOCTYPE html> <link rel="import" href="/z/foo2.html"> <link rel="stylesheet" href="/z/foo.css"> <script src="/bar.js"></script> """) fs.AddFile('/x/y/z/foo.css', """ .x .y { background-image: url(foo.jpeg); } """) fs.AddFile('/x/y/z/foo.jpeg', '') fs.AddFile('/x/y/z/foo2.html', """ <!DOCTYPE html> """) fs.AddFile('/x/raw/bar.js', 'hello') project = project_module.Project([ os.path.normpath('/x/y'), os.path.normpath('/x/raw/')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='z.foo') self.assertEquals(1, len(my_module.dependent_raw_scripts)) dependent_filenames = my_module.GetAllDependentFilenamesRecursive() self.assertEquals( [ os.path.normpath('/x/y/z/foo.html'), os.path.normpath('/x/raw/bar.js'), os.path.normpath('/x/y/z/foo.css'), os.path.normpath('/x/y/z/foo.jpeg'), os.path.normpath('/x/y/z/foo2.html'), ], dependent_filenames)
ModuleIntegrationTests
identifier_name
module_unittest.py
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for the module module, which contains Module and related classes.""" import os import unittest from tvcm import fake_fs from tvcm import module from tvcm import resource_loader from tvcm import project as project_module class ModuleIntegrationTests(unittest.TestCase): def test_module(self): fs = fake_fs.FakeFS() fs.AddFile('/src/x.html', """ <!DOCTYPE html> <link rel="import" href="/y.html"> <link rel="import" href="/z.html"> <script> 'use strict'; </script> """) fs.AddFile('/src/y.html', """ <!DOCTYPE html> <link rel="import" href="/z.html"> """) fs.AddFile('/src/z.html', """ <!DOCTYPE html> """) fs.AddFile('/src/tvcm.html', '<!DOCTYPE html>') with fs: project = project_module.Project([os.path.normpath('/src/')]) loader = resource_loader.ResourceLoader(project) x_module = loader.LoadModule('x') self.assertEquals([loader.loaded_modules['y'], loader.loaded_modules['z']], x_module.dependent_modules) already_loaded_set = set() load_sequence = [] x_module.ComputeLoadSequenceRecursive(load_sequence, already_loaded_set) self.assertEquals([loader.loaded_modules['z'], loader.loaded_modules['y'], x_module], load_sequence) def testBasic(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> }); """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> }); """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='src.my_module') dep_names = [x.name for x in my_module.dependent_modules] self.assertEquals(['tvcm.foo'], dep_names) def testDepsExceptionContext(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> <link rel="import" href="missing.html"> """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: exc = None try: loader.LoadModule(module_name='src.my_module') assert False, 'Expected an exception' except module.DepsException, e: exc = e self.assertEquals( ['src.my_module', 'tvcm.foo'], exc.context) def testGetAllDependentFilenamesRecursive(self): fs = fake_fs.FakeFS() fs.AddFile('/x/y/z/foo.html', """ <!DOCTYPE html> <link rel="import" href="/z/foo2.html"> <link rel="stylesheet" href="/z/foo.css"> <script src="/bar.js"></script> """) fs.AddFile('/x/y/z/foo.css', """
""") fs.AddFile('/x/y/z/foo.jpeg', '') fs.AddFile('/x/y/z/foo2.html', """ <!DOCTYPE html> """) fs.AddFile('/x/raw/bar.js', 'hello') project = project_module.Project([ os.path.normpath('/x/y'), os.path.normpath('/x/raw/')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='z.foo') self.assertEquals(1, len(my_module.dependent_raw_scripts)) dependent_filenames = my_module.GetAllDependentFilenamesRecursive() self.assertEquals( [ os.path.normpath('/x/y/z/foo.html'), os.path.normpath('/x/raw/bar.js'), os.path.normpath('/x/y/z/foo.css'), os.path.normpath('/x/y/z/foo.jpeg'), os.path.normpath('/x/y/z/foo2.html'), ], dependent_filenames)
.x .y { background-image: url(foo.jpeg); }
random_line_split
module_unittest.py
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for the module module, which contains Module and related classes.""" import os import unittest from tvcm import fake_fs from tvcm import module from tvcm import resource_loader from tvcm import project as project_module class ModuleIntegrationTests(unittest.TestCase): def test_module(self): fs = fake_fs.FakeFS() fs.AddFile('/src/x.html', """ <!DOCTYPE html> <link rel="import" href="/y.html"> <link rel="import" href="/z.html"> <script> 'use strict'; </script> """) fs.AddFile('/src/y.html', """ <!DOCTYPE html> <link rel="import" href="/z.html"> """) fs.AddFile('/src/z.html', """ <!DOCTYPE html> """) fs.AddFile('/src/tvcm.html', '<!DOCTYPE html>') with fs: project = project_module.Project([os.path.normpath('/src/')]) loader = resource_loader.ResourceLoader(project) x_module = loader.LoadModule('x') self.assertEquals([loader.loaded_modules['y'], loader.loaded_modules['z']], x_module.dependent_modules) already_loaded_set = set() load_sequence = [] x_module.ComputeLoadSequenceRecursive(load_sequence, already_loaded_set) self.assertEquals([loader.loaded_modules['z'], loader.loaded_modules['y'], x_module], load_sequence) def testBasic(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> }); """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> }); """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='src.my_module') dep_names = [x.name for x in my_module.dependent_modules] self.assertEquals(['tvcm.foo'], dep_names) def testDepsExceptionContext(self): fs = fake_fs.FakeFS() fs.AddFile('/x/src/my_module.html', """ <!DOCTYPE html> <link rel="import" href="/tvcm/foo.html"> """) fs.AddFile('/x/tvcm/foo.html', """ <!DOCTYPE html> <link rel="import" href="missing.html"> """) project = project_module.Project([os.path.normpath('/x')]) loader = resource_loader.ResourceLoader(project) with fs: exc = None try: loader.LoadModule(module_name='src.my_module') assert False, 'Expected an exception' except module.DepsException, e: exc = e self.assertEquals( ['src.my_module', 'tvcm.foo'], exc.context) def testGetAllDependentFilenamesRecursive(self):
fs = fake_fs.FakeFS() fs.AddFile('/x/y/z/foo.html', """ <!DOCTYPE html> <link rel="import" href="/z/foo2.html"> <link rel="stylesheet" href="/z/foo.css"> <script src="/bar.js"></script> """) fs.AddFile('/x/y/z/foo.css', """ .x .y { background-image: url(foo.jpeg); } """) fs.AddFile('/x/y/z/foo.jpeg', '') fs.AddFile('/x/y/z/foo2.html', """ <!DOCTYPE html> """) fs.AddFile('/x/raw/bar.js', 'hello') project = project_module.Project([ os.path.normpath('/x/y'), os.path.normpath('/x/raw/')]) loader = resource_loader.ResourceLoader(project) with fs: my_module = loader.LoadModule(module_name='z.foo') self.assertEquals(1, len(my_module.dependent_raw_scripts)) dependent_filenames = my_module.GetAllDependentFilenamesRecursive() self.assertEquals( [ os.path.normpath('/x/y/z/foo.html'), os.path.normpath('/x/raw/bar.js'), os.path.normpath('/x/y/z/foo.css'), os.path.normpath('/x/y/z/foo.jpeg'), os.path.normpath('/x/y/z/foo2.html'), ], dependent_filenames)
identifier_body
trait-bounds-in-arc.rs
// ignore-pretty // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. extern crate sync; use sync::Arc; use std::task; trait Pet { fn name(&self, blk: |&str|); fn num_legs(&self) -> uint; fn of_good_pedigree(&self) -> bool; } struct Catte { num_whiskers: uint, name: ~str, } struct Dogge { bark_decibels: uint, tricks_known: uint, name: ~str, } struct Goldfyshe { swim_speed: uint, name: ~str, } impl Pet for Catte { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 } } impl Pet for Dogge { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 0 } fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 } } pub fn main() { let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_owned() }; let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_owned() }; let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_owned() }; let fishe = Goldfyshe { swim_speed: 998, name: "alec_guinness".to_owned() }; let arc = Arc::new(vec!(~catte as ~Pet:Share+Send, ~dogge1 as ~Pet:Share+Send, ~fishe as ~Pet:Share+Send, ~dogge2 as ~Pet:Share+Send)); let (tx1, rx1) = channel(); let arc1 = arc.clone(); task::spawn(proc() { check_legs(arc1); tx1.send(()); }); let (tx2, rx2) = channel(); let arc2 = arc.clone(); task::spawn(proc() { check_names(arc2); tx2.send(()); }); let (tx3, rx3) = channel(); let arc3 = arc.clone(); task::spawn(proc() { check_pedigree(arc3); tx3.send(()); }); rx1.recv(); rx2.recv(); rx3.recv(); } fn check_legs(arc: Arc<Vec<~Pet:Share+Send>>) { let mut legs = 0; for pet in arc.iter() { legs += pet.num_legs(); } assert!(legs == 12);
for pet in arc.iter() { pet.name(|name| { assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8); }) } } fn check_pedigree(arc: Arc<Vec<~Pet:Share+Send>>) { for pet in arc.iter() { assert!(pet.of_good_pedigree()); } }
} fn check_names(arc: Arc<Vec<~Pet:Share+Send>>) {
random_line_split
trait-bounds-in-arc.rs
// ignore-pretty // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. extern crate sync; use sync::Arc; use std::task; trait Pet { fn name(&self, blk: |&str|); fn num_legs(&self) -> uint; fn of_good_pedigree(&self) -> bool; } struct Catte { num_whiskers: uint, name: ~str, } struct Dogge { bark_decibels: uint, tricks_known: uint, name: ~str, } struct Goldfyshe { swim_speed: uint, name: ~str, } impl Pet for Catte { fn
(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 } } impl Pet for Dogge { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 0 } fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 } } pub fn main() { let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_owned() }; let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_owned() }; let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_owned() }; let fishe = Goldfyshe { swim_speed: 998, name: "alec_guinness".to_owned() }; let arc = Arc::new(vec!(~catte as ~Pet:Share+Send, ~dogge1 as ~Pet:Share+Send, ~fishe as ~Pet:Share+Send, ~dogge2 as ~Pet:Share+Send)); let (tx1, rx1) = channel(); let arc1 = arc.clone(); task::spawn(proc() { check_legs(arc1); tx1.send(()); }); let (tx2, rx2) = channel(); let arc2 = arc.clone(); task::spawn(proc() { check_names(arc2); tx2.send(()); }); let (tx3, rx3) = channel(); let arc3 = arc.clone(); task::spawn(proc() { check_pedigree(arc3); tx3.send(()); }); rx1.recv(); rx2.recv(); rx3.recv(); } fn check_legs(arc: Arc<Vec<~Pet:Share+Send>>) { let mut legs = 0; for pet in arc.iter() { legs += pet.num_legs(); } assert!(legs == 12); } fn check_names(arc: Arc<Vec<~Pet:Share+Send>>) { for pet in arc.iter() { pet.name(|name| { assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8); }) } } fn check_pedigree(arc: Arc<Vec<~Pet:Share+Send>>) { for pet in arc.iter() { assert!(pet.of_good_pedigree()); } }
name
identifier_name
trait-bounds-in-arc.rs
// ignore-pretty // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. extern crate sync; use sync::Arc; use std::task; trait Pet { fn name(&self, blk: |&str|); fn num_legs(&self) -> uint; fn of_good_pedigree(&self) -> bool; } struct Catte { num_whiskers: uint, name: ~str, } struct Dogge { bark_decibels: uint, tricks_known: uint, name: ~str, } struct Goldfyshe { swim_speed: uint, name: ~str, } impl Pet for Catte { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 } } impl Pet for Dogge { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, blk: |&str|) { blk(self.name) } fn num_legs(&self) -> uint { 0 } fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 } } pub fn main() { let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_owned() }; let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_owned() }; let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_owned() }; let fishe = Goldfyshe { swim_speed: 998, name: "alec_guinness".to_owned() }; let arc = Arc::new(vec!(~catte as ~Pet:Share+Send, ~dogge1 as ~Pet:Share+Send, ~fishe as ~Pet:Share+Send, ~dogge2 as ~Pet:Share+Send)); let (tx1, rx1) = channel(); let arc1 = arc.clone(); task::spawn(proc() { check_legs(arc1); tx1.send(()); }); let (tx2, rx2) = channel(); let arc2 = arc.clone(); task::spawn(proc() { check_names(arc2); tx2.send(()); }); let (tx3, rx3) = channel(); let arc3 = arc.clone(); task::spawn(proc() { check_pedigree(arc3); tx3.send(()); }); rx1.recv(); rx2.recv(); rx3.recv(); } fn check_legs(arc: Arc<Vec<~Pet:Share+Send>>) { let mut legs = 0; for pet in arc.iter() { legs += pet.num_legs(); } assert!(legs == 12); } fn check_names(arc: Arc<Vec<~Pet:Share+Send>>) { for pet in arc.iter() { pet.name(|name| { assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8); }) } } fn check_pedigree(arc: Arc<Vec<~Pet:Share+Send>>)
{ for pet in arc.iter() { assert!(pet.of_good_pedigree()); } }
identifier_body
sketch2.ts
//#!tsc && NODE_PATH=dist/src node dist/sketch2.js
Rect, TextHjustify, TextVjustify, Transform, DECIDEG2RAD, TextAngle, } from "./src/kicad_common"; import { StrokeFont } from "./src/kicad_strokefont"; import { Plotter, CanvasPlotter } from "./src/kicad_plotter"; import * as fs from "fs"; { const font = StrokeFont.instance; const width = 2000, height = 2000; const Canvas = require('canvas'); const canvas = Canvas.createCanvas ? Canvas.createCanvas(width, height) : new Canvas(width, height); const ctx = canvas.getContext('2d'); ctx.strokeStyle = "#666666"; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(canvas.width / 2, 0); ctx.lineTo(canvas.width / 2, canvas.height); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, canvas.height / 2); ctx.lineTo(canvas.width, canvas.height / 2); ctx.stroke(); ctx.lineCap = "round"; ctx.lineJoin = 'round'; // ctx.translate(canvas.width / 2, canvas.height / 2); const plotter = new CanvasPlotter(ctx); const text = 'jeyjmcNV'; const size = 100; const lineWidth = 20; const bold = false; const italic = false; const pos = { x: canvas.width / 2, y: canvas.height / 2 }; const vjustify = TextVjustify.CENTER; { const boundingbox = font.computeStringBoundaryLimits(text, size, lineWidth, italic); ctx.save(); ctx.translate(pos.x, pos.y); ctx.translate(0, size / 2); ctx.fillStyle = "rgba(255, 0, 0, 0.3)"; ctx.fillRect(0, 0, boundingbox.width, -boundingbox.height); ctx.fillStyle = "rgba(0, 0, 255, 0.3)"; ctx.fillRect(0, 0, boundingbox.width, boundingbox.topLimit); ctx.fillRect(0, 0, boundingbox.width, boundingbox.bottomLimit); { const n = text.charCodeAt(0) - ' '.charCodeAt(0); const glyph = font.glyphs[n]; console.log(JSON.stringify(glyph)); ctx.fillStyle = "rgba(0, 255, 0, 0.3)"; ctx.fillRect( glyph.boundingBox.pos1.x * size, glyph.boundingBox.pos1.y * size, glyph.boundingBox.width * size, glyph.boundingBox.height * size ); ctx.restore(); } } font.drawText(plotter, pos, text, size, lineWidth, TextAngle.HORIZ, TextHjustify.LEFT, vjustify, italic, bold); const out = fs.createWriteStream('text.png'), stream = canvas.pngStream(); stream.on('data', function (chunk: any) { out.write(chunk); }); stream.on('end', function(){ console.log('saved png'); }); }
import { Point,
random_line_split
central-panel.component.ts
import { Component, OnInit, Inject, EventEmitter } from '@angular/core'; import { EditorService, LeftSelection } from '../editor.service'; import { AxScriptFlow } from 'src/app/ax-model/model'; import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service'; import { EditorGlobal } from '../editor-global'; import { DesignerGlobal } from 'src/app/ax-designer/ax-global'; import { SelectorGlobal } from 'src/app/ax-selector/global'; import { debounce } from 'rxjs/operators'; import { timer } from 'rxjs'; import { MapWithName } from './map-editor/map-editor.component'; import { Step } from './script-editor/step/step.component'; @Component({ selector: 'app-central-panel', templateUrl: './central-panel.component.html', styleUrls: ['./central-panel.component.scss'] }) export class CentralPanelComponent implements OnInit { static consoleTab:LeftSelection = {name: 'Console', type:'console'}; private throttledChange:EventEmitter<[LeftSelection,MapRowVM[]]> = new EventEmitter(); monitorTab:LeftSelection = {name: 'Monitor', type:'monitor'}; baseTabs: LeftSelection[] = [this.monitorTab,CentralPanelComponent.consoleTab]; tabs: LeftSelection[] = []; steps:AxScriptFlow[] = []; selected: LeftSelection = this.tabs[0]; mapSelected:MapWithName = null; oldCurrentResolution:string = ''; constructor( private editorService:EditorService, private selectorDatastore: SelectorDatastoreService, @Inject('GlobalRefSelector') private global:SelectorGlobal ) { } ngOnInit() { this.selectorDatastore.getSelected().subscribe(s => { if(!s || s.length == 0 || s.every(x => this.oldCurrentResolution != x.selectedResolution)) { if(s && s.length >0) { this.oldCurrentResolution = s[0].selectedResolution } else { this.oldCurrentResolution = ''; } let isCurrentResolution = s && s.length > 0 && s.every(x => x.selectedResolution === this.global.res_string) if(isCurrentResolution) { this.baseTabs = [this.monitorTab,CentralPanelComponent.consoleTab]; if(!this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== CentralPanelComponent.consoleTab.name) this.tabs = this.tabs.concat(this.baseTabs); } } else { this.baseTabs = [CentralPanelComponent.consoleTab]; if(this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== this.monitorTab.name) if(this.selected.name === this.monitorTab.name && this.tabs[0]) { this.selected = this.tabs[0] } } } } }) this.editorService.getLeftSelection().subscribe(s => { if(s) {
this.selectTab(s) } else { this.tabs = [s].concat(this.baseTabs); this.selected = s; if(this.selected.map) { this.mapSelected = this.mapName(this.selected.map()); } if(this.selected.steps) { this.steps = Array.from(this.selected.steps()); // need to do a copy for the script editor to catch the change } } } }) this.throttledChange.pipe(debounce(() => timer(500))).subscribe(x =>{ if(x[0].onChangeMap) { x[0].onChangeMap(x[1]); } }); } selectTab(tab:LeftSelection) { if(tab.type == 'map') { this.mapSelected = this.mapName(tab.map()); // this.selectorDatastore.getData().subscribe(x => { // this.selectorDatastore.getMaps().subscribe(y => { // this.mapSelected = y.map(z => { return {name: z.name, rows: z.rows}}).find(x => x.name == tab.name) // this.selected = tab // }) // }) } this.selected = tab } isSelectedTab(tab:LeftSelection):boolean { return this.selected.name === tab.name; } scriptChanged(flow:AxScriptFlow[]) { if (this.selected.onChangeSteps) { this.selected.onChangeSteps(flow); } } mapChanged(map:MapRowVM[]) { this.selected.onChangeMap(map); } mapName(map:MapRowVM[]):MapWithName { return { rows: map, name: this.selected.name } } }
if(s.name === CentralPanelComponent.consoleTab.name) {
random_line_split
central-panel.component.ts
import { Component, OnInit, Inject, EventEmitter } from '@angular/core'; import { EditorService, LeftSelection } from '../editor.service'; import { AxScriptFlow } from 'src/app/ax-model/model'; import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service'; import { EditorGlobal } from '../editor-global'; import { DesignerGlobal } from 'src/app/ax-designer/ax-global'; import { SelectorGlobal } from 'src/app/ax-selector/global'; import { debounce } from 'rxjs/operators'; import { timer } from 'rxjs'; import { MapWithName } from './map-editor/map-editor.component'; import { Step } from './script-editor/step/step.component'; @Component({ selector: 'app-central-panel', templateUrl: './central-panel.component.html', styleUrls: ['./central-panel.component.scss'] }) export class CentralPanelComponent implements OnInit { static consoleTab:LeftSelection = {name: 'Console', type:'console'}; private throttledChange:EventEmitter<[LeftSelection,MapRowVM[]]> = new EventEmitter(); monitorTab:LeftSelection = {name: 'Monitor', type:'monitor'}; baseTabs: LeftSelection[] = [this.monitorTab,CentralPanelComponent.consoleTab]; tabs: LeftSelection[] = []; steps:AxScriptFlow[] = []; selected: LeftSelection = this.tabs[0]; mapSelected:MapWithName = null; oldCurrentResolution:string = ''; constructor( private editorService:EditorService, private selectorDatastore: SelectorDatastoreService, @Inject('GlobalRefSelector') private global:SelectorGlobal ) { } ngOnInit() { this.selectorDatastore.getSelected().subscribe(s => { if(!s || s.length == 0 || s.every(x => this.oldCurrentResolution != x.selectedResolution)) { if(s && s.length >0) { this.oldCurrentResolution = s[0].selectedResolution } else { this.oldCurrentResolution = ''; } let isCurrentResolution = s && s.length > 0 && s.every(x => x.selectedResolution === this.global.res_string) if(isCurrentResolution) { this.baseTabs = [this.monitorTab,CentralPanelComponent.consoleTab]; if(!this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== CentralPanelComponent.consoleTab.name) this.tabs = this.tabs.concat(this.baseTabs); } } else { this.baseTabs = [CentralPanelComponent.consoleTab]; if(this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== this.monitorTab.name) if(this.selected.name === this.monitorTab.name && this.tabs[0]) { this.selected = this.tabs[0] } } } } }) this.editorService.getLeftSelection().subscribe(s => { if(s) { if(s.name === CentralPanelComponent.consoleTab.name) { this.selectTab(s) } else { this.tabs = [s].concat(this.baseTabs); this.selected = s; if(this.selected.map) { this.mapSelected = this.mapName(this.selected.map()); } if(this.selected.steps) { this.steps = Array.from(this.selected.steps()); // need to do a copy for the script editor to catch the change } } } }) this.throttledChange.pipe(debounce(() => timer(500))).subscribe(x =>{ if(x[0].onChangeMap) { x[0].onChangeMap(x[1]); } }); } selectTab(tab:LeftSelection) { if(tab.type == 'map') { this.mapSelected = this.mapName(tab.map()); // this.selectorDatastore.getData().subscribe(x => { // this.selectorDatastore.getMaps().subscribe(y => { // this.mapSelected = y.map(z => { return {name: z.name, rows: z.rows}}).find(x => x.name == tab.name) // this.selected = tab // }) // }) } this.selected = tab } isSelectedTab(tab:LeftSelection):boolean { return this.selected.name === tab.name; } scriptChanged(flow:AxScriptFlow[])
mapChanged(map:MapRowVM[]) { this.selected.onChangeMap(map); } mapName(map:MapRowVM[]):MapWithName { return { rows: map, name: this.selected.name } } }
{ if (this.selected.onChangeSteps) { this.selected.onChangeSteps(flow); } }
identifier_body
central-panel.component.ts
import { Component, OnInit, Inject, EventEmitter } from '@angular/core'; import { EditorService, LeftSelection } from '../editor.service'; import { AxScriptFlow } from 'src/app/ax-model/model'; import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service'; import { EditorGlobal } from '../editor-global'; import { DesignerGlobal } from 'src/app/ax-designer/ax-global'; import { SelectorGlobal } from 'src/app/ax-selector/global'; import { debounce } from 'rxjs/operators'; import { timer } from 'rxjs'; import { MapWithName } from './map-editor/map-editor.component'; import { Step } from './script-editor/step/step.component'; @Component({ selector: 'app-central-panel', templateUrl: './central-panel.component.html', styleUrls: ['./central-panel.component.scss'] }) export class CentralPanelComponent implements OnInit { static consoleTab:LeftSelection = {name: 'Console', type:'console'}; private throttledChange:EventEmitter<[LeftSelection,MapRowVM[]]> = new EventEmitter(); monitorTab:LeftSelection = {name: 'Monitor', type:'monitor'}; baseTabs: LeftSelection[] = [this.monitorTab,CentralPanelComponent.consoleTab]; tabs: LeftSelection[] = []; steps:AxScriptFlow[] = []; selected: LeftSelection = this.tabs[0]; mapSelected:MapWithName = null; oldCurrentResolution:string = ''; constructor( private editorService:EditorService, private selectorDatastore: SelectorDatastoreService, @Inject('GlobalRefSelector') private global:SelectorGlobal ) { } ngOnInit() { this.selectorDatastore.getSelected().subscribe(s => { if(!s || s.length == 0 || s.every(x => this.oldCurrentResolution != x.selectedResolution)) { if(s && s.length >0) { this.oldCurrentResolution = s[0].selectedResolution } else { this.oldCurrentResolution = ''; } let isCurrentResolution = s && s.length > 0 && s.every(x => x.selectedResolution === this.global.res_string) if(isCurrentResolution) { this.baseTabs = [this.monitorTab,CentralPanelComponent.consoleTab]; if(!this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== CentralPanelComponent.consoleTab.name) this.tabs = this.tabs.concat(this.baseTabs); } } else { this.baseTabs = [CentralPanelComponent.consoleTab]; if(this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== this.monitorTab.name) if(this.selected.name === this.monitorTab.name && this.tabs[0]) { this.selected = this.tabs[0] } } } } }) this.editorService.getLeftSelection().subscribe(s => { if(s) { if(s.name === CentralPanelComponent.consoleTab.name) { this.selectTab(s) } else { this.tabs = [s].concat(this.baseTabs); this.selected = s; if(this.selected.map) { this.mapSelected = this.mapName(this.selected.map()); } if(this.selected.steps) { this.steps = Array.from(this.selected.steps()); // need to do a copy for the script editor to catch the change } } } }) this.throttledChange.pipe(debounce(() => timer(500))).subscribe(x =>{ if(x[0].onChangeMap) { x[0].onChangeMap(x[1]); } }); } selectTab(tab:LeftSelection) { if(tab.type == 'map') { this.mapSelected = this.mapName(tab.map()); // this.selectorDatastore.getData().subscribe(x => { // this.selectorDatastore.getMaps().subscribe(y => { // this.mapSelected = y.map(z => { return {name: z.name, rows: z.rows}}).find(x => x.name == tab.name) // this.selected = tab // }) // }) } this.selected = tab } isSelectedTab(tab:LeftSelection):boolean { return this.selected.name === tab.name; }
(flow:AxScriptFlow[]) { if (this.selected.onChangeSteps) { this.selected.onChangeSteps(flow); } } mapChanged(map:MapRowVM[]) { this.selected.onChangeMap(map); } mapName(map:MapRowVM[]):MapWithName { return { rows: map, name: this.selected.name } } }
scriptChanged
identifier_name
central-panel.component.ts
import { Component, OnInit, Inject, EventEmitter } from '@angular/core'; import { EditorService, LeftSelection } from '../editor.service'; import { AxScriptFlow } from 'src/app/ax-model/model'; import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service'; import { EditorGlobal } from '../editor-global'; import { DesignerGlobal } from 'src/app/ax-designer/ax-global'; import { SelectorGlobal } from 'src/app/ax-selector/global'; import { debounce } from 'rxjs/operators'; import { timer } from 'rxjs'; import { MapWithName } from './map-editor/map-editor.component'; import { Step } from './script-editor/step/step.component'; @Component({ selector: 'app-central-panel', templateUrl: './central-panel.component.html', styleUrls: ['./central-panel.component.scss'] }) export class CentralPanelComponent implements OnInit { static consoleTab:LeftSelection = {name: 'Console', type:'console'}; private throttledChange:EventEmitter<[LeftSelection,MapRowVM[]]> = new EventEmitter(); monitorTab:LeftSelection = {name: 'Monitor', type:'monitor'}; baseTabs: LeftSelection[] = [this.monitorTab,CentralPanelComponent.consoleTab]; tabs: LeftSelection[] = []; steps:AxScriptFlow[] = []; selected: LeftSelection = this.tabs[0]; mapSelected:MapWithName = null; oldCurrentResolution:string = ''; constructor( private editorService:EditorService, private selectorDatastore: SelectorDatastoreService, @Inject('GlobalRefSelector') private global:SelectorGlobal ) { } ngOnInit() { this.selectorDatastore.getSelected().subscribe(s => { if(!s || s.length == 0 || s.every(x => this.oldCurrentResolution != x.selectedResolution)) { if(s && s.length >0)
else { this.oldCurrentResolution = ''; } let isCurrentResolution = s && s.length > 0 && s.every(x => x.selectedResolution === this.global.res_string) if(isCurrentResolution) { this.baseTabs = [this.monitorTab,CentralPanelComponent.consoleTab]; if(!this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== CentralPanelComponent.consoleTab.name) this.tabs = this.tabs.concat(this.baseTabs); } } else { this.baseTabs = [CentralPanelComponent.consoleTab]; if(this.tabs.includes(this.monitorTab)) { this.tabs = this.tabs.filter(x => x.name !== this.monitorTab.name) if(this.selected.name === this.monitorTab.name && this.tabs[0]) { this.selected = this.tabs[0] } } } } }) this.editorService.getLeftSelection().subscribe(s => { if(s) { if(s.name === CentralPanelComponent.consoleTab.name) { this.selectTab(s) } else { this.tabs = [s].concat(this.baseTabs); this.selected = s; if(this.selected.map) { this.mapSelected = this.mapName(this.selected.map()); } if(this.selected.steps) { this.steps = Array.from(this.selected.steps()); // need to do a copy for the script editor to catch the change } } } }) this.throttledChange.pipe(debounce(() => timer(500))).subscribe(x =>{ if(x[0].onChangeMap) { x[0].onChangeMap(x[1]); } }); } selectTab(tab:LeftSelection) { if(tab.type == 'map') { this.mapSelected = this.mapName(tab.map()); // this.selectorDatastore.getData().subscribe(x => { // this.selectorDatastore.getMaps().subscribe(y => { // this.mapSelected = y.map(z => { return {name: z.name, rows: z.rows}}).find(x => x.name == tab.name) // this.selected = tab // }) // }) } this.selected = tab } isSelectedTab(tab:LeftSelection):boolean { return this.selected.name === tab.name; } scriptChanged(flow:AxScriptFlow[]) { if (this.selected.onChangeSteps) { this.selected.onChangeSteps(flow); } } mapChanged(map:MapRowVM[]) { this.selected.onChangeMap(map); } mapName(map:MapRowVM[]):MapWithName { return { rows: map, name: this.selected.name } } }
{ this.oldCurrentResolution = s[0].selectedResolution }
conditional_block
qa_test.py
""" Copyright 2013 OpERA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ #!/usr/bin/python ## @package algorithm # ::TODO:: Discover how to include patches externally import sys import os path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) sys.path.insert(0, path) import unittest import random # Modules tested from feedbackAlgorithm import FeedbackAlgorithm, ExponentialTimeFeedback, KunstTimeFeedback # Other modules needed from device import radioDevice from abstractAlgorithm import AbstractAlgorithm class QaAlgorithm(unittest.TestCase): """ Test algorithm module. """ def test_feedback_001(self): """ Test the feedback algorithm. """ mi = 1, ma = 256 base = 3 obj = ExponentialTimeFeedback(min_time=mi, max_time=ma, base=base ) # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 3 ^ 0 == 1 (wait is 1) self.assertEqual(True, obj.feedback()) # Testa se voltou direito # Test if got back correctly. self.assertEqual(False, obj.feedback()) # Aumentamos o tempo de sensoriamento 3^1 = 3 # We increase the sensing time 3^1 = 3. obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 obj.wait() # wait = 3 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) obj.decrease_time() # reset time 3^0 = 1 # reseta tempo 3^0 = 1 obj.wait() # wait = 1 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 def
(self): """ Test the feedback algorithm """ obj = KunstTimeFeedback() # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 2 ^ 0 == 1 # wait = 0 self.assertEqual(True, obj.feedback()) # Aumentamos o tempo de sensoriamento 2^1 = 2 # We increase the sensing time 2^1 = 2 obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 volta wait para 0 obj.wait() # wait = 1 obj.wait() # wait = 2 obj.wait() # wait = 3 obj.wait() # wait = 4 obj.increase_time() # 2^2 = 4 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 obj.decrease_time() # Should be 2^1 = 2 obj.wait() obj.wait() self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 if __name__ == '__main__': unittest.main()
test_feedback_002
identifier_name
qa_test.py
""" Copyright 2013 OpERA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ #!/usr/bin/python ## @package algorithm # ::TODO:: Discover how to include patches externally import sys import os path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) sys.path.insert(0, path) import unittest import random # Modules tested from feedbackAlgorithm import FeedbackAlgorithm, ExponentialTimeFeedback, KunstTimeFeedback # Other modules needed from device import radioDevice from abstractAlgorithm import AbstractAlgorithm class QaAlgorithm(unittest.TestCase): """ Test algorithm module. """ def test_feedback_001(self): """ Test the feedback algorithm. """ mi = 1, ma = 256 base = 3 obj = ExponentialTimeFeedback(min_time=mi, max_time=ma, base=base ) # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 3 ^ 0 == 1 (wait is 1) self.assertEqual(True, obj.feedback()) # Testa se voltou direito # Test if got back correctly. self.assertEqual(False, obj.feedback()) # Aumentamos o tempo de sensoriamento 3^1 = 3 # We increase the sensing time 3^1 = 3. obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 obj.wait() # wait = 3 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) obj.decrease_time() # reset time 3^0 = 1 # reseta tempo 3^0 = 1 obj.wait() # wait = 1 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 def test_feedback_002(self): """
""" obj = KunstTimeFeedback() # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 2 ^ 0 == 1 # wait = 0 self.assertEqual(True, obj.feedback()) # Aumentamos o tempo de sensoriamento 2^1 = 2 # We increase the sensing time 2^1 = 2 obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 volta wait para 0 obj.wait() # wait = 1 obj.wait() # wait = 2 obj.wait() # wait = 3 obj.wait() # wait = 4 obj.increase_time() # 2^2 = 4 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 obj.decrease_time() # Should be 2^1 = 2 obj.wait() obj.wait() self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 if __name__ == '__main__': unittest.main()
Test the feedback algorithm
random_line_split
qa_test.py
""" Copyright 2013 OpERA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ #!/usr/bin/python ## @package algorithm # ::TODO:: Discover how to include patches externally import sys import os path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) sys.path.insert(0, path) import unittest import random # Modules tested from feedbackAlgorithm import FeedbackAlgorithm, ExponentialTimeFeedback, KunstTimeFeedback # Other modules needed from device import radioDevice from abstractAlgorithm import AbstractAlgorithm class QaAlgorithm(unittest.TestCase): """ Test algorithm module. """ def test_feedback_001(self): """ Test the feedback algorithm. """ mi = 1, ma = 256 base = 3 obj = ExponentialTimeFeedback(min_time=mi, max_time=ma, base=base ) # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 3 ^ 0 == 1 (wait is 1) self.assertEqual(True, obj.feedback()) # Testa se voltou direito # Test if got back correctly. self.assertEqual(False, obj.feedback()) # Aumentamos o tempo de sensoriamento 3^1 = 3 # We increase the sensing time 3^1 = 3. obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 obj.wait() # wait = 3 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) obj.decrease_time() # reset time 3^0 = 1 # reseta tempo 3^0 = 1 obj.wait() # wait = 1 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 def test_feedback_002(self):
if __name__ == '__main__': unittest.main()
""" Test the feedback algorithm """ obj = KunstTimeFeedback() # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 2 ^ 0 == 1 # wait = 0 self.assertEqual(True, obj.feedback()) # Aumentamos o tempo de sensoriamento 2^1 = 2 # We increase the sensing time 2^1 = 2 obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 volta wait para 0 obj.wait() # wait = 1 obj.wait() # wait = 2 obj.wait() # wait = 3 obj.wait() # wait = 4 obj.increase_time() # 2^2 = 4 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 obj.decrease_time() # Should be 2^1 = 2 obj.wait() obj.wait() self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0
identifier_body
qa_test.py
""" Copyright 2013 OpERA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ #!/usr/bin/python ## @package algorithm # ::TODO:: Discover how to include patches externally import sys import os path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) sys.path.insert(0, path) import unittest import random # Modules tested from feedbackAlgorithm import FeedbackAlgorithm, ExponentialTimeFeedback, KunstTimeFeedback # Other modules needed from device import radioDevice from abstractAlgorithm import AbstractAlgorithm class QaAlgorithm(unittest.TestCase): """ Test algorithm module. """ def test_feedback_001(self): """ Test the feedback algorithm. """ mi = 1, ma = 256 base = 3 obj = ExponentialTimeFeedback(min_time=mi, max_time=ma, base=base ) # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 3 ^ 0 == 1 (wait is 1) self.assertEqual(True, obj.feedback()) # Testa se voltou direito # Test if got back correctly. self.assertEqual(False, obj.feedback()) # Aumentamos o tempo de sensoriamento 3^1 = 3 # We increase the sensing time 3^1 = 3. obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 obj.wait() # wait = 3 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) obj.decrease_time() # reset time 3^0 = 1 # reseta tempo 3^0 = 1 obj.wait() # wait = 1 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 def test_feedback_002(self): """ Test the feedback algorithm """ obj = KunstTimeFeedback() # Estado inicial # Initial state. self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 # 2 ^ 0 == 1 # wait = 0 self.assertEqual(True, obj.feedback()) # Aumentamos o tempo de sensoriamento 2^1 = 2 # We increase the sensing time 2^1 = 2 obj.increase_time() self.assertEqual(False, obj.feedback()) obj.wait() # wait = 1 self.assertEqual(False, obj.feedback()) obj.wait() # wait = 2 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 volta wait para 0 obj.wait() # wait = 1 obj.wait() # wait = 2 obj.wait() # wait = 3 obj.wait() # wait = 4 obj.increase_time() # 2^2 = 4 self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 obj.decrease_time() # Should be 2^1 = 2 obj.wait() obj.wait() self.assertEqual(True, obj.feedback()) # wait gets back to 0 # volta wait para 0 self.assertEqual(False, obj.feedback()) # wait gets back to 0 # volta wait para 0 if __name__ == '__main__':
unittest.main()
conditional_block
ConstValues.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-2015, Egret Technology Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Egret nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////////////// module dragonBones { /** * @class dragonBones.ConstValues * @classdesc *定义了常用的常量 */ export class ConstValues{ /
换为弧度 */ public static ANGLE_TO_RADIAN:number = Math.PI / 180; /** * 弧度转换为角度 */ public static RADIAN_TO_ANGLE:number = 180 / Math.PI; /** *龙骨 */ public static DRAGON_BONES:string = "dragonBones"; /** * 骨架 */ public static ARMATURE:string = "armature"; /** *皮肤 */ public static SKIN:string = "skin"; /** * 骨骼 */ public static BONE:string = "bone"; /** * 插槽 */ public static SLOT:string = "slot"; /** * 显示对象 */ public static DISPLAY:string = "display"; /** * 动画 */ public static ANIMATION:string = "animation"; /** * 时间轴 */ public static TIMELINE:string = "timeline"; /** * 帧 */ public static FRAME:string = "frame"; /** * 变换 */ public static TRANSFORM:string = "transform"; /** * 颜色变换 */ public static COLOR_TRANSFORM:string = "colorTransform"; /** * 矩形 */ public static RECTANGLE:string = "rectangle"; /** * 椭圆 */ public static ELLIPSE:string = "ellipse"; /** * 纹理集 */ public static TEXTURE_ATLAS:string = "TextureAtlas"; /** * 子纹理 */ public static SUB_TEXTURE:string = "SubTexture"; /** * 旋转 */ public static A_ROTATED:string = "rotated"; /** * 帧的x坐标 */ public static A_FRAME_X:string = "frameX"; /** * 帧的y坐标 */ public static A_FRAME_Y:string = "frameY"; /** * 帧的宽度 */ public static A_FRAME_WIDTH:string = "frameWidth"; /** * 帧的高度 */ public static A_FRAME_HEIGHT:string = "frameHeight"; /** * 版本 */ public static A_VERSION:string = "version"; /** * 图片路径 */ public static A_IMAGE_PATH:string = "imagePath"; /** * 帧速率 */ public static A_FRAME_RATE:string = "frameRate"; /** * 名字 */ public static A_NAME:string = "name"; /** * 是否是全局 */ public static A_IS_GLOBAL:string = "isGlobal"; /** * 父亲 */ public static A_PARENT:string = "parent"; /** * 长度 */ public static A_LENGTH:string = "length"; /** * 类型 */ public static A_TYPE:string = "type"; /** * 缓入事件 */ public static A_FADE_IN_TIME:string = "fadeInTime"; /** * 持续时长 */ public static A_DURATION:string = "duration"; /** * 缩放 */ public static A_SCALE:string = "scale"; /** * 偏移 */ public static A_OFFSET:string = "offset"; /** * 循环 */ public static A_LOOP:string = "loop"; /** * 事件 */ public static A_EVENT:string = "event"; /** * 事件参数 */ public static A_EVENT_PARAMETERS:string = "eventParameters"; /** * 声音 */ public static A_SOUND:string = "sound"; /** * 动作 */ public static A_ACTION:string = "action"; /** * 隐藏 */ public static A_HIDE:string = "hide"; /** * 自动补间 */ public static A_AUTO_TWEEN:string ="autoTween"; /** * 补间缓动 */ public static A_TWEEN_EASING:string = "tweenEasing"; /** * 补间旋转 */ public static A_TWEEN_ROTATE:string = "tweenRotate"; /** * 补间缩放 */ public static A_TWEEN_SCALE:string = "tweenScale"; /** * 显示对象序号 */ public static A_DISPLAY_INDEX:string = "displayIndex"; /** * z轴 */ public static A_Z_ORDER:string = "z"; /** * 混合模式 */ public static A_BLENDMODE:string = "blendMode"; /** * 宽度 */ public static A_WIDTH:string = "width"; /** * 高度 */ public static A_HEIGHT:string = "height"; /** * 继承缩放 */ public static A_INHERIT_SCALE:string = "inheritScale"; /** * 继承旋转 */ public static A_INHERIT_ROTATION:string = "inheritRotation"; /** * x轴 */ public static A_X:string = "x"; /** * y轴 */ public static A_Y:string = "y"; /** * x方向斜切 */ public static A_SKEW_X:string = "skX"; /** * y方向斜切 */ public static A_SKEW_Y:string = "skY"; /** * x方向缩放 */ public static A_SCALE_X:string = "scX"; /** * y方向缩放 */ public static A_SCALE_Y:string = "scY"; /** * 轴点的x坐标 */ public static A_PIVOT_X:string = "pX"; /** * 轴点的y坐标 */ public static A_PIVOT_Y:string = "pY"; /** * 透明度的偏移 */ public static A_ALPHA_OFFSET:string = "aO"; /** * 红色的偏移 */ public static A_RED_OFFSET:string = "rO"; /** * 绿色的偏移 */ public static A_GREEN_OFFSET:string = "gO"; /** * 蓝色的偏移 */ public static A_BLUE_OFFSET:string = "bO"; /** * 透明度的倍数 */ public static A_ALPHA_MULTIPLIER:string = "aM"; /** * 红色的倍数 */ public static A_RED_MULTIPLIER:string = "rM"; /** * 绿色的倍数 */ public static A_GREEN_MULTIPLIER:string = "gM"; /** * 蓝色的倍数 */ public static A_BLUE_MULTIPLIER:string = "bM"; /** * x方向缩放的偏移 */ public static A_SCALE_X_OFFSET:string = "scXOffset"; /** * y方向的偏移 */ public static A_SCALE_Y_OFFSET:string = "scYOffset"; /** * 缩放模式 */ public static A_SCALE_MODE:string = "scaleMode"; /** * 旋转修正 */ public static A_FIXED_ROTATION:string = "fixedRotation"; } }
** * 角度转
identifier_name
ConstValues.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-2015, Egret Technology Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Egret nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////////////// module dragonBones { /** * @class dragonBones.ConstValues * @classdesc *定义了常用的常量 */ export class ConstValues{ /** * 角度转换为弧度 */ public static ANGLE_TO_RADIAN:number = Math.PI / 180; /** * 弧度转换为角度 */ public static RADIAN_TO_ANGLE:number = 180 / Math.PI; /** *龙骨 */ public static DRAGON_BONES:string = "dragonBones"; /** * 骨架 */ public static ARMATURE:string = "armature"; /** *皮肤 */ public static SKIN:string = "skin"; /** * 骨骼 */ public static BONE:string = "bone"; /** * 插槽 */ public static SLOT:string = "slot"; /** * 显示对象 */ public static DISPLAY:string = "display"; /** * 动画 */ public static ANIMATION:string = "animation"; /** * 时间轴 */ public static TIMELINE:string = "timeline"; /** * 帧 */ public static FRAME:string = "frame"; /** * 变换 */ public static TRANSFORM:string = "transform"; /** * 颜色变换 */ public static COLOR_TRANSFORM:string = "colorTransform"; /** * 矩形 */ public static RECTANGLE:string = "rectangle"; /** * 椭圆 */ public static ELLIPSE:string = "ellipse"; /** * 纹理集 */ public static TEXTURE_ATLAS:string = "TextureAtlas"; /** * 子纹理 */ public static SUB_TEXTURE:string = "SubTexture"; /** * 旋转 */ public static A_ROTATED:string = "rotated"; /** * 帧的x坐标 */ public static A_FRAME_X:string = "frameX"; /** * 帧的y坐标 */ public static A_FRAME_Y:string = "frameY"; /** * 帧的宽度 */ public static A_FRAME_WIDTH:string = "frameWidth"; /** * 帧的高度 */ public static A_FRAME_HEIGHT:string = "frameHeight"; /** * 版本 */ public static A_VERSION:string = "version"; /** * 图片路径 */ public static A_IMAGE_PATH:string = "imagePath"; /** * 帧速率 */ public static A_FRAME_RATE:string = "frameRate"; /** * 名字 */ public static A_NAME:string = "name"; /** * 是否是全局 */ public static A_IS_GLOBAL:string = "isGlobal"; /** * 父亲 */ public static A_PARENT:string = "parent"; /** * 长度 */ public static A_LENGTH:string = "length"; /** * 类型 */ public static A_TYPE:string = "type"; /** * 缓入事件 */ public static A_FADE_IN_TIME:string = "fadeInTime"; /** * 持续时长 */ public static A_DURATION:string = "duration"; /**
/** * 偏移 */ public static A_OFFSET:string = "offset"; /** * 循环 */ public static A_LOOP:string = "loop"; /** * 事件 */ public static A_EVENT:string = "event"; /** * 事件参数 */ public static A_EVENT_PARAMETERS:string = "eventParameters"; /** * 声音 */ public static A_SOUND:string = "sound"; /** * 动作 */ public static A_ACTION:string = "action"; /** * 隐藏 */ public static A_HIDE:string = "hide"; /** * 自动补间 */ public static A_AUTO_TWEEN:string ="autoTween"; /** * 补间缓动 */ public static A_TWEEN_EASING:string = "tweenEasing"; /** * 补间旋转 */ public static A_TWEEN_ROTATE:string = "tweenRotate"; /** * 补间缩放 */ public static A_TWEEN_SCALE:string = "tweenScale"; /** * 显示对象序号 */ public static A_DISPLAY_INDEX:string = "displayIndex"; /** * z轴 */ public static A_Z_ORDER:string = "z"; /** * 混合模式 */ public static A_BLENDMODE:string = "blendMode"; /** * 宽度 */ public static A_WIDTH:string = "width"; /** * 高度 */ public static A_HEIGHT:string = "height"; /** * 继承缩放 */ public static A_INHERIT_SCALE:string = "inheritScale"; /** * 继承旋转 */ public static A_INHERIT_ROTATION:string = "inheritRotation"; /** * x轴 */ public static A_X:string = "x"; /** * y轴 */ public static A_Y:string = "y"; /** * x方向斜切 */ public static A_SKEW_X:string = "skX"; /** * y方向斜切 */ public static A_SKEW_Y:string = "skY"; /** * x方向缩放 */ public static A_SCALE_X:string = "scX"; /** * y方向缩放 */ public static A_SCALE_Y:string = "scY"; /** * 轴点的x坐标 */ public static A_PIVOT_X:string = "pX"; /** * 轴点的y坐标 */ public static A_PIVOT_Y:string = "pY"; /** * 透明度的偏移 */ public static A_ALPHA_OFFSET:string = "aO"; /** * 红色的偏移 */ public static A_RED_OFFSET:string = "rO"; /** * 绿色的偏移 */ public static A_GREEN_OFFSET:string = "gO"; /** * 蓝色的偏移 */ public static A_BLUE_OFFSET:string = "bO"; /** * 透明度的倍数 */ public static A_ALPHA_MULTIPLIER:string = "aM"; /** * 红色的倍数 */ public static A_RED_MULTIPLIER:string = "rM"; /** * 绿色的倍数 */ public static A_GREEN_MULTIPLIER:string = "gM"; /** * 蓝色的倍数 */ public static A_BLUE_MULTIPLIER:string = "bM"; /** * x方向缩放的偏移 */ public static A_SCALE_X_OFFSET:string = "scXOffset"; /** * y方向的偏移 */ public static A_SCALE_Y_OFFSET:string = "scYOffset"; /** * 缩放模式 */ public static A_SCALE_MODE:string = "scaleMode"; /** * 旋转修正 */ public static A_FIXED_ROTATION:string = "fixedRotation"; } }
* 缩放 */ public static A_SCALE:string = "scale";
random_line_split
xmodule_django.py
""" Exposes Django utilities for consumption in the xmodule library NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django runtime environment with the djangoapps in common configured to load """ import webpack_loader # NOTE: we are importing this method so that any module that imports us has access to get_current_request from crum import get_current_request def get_current_request_hostname(): """ This method will return the hostname that was used in the current Django request """ hostname = None request = get_current_request() if request: hostname = request.META.get('HTTP_HOST') return hostname def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='DEFAULT'): """ Add all webpack chunks to the supplied fragment as the appropriate resource type. """ for chunk in webpack_loader.utils.get_files(bundle_name, extension, config): if chunk['name'].endswith(('.js', '.js.gz')): fragment.add_javascript_url(chunk['url']) elif chunk['name'].endswith(('.css', '.css.gz')):
fragment.add_css_url(chunk['url'])
conditional_block
xmodule_django.py
""" Exposes Django utilities for consumption in the xmodule library NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django runtime environment with the djangoapps in common configured to load """ import webpack_loader # NOTE: we are importing this method so that any module that imports us has access to get_current_request from crum import get_current_request def
(): """ This method will return the hostname that was used in the current Django request """ hostname = None request = get_current_request() if request: hostname = request.META.get('HTTP_HOST') return hostname def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='DEFAULT'): """ Add all webpack chunks to the supplied fragment as the appropriate resource type. """ for chunk in webpack_loader.utils.get_files(bundle_name, extension, config): if chunk['name'].endswith(('.js', '.js.gz')): fragment.add_javascript_url(chunk['url']) elif chunk['name'].endswith(('.css', '.css.gz')): fragment.add_css_url(chunk['url'])
get_current_request_hostname
identifier_name
xmodule_django.py
""" Exposes Django utilities for consumption in the xmodule library NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django runtime environment with the djangoapps in common configured to load """ import webpack_loader # NOTE: we are importing this method so that any module that imports us has access to get_current_request from crum import get_current_request def get_current_request_hostname(): """ This method will return the hostname that was used in the current Django request """ hostname = None request = get_current_request() if request: hostname = request.META.get('HTTP_HOST') return hostname def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='DEFAULT'): """ Add all webpack chunks to the supplied fragment as the appropriate resource type. """ for chunk in webpack_loader.utils.get_files(bundle_name, extension, config): if chunk['name'].endswith(('.js', '.js.gz')): fragment.add_javascript_url(chunk['url']) elif chunk['name'].endswith(('.css', '.css.gz')):
fragment.add_css_url(chunk['url'])
random_line_split
xmodule_django.py
""" Exposes Django utilities for consumption in the xmodule library NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django runtime environment with the djangoapps in common configured to load """ import webpack_loader # NOTE: we are importing this method so that any module that imports us has access to get_current_request from crum import get_current_request def get_current_request_hostname():
def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='DEFAULT'): """ Add all webpack chunks to the supplied fragment as the appropriate resource type. """ for chunk in webpack_loader.utils.get_files(bundle_name, extension, config): if chunk['name'].endswith(('.js', '.js.gz')): fragment.add_javascript_url(chunk['url']) elif chunk['name'].endswith(('.css', '.css.gz')): fragment.add_css_url(chunk['url'])
""" This method will return the hostname that was used in the current Django request """ hostname = None request = get_current_request() if request: hostname = request.META.get('HTTP_HOST') return hostname
identifier_body
test_inline_arbitrary_chapel.py
from pych.extern import Chapel import os.path currentloc = os.path.dirname(os.path.realpath(__file__)) # Don't have a way to specify where the Chapel module arbitraryfile would live # The intention seems to be the addition of an argument lib to @Chapel @Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')]) def useArbitrary(): """ use arbitraryfile; writeln(foo(1, 2)); // Should be 6 writeln(bar()); // Should be: 14 14 3 14 14 // 14 14 3 14 14 writeln(baz()); // Should be: (contents = 3.0) // (contents = 3.0) """ return None if __name__ == "__main__":
import testcase # contains the general testing method, which allows us to gather output def test_using_other_chapel_code(): """ ensures that an inline definition of a Chapel function with a use statement will work when the module being used lives in a directory specified with the decorator argument "module_dirs" """ out = testcase.runpy(os.path.realpath(__file__)) assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\n(contents = 3.0)\n(contents = 3.0)\n')
useArbitrary()
conditional_block
test_inline_arbitrary_chapel.py
from pych.extern import Chapel import os.path currentloc = os.path.dirname(os.path.realpath(__file__)) # Don't have a way to specify where the Chapel module arbitraryfile would live # The intention seems to be the addition of an argument lib to @Chapel @Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')]) def useArbitrary(): """ use arbitraryfile; writeln(foo(1, 2)); // Should be 6 writeln(bar()); // Should be: 14 14 3 14 14 // 14 14 3 14 14 writeln(baz()); // Should be: (contents = 3.0) // (contents = 3.0) """ return None if __name__ == "__main__": useArbitrary() import testcase # contains the general testing method, which allows us to gather output def test_using_other_chapel_code():
""" ensures that an inline definition of a Chapel function with a use statement will work when the module being used lives in a directory specified with the decorator argument "module_dirs" """ out = testcase.runpy(os.path.realpath(__file__)) assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\n(contents = 3.0)\n(contents = 3.0)\n')
identifier_body
test_inline_arbitrary_chapel.py
from pych.extern import Chapel import os.path currentloc = os.path.dirname(os.path.realpath(__file__)) # Don't have a way to specify where the Chapel module arbitraryfile would live # The intention seems to be the addition of an argument lib to @Chapel @Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')]) def
(): """ use arbitraryfile; writeln(foo(1, 2)); // Should be 6 writeln(bar()); // Should be: 14 14 3 14 14 // 14 14 3 14 14 writeln(baz()); // Should be: (contents = 3.0) // (contents = 3.0) """ return None if __name__ == "__main__": useArbitrary() import testcase # contains the general testing method, which allows us to gather output def test_using_other_chapel_code(): """ ensures that an inline definition of a Chapel function with a use statement will work when the module being used lives in a directory specified with the decorator argument "module_dirs" """ out = testcase.runpy(os.path.realpath(__file__)) assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\n(contents = 3.0)\n(contents = 3.0)\n')
useArbitrary
identifier_name
test_inline_arbitrary_chapel.py
from pych.extern import Chapel import os.path currentloc = os.path.dirname(os.path.realpath(__file__)) # Don't have a way to specify where the Chapel module arbitraryfile would live # The intention seems to be the addition of an argument lib to @Chapel @Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')]) def useArbitrary(): """ use arbitraryfile; writeln(foo(1, 2)); // Should be 6 writeln(bar()); // Should be: 14 14 3 14 14 // 14 14 3 14 14 writeln(baz()); // Should be: (contents = 3.0) // (contents = 3.0) """ return None if __name__ == "__main__": useArbitrary() import testcase # contains the general testing method, which allows us to gather output def test_using_other_chapel_code(): """
the decorator argument "module_dirs" """ out = testcase.runpy(os.path.realpath(__file__)) assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\n(contents = 3.0)\n(contents = 3.0)\n')
ensures that an inline definition of a Chapel function with a use statement will work when the module being used lives in a directory specified with
random_line_split
mod.rs
use super::Numeric; use std::ops::{Add, Sub, Mul, Div, Rem}; use std::ops; use std::convert; use std::mem::transmute; #[cfg(test)] mod test; #[macro_use] mod macros; pub trait Matrix<N>: Sized { fn nrows(&self) -> usize; fn ncols(&self) -> usize; } //#[cfg(not(simd))]
//pub struct Matrix2<N> //where N: Numeric { pub x1y1: N, pub x2y1: N // , pub x1y2: N, pub x2y2: N // } // // #[cfg(not(simd))] // #[repr(C)] // #[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Debug, Hash)] //pub struct Matrix3<N> //where N: Numeric { pub x1y1: N, pub x2y1: N, pub x3y1: N // , pub x1y2: N, pub x2y2: N, pub x3y2: N // , pub x1y3: N, pub x2y3: N, pub x3y3: N // } // // #[cfg(not(simd))] // #[repr(C)] // #[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Debug, Hash)] //pub struct Matrix4<N> { // pub x1y1: N, pub x2y1: N, pub x3y1: N, pub x4y1: N // , pub x1y2: N, pub x2y2: N, pub x3y2: N, pub x4y2: N // , pub x1y3: N, pub x2y3: N, pub x3y3: N, pub x4y3: N // , pub x1y4: N, pub x2y4: N, pub x3y4: N, pub x4y4: N // } make_matrix! { Matrix2, rows: 2, cols: 2 , x1y1, x2y1 , x1y2, x2y2 } make_matrix! { Matrix3, rows: 3, cols: 3 , x1y1, x2y1, x3y1 , x1y2, x2y2, x3y2 , x1y3, x2y3, x3y3 } make_matrix! { Matrix4, rows: 4, cols: 4 , x1y1, x2y1, x3y1, x4y1 , x1y2, x2y2, x3y2, x4y2 , x1y3, x2y3, x3y3, x4y3 , x1y4, x2y4, x3y4, x4y4 } //impl_converts! { Matrix2, 2 // , Matrix3, 3 // , Matrix4, 4 // } //impl_index! { Matrix2, 2 // , Matrix3, 3 // , Matrix4, 4 // }
//#[repr(C)] //#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Debug, Hash)]
random_line_split
urls.py
#-*- coding: utf-8 -*-
app_name = "perso" urlpatterns = [ url(r'^$', views.main, name='main'), url(r'^(?P<pageId>[0-9]+)/?$', views.main, name='main'), url(r'^about/?$', views.about, name='about'), url(r'^contact/?$', views.contact, name='contact'), url(r'^(?P<cat_slug>[-a-zA-Z0-9_]+)/?$', views.main, name='main'), url(r'^(?P<cat_slug>[-a-zA-Z0-9_]+)/(?P<pageId>[0-9]+)/?$', views.main, name='main'), url(r'^publication/(?P<slug>[-a-zA-Z0-9_]+)/?$', views.publication, name='publication'), url(r'^tag/(?P<slug>[-a-zA-Z0-9_]+)/?$', views.tag, name='tag'), ]
from django.conf.urls import url from . import views
random_line_split
textSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import strings = require('vs/base/common/strings'); import assert = require('assert'); import fs = require('fs');
import {FileWalker} from 'vs/workbench/services/search/node/fileSearch'; import {UTF16le, UTF16be, UTF8, detectEncodingByBOMFromBuffer} from 'vs/base/node/encoding'; import {ISerializedFileMatch, IRawSearch, ISearchEngine} from 'vs/workbench/services/search/node/rawSearchService'; export class Engine implements ISearchEngine { private rootPaths: string[]; private maxResults: number; private walker: FileWalker; private contentPattern: RegExp; private isCanceled: boolean; private isDone: boolean; private total: number = 0; private worked: number = 0; private walkerError: Error; private walkerIsDone: boolean; private fileEncoding: string; constructor(config: IRawSearch, walker: FileWalker) { this.rootPaths = config.rootPaths; this.walker = walker; this.contentPattern = strings.createRegExp(config.contentPattern.pattern, config.contentPattern.isRegExp, config.contentPattern.isCaseSensitive, config.contentPattern.isWordMatch); this.isCanceled = false; this.maxResults = config.maxResults; this.worked = 0; this.total = 0; this.fileEncoding = iconv.encodingExists(config.fileEncoding) ? config.fileEncoding : UTF8; } public cancel(): void { this.isCanceled = true; this.walker.cancel(); } public search(onResult: (match: ISerializedFileMatch) => void, onProgress: (progress: IProgress) => void, done: (error: Error, isLimitHit: boolean) => void): void { let resultCounter = 0; let limitReached = false; let unwind = (processed: number) => { this.worked += processed; // Emit progress() if (processed && !this.isDone) { onProgress({ total: this.total, worked: this.worked }); } // Emit done() if (this.worked === this.total && this.walkerIsDone && !this.isDone) { this.isDone = true; done(this.walkerError, limitReached); } }; this.walker.walk(this.rootPaths, (result) => { // Indicate progress to the outside this.total++; onProgress({ total: this.total, worked: this.worked }); // If the result is empty or we have reached the limit or we are canceled, ignore it if (limitReached || this.isCanceled) { return unwind(1); } // Need to detect mime type now to find out if the file is binary or not this.isBinary(result.path, (isBinary: boolean) => { // If the file does not have textual content, do not return it as a result if (isBinary) { return unwind(1); } let fileMatch: FileMatch = null; let doneCallback = (error?: Error) => { // If the result is empty or we have reached the limit or we are canceled, ignore it if (error || !fileMatch || fileMatch.isEmpty() || this.isCanceled) { return unwind(1); } // Otherwise send it back as result else { onResult(fileMatch.serialize()); return unwind(1); } }; let perLineCallback = (line: string, lineNumber: number) => { if (limitReached || this.isCanceled) { return; // return early if canceled or limit reached } let lineMatch: LineMatch = null; let match = this.contentPattern.exec(line); // Record all matches into file result while (match !== null && match[0].length > 0 && !limitReached && !this.isCanceled) { resultCounter++; if (this.maxResults && resultCounter >= this.maxResults) { limitReached = true; } if (fileMatch === null) { fileMatch = new FileMatch(result.path); } if (lineMatch === null) { lineMatch = new LineMatch(line, lineNumber); fileMatch.addMatch(lineMatch); } lineMatch.addMatch(match.index, match[0].length); match = this.contentPattern.exec(line); } }; // Read lines buffered to support large files readlinesAsync(result.path, perLineCallback, { bufferLength: 8096, encoding: this.fileEncoding }, doneCallback); }); }, (error, isLimitHit) => { this.walkerIsDone = true; this.walkerError = error; unwind(0 /* walker is done, indicate this back to our handler to be able to unwind */); }); } private isBinary(path: string, callback: (isBinary: boolean) => void): void { // Return early if we guess that the file is text or binary let mimes = baseMime.guessMimeTypes(path); if (mimes.indexOf(baseMime.MIME_TEXT) >= 0) { return callback(false); } if (mimes.indexOf(baseMime.MIME_BINARY) >= 0) { return callback(true); } // Otherwise do full blown detection return detectMimesFromFile(path, (error: Error, result: IMimeAndEncoding) => { callback(!!error || result.mimes[result.mimes.length - 1] !== baseMime.MIME_TEXT); }); } } interface ReadLinesOptions { bufferLength: number; encoding: string; } function readlinesAsync(filename: string, perLineCallback: (line: string, lineNumber: number) => void, options: ReadLinesOptions, callback: (error: Error) => void): void { fs.open(filename, 'r', null, (error: Error, fd: number) => { if (error) { return callback(error); } let buffer = new Buffer(options.bufferLength); let pos: number, i: number; let line = ''; let lineNumber = 0; let lastBufferHadTraillingCR = false; function call(n: number): void { line += iconv.decode(buffer.slice(pos, i + n), options.encoding); perLineCallback(line, lineNumber); line = ''; lineNumber++; pos = i + n; } function readFile(clb: (error: Error) => void): void { fs.read(fd, buffer, 0, buffer.length, null, (error: Error, bytesRead: number, buffer: NodeBuffer) => { if (error) { return clb(error); } if (bytesRead === 0) { return clb(null); } pos = 0; i = 0; // BOMs override the configured encoding so we want to detec them let enc = detectEncodingByBOMFromBuffer(buffer, bytesRead); switch (enc) { case UTF8: pos = i = 3; options.encoding = UTF8; break; case UTF16be: pos = i = 2; options.encoding = UTF16be; break; case UTF16le: pos = i = 2; options.encoding = UTF16le; break; } if (lastBufferHadTraillingCR) { if (buffer[i] === 0x0a) { call(1); i++; } else { call(0); } lastBufferHadTraillingCR = false; } for (; i < bytesRead; ++i) { if (buffer[i] === 0x0a) { call(1); } else if (buffer[i] === 0x0d) { if (i + 1 === bytesRead) { lastBufferHadTraillingCR = true; } else if (buffer[i + 1] === 0x0a) { call(2); i++; } else { call(1); } } } line += iconv.decode(buffer.slice(pos, bytesRead), options.encoding); readFile(clb); // Continue reading }); } readFile((error: Error) => { if (error) { return callback(error); } if (line.length) { perLineCallback(line, lineNumber); } fs.close(fd, (error: Error) => { callback(error); }); }); }); } class FileMatch implements ISerializedFileMatch { public path: string; public lineMatches: LineMatch[]; constructor(path: string) { this.path = path; this.lineMatches = []; } public addMatch(lineMatch: LineMatch): void { assert.ok(lineMatch, 'Missing parameter (lineMatch = ' + lineMatch + ')'); this.lineMatches.push(lineMatch); } public isEmpty(): boolean { return this.lineMatches.length === 0; } public serialize(): ISerializedFileMatch { let lineMatches: ILineMatch[] = []; for (let i = 0; i < this.lineMatches.length; i++) { lineMatches.push(this.lineMatches[i].serialize()); } return { path: this.path, lineMatches: lineMatches }; } } class LineMatch implements ILineMatch { public preview: string; public lineNumber: number; public offsetAndLengths: number[][]; constructor(preview: string, lineNumber: number) { assert.ok(preview, 'Missing parameter (content = ' + preview + ')'); assert.ok(!isNaN(Number(lineNumber)) && lineNumber >= 0, 'LineNumber must be positive'); this.preview = preview.replace(/(\r|\n)*$/, ''); this.lineNumber = lineNumber; this.offsetAndLengths = []; } public getText(): string { return this.preview; } public getLineNumber(): number { return this.lineNumber; } public addMatch(offset: number, length: number): void { assert.ok(!isNaN(Number(offset)) && offset >= 0, 'Offset must be positive'); assert.ok(!isNaN(Number(length)) && length >= 0, 'Length must be positive'); this.offsetAndLengths.push([offset, length]); } public serialize(): ILineMatch { let result = { preview: this.preview, lineNumber: this.lineNumber, offsetAndLengths: this.offsetAndLengths }; return result; } }
import iconv = require('iconv-lite'); import baseMime = require('vs/base/common/mime'); import {ILineMatch, IProgress} from 'vs/platform/search/common/search'; import {detectMimesFromFile, IMimeAndEncoding} from 'vs/base/node/mime';
random_line_split
textSearch.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import strings = require('vs/base/common/strings'); import assert = require('assert'); import fs = require('fs'); import iconv = require('iconv-lite'); import baseMime = require('vs/base/common/mime'); import {ILineMatch, IProgress} from 'vs/platform/search/common/search'; import {detectMimesFromFile, IMimeAndEncoding} from 'vs/base/node/mime'; import {FileWalker} from 'vs/workbench/services/search/node/fileSearch'; import {UTF16le, UTF16be, UTF8, detectEncodingByBOMFromBuffer} from 'vs/base/node/encoding'; import {ISerializedFileMatch, IRawSearch, ISearchEngine} from 'vs/workbench/services/search/node/rawSearchService'; export class Engine implements ISearchEngine { private rootPaths: string[]; private maxResults: number; private walker: FileWalker; private contentPattern: RegExp; private isCanceled: boolean; private isDone: boolean; private total: number = 0; private worked: number = 0; private walkerError: Error; private walkerIsDone: boolean; private fileEncoding: string; constructor(config: IRawSearch, walker: FileWalker) { this.rootPaths = config.rootPaths; this.walker = walker; this.contentPattern = strings.createRegExp(config.contentPattern.pattern, config.contentPattern.isRegExp, config.contentPattern.isCaseSensitive, config.contentPattern.isWordMatch); this.isCanceled = false; this.maxResults = config.maxResults; this.worked = 0; this.total = 0; this.fileEncoding = iconv.encodingExists(config.fileEncoding) ? config.fileEncoding : UTF8; } public cancel(): void { this.isCanceled = true; this.walker.cancel(); } public search(onResult: (match: ISerializedFileMatch) => void, onProgress: (progress: IProgress) => void, done: (error: Error, isLimitHit: boolean) => void): void { let resultCounter = 0; let limitReached = false; let unwind = (processed: number) => { this.worked += processed; // Emit progress() if (processed && !this.isDone) { onProgress({ total: this.total, worked: this.worked }); } // Emit done() if (this.worked === this.total && this.walkerIsDone && !this.isDone) { this.isDone = true; done(this.walkerError, limitReached); } }; this.walker.walk(this.rootPaths, (result) => { // Indicate progress to the outside this.total++; onProgress({ total: this.total, worked: this.worked }); // If the result is empty or we have reached the limit or we are canceled, ignore it if (limitReached || this.isCanceled) { return unwind(1); } // Need to detect mime type now to find out if the file is binary or not this.isBinary(result.path, (isBinary: boolean) => { // If the file does not have textual content, do not return it as a result if (isBinary) { return unwind(1); } let fileMatch: FileMatch = null; let doneCallback = (error?: Error) => { // If the result is empty or we have reached the limit or we are canceled, ignore it if (error || !fileMatch || fileMatch.isEmpty() || this.isCanceled) { return unwind(1); } // Otherwise send it back as result else { onResult(fileMatch.serialize()); return unwind(1); } }; let perLineCallback = (line: string, lineNumber: number) => { if (limitReached || this.isCanceled) { return; // return early if canceled or limit reached } let lineMatch: LineMatch = null; let match = this.contentPattern.exec(line); // Record all matches into file result while (match !== null && match[0].length > 0 && !limitReached && !this.isCanceled) { resultCounter++; if (this.maxResults && resultCounter >= this.maxResults) { limitReached = true; } if (fileMatch === null) { fileMatch = new FileMatch(result.path); } if (lineMatch === null) { lineMatch = new LineMatch(line, lineNumber); fileMatch.addMatch(lineMatch); } lineMatch.addMatch(match.index, match[0].length); match = this.contentPattern.exec(line); } }; // Read lines buffered to support large files readlinesAsync(result.path, perLineCallback, { bufferLength: 8096, encoding: this.fileEncoding }, doneCallback); }); }, (error, isLimitHit) => { this.walkerIsDone = true; this.walkerError = error; unwind(0 /* walker is done, indicate this back to our handler to be able to unwind */); }); } private isBinary(path: string, callback: (isBinary: boolean) => void): void { // Return early if we guess that the file is text or binary let mimes = baseMime.guessMimeTypes(path); if (mimes.indexOf(baseMime.MIME_TEXT) >= 0) { return callback(false); } if (mimes.indexOf(baseMime.MIME_BINARY) >= 0) { return callback(true); } // Otherwise do full blown detection return detectMimesFromFile(path, (error: Error, result: IMimeAndEncoding) => { callback(!!error || result.mimes[result.mimes.length - 1] !== baseMime.MIME_TEXT); }); } } interface ReadLinesOptions { bufferLength: number; encoding: string; } function readlinesAsync(filename: string, perLineCallback: (line: string, lineNumber: number) => void, options: ReadLinesOptions, callback: (error: Error) => void): void { fs.open(filename, 'r', null, (error: Error, fd: number) => { if (error) { return callback(error); } let buffer = new Buffer(options.bufferLength); let pos: number, i: number; let line = ''; let lineNumber = 0; let lastBufferHadTraillingCR = false; function call(n: number): void { line += iconv.decode(buffer.slice(pos, i + n), options.encoding); perLineCallback(line, lineNumber); line = ''; lineNumber++; pos = i + n; } function readFile(clb: (error: Error) => void): void { fs.read(fd, buffer, 0, buffer.length, null, (error: Error, bytesRead: number, buffer: NodeBuffer) => { if (error) { return clb(error); } if (bytesRead === 0) { return clb(null); } pos = 0; i = 0; // BOMs override the configured encoding so we want to detec them let enc = detectEncodingByBOMFromBuffer(buffer, bytesRead); switch (enc) { case UTF8: pos = i = 3; options.encoding = UTF8; break; case UTF16be: pos = i = 2; options.encoding = UTF16be; break; case UTF16le: pos = i = 2; options.encoding = UTF16le; break; } if (lastBufferHadTraillingCR) { if (buffer[i] === 0x0a) { call(1); i++; } else { call(0); } lastBufferHadTraillingCR = false; } for (; i < bytesRead; ++i) { if (buffer[i] === 0x0a) { call(1); } else if (buffer[i] === 0x0d) { if (i + 1 === bytesRead) { lastBufferHadTraillingCR = true; } else if (buffer[i + 1] === 0x0a) { call(2); i++; } else { call(1); } } } line += iconv.decode(buffer.slice(pos, bytesRead), options.encoding); readFile(clb); // Continue reading }); } readFile((error: Error) => { if (error) { return callback(error); } if (line.length) { perLineCallback(line, lineNumber); } fs.close(fd, (error: Error) => { callback(error); }); }); }); } class
implements ISerializedFileMatch { public path: string; public lineMatches: LineMatch[]; constructor(path: string) { this.path = path; this.lineMatches = []; } public addMatch(lineMatch: LineMatch): void { assert.ok(lineMatch, 'Missing parameter (lineMatch = ' + lineMatch + ')'); this.lineMatches.push(lineMatch); } public isEmpty(): boolean { return this.lineMatches.length === 0; } public serialize(): ISerializedFileMatch { let lineMatches: ILineMatch[] = []; for (let i = 0; i < this.lineMatches.length; i++) { lineMatches.push(this.lineMatches[i].serialize()); } return { path: this.path, lineMatches: lineMatches }; } } class LineMatch implements ILineMatch { public preview: string; public lineNumber: number; public offsetAndLengths: number[][]; constructor(preview: string, lineNumber: number) { assert.ok(preview, 'Missing parameter (content = ' + preview + ')'); assert.ok(!isNaN(Number(lineNumber)) && lineNumber >= 0, 'LineNumber must be positive'); this.preview = preview.replace(/(\r|\n)*$/, ''); this.lineNumber = lineNumber; this.offsetAndLengths = []; } public getText(): string { return this.preview; } public getLineNumber(): number { return this.lineNumber; } public addMatch(offset: number, length: number): void { assert.ok(!isNaN(Number(offset)) && offset >= 0, 'Offset must be positive'); assert.ok(!isNaN(Number(length)) && length >= 0, 'Length must be positive'); this.offsetAndLengths.push([offset, length]); } public serialize(): ILineMatch { let result = { preview: this.preview, lineNumber: this.lineNumber, offsetAndLengths: this.offsetAndLengths }; return result; } }
FileMatch
identifier_name
Logger.js
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * "Ancilla Libary" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } } } return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions ){ return _.extend( this.__oOptions, oOptions ); } __getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } }
( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
__getTag
identifier_name
Logger.js
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * "Ancilla Libary" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } } } return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions ){ return _.extend( this.__oOptions, oOptions );
} __getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } } __getTag( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
random_line_split
Logger.js
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * "Ancilla Libary" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) )
} return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions ){ return _.extend( this.__oOptions, oOptions ); } __getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } } __getTag( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
{ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } }
conditional_block
Logger.js
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * "Ancilla Libary" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } } } return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions )
__getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } } __getTag( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
{ return _.extend( this.__oOptions, oOptions ); }
identifier_body
user_update_eligibility.py
from datetime import timedelta import logging from django.utils.timezone import now from django.core.management.base import BaseCommand from TWLight.users.models import Editor from TWLight.users.helpers.editor_data import ( editor_global_userinfo, editor_valid, editor_enough_edits, editor_not_blocked, editor_bundle_eligible, editor_account_old_enough, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Updates editor info and Bundle eligibility for currently-eligible Editors." def add_arguments(self, parser): """ Adds command arguments. """ parser.add_argument( "--datetime", action="store", help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.", ) parser.add_argument( "--global_userinfo", action="store", help="Specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.", ) parser.add_argument( "--timedelta_days", action="store", help="Number of days used to define 'recent' edits. Defaults to 30. Currently only used for faking command runs in tests.", ) parser.add_argument( "--wp_username", action="store", help="Specify a single editor to update. Other arguments and filters still apply.", ) def handle(self, *args, **options): """ Updates editor info and Bundle eligibility for currently-eligible Editors. Parameters ---------- args options Returns ------- None """ # Default behavior is to use current datetime for timestamps to check all editors. now_or_datetime = now() datetime_override = None timedelta_days = 0 wp_username = None editors = Editor.objects.all() # This may be overridden so that values may be treated as if they were valid for an arbitrary datetime. # This is also passed to the model method. if options["datetime"]:
# These are used to limit the set of editors updated by the command. # Nothing is passed to the model method. if options["timedelta_days"]: timedelta_days = int(options["timedelta_days"]) # Get editors that haven't been updated in the specified time range, with an option to limit on wp_username. if timedelta_days: editors = editors.exclude( editorlogs__timestamp__gt=now_or_datetime - timedelta(days=timedelta_days), ) # Optional wp_username filter. if options["wp_username"]: editors = editors.filter(wp_username=str(options["wp_username"])) # Iterator reduces memory footprint for large querysets for editor in editors.iterator(): # T296853: avoid stale editor data while looping through big sets. editor.refresh_from_db() # `global_userinfo` data may be overridden. if options["global_userinfo"]: global_userinfo = options["global_userinfo"] editor.check_sub(global_userinfo["id"]) # Default behavior is to fetch live `global_userinfo` else: global_userinfo = editor_global_userinfo(editor.wp_sub) if global_userinfo: editor.update_editcount(global_userinfo["editcount"], datetime_override) # Determine editor validity. editor.wp_enough_edits = editor_enough_edits(editor.wp_editcount) editor.wp_not_blocked = editor_not_blocked(global_userinfo["merged"]) # We will only check if the account is old enough if the value is False # Accounts that are already old enough will never cease to be old enough if not editor.wp_account_old_enough: editor.wp_account_old_enough = editor_account_old_enough( editor.wp_registered ) editor.wp_valid = editor_valid( editor.wp_enough_edits, editor.wp_account_old_enough, # editor.wp_not_blocked can only be rechecked on login, so we're going with the existing value. editor.wp_not_blocked, editor.ignore_wp_blocks, ) # Determine Bundle eligibility. editor.wp_bundle_eligible = editor_bundle_eligible(editor) # Save editor. editor.save() # Prune EditorLogs, with daily_prune_range set to only check the previous day to improve performance. editor.prune_editcount( current_datetime=datetime_override, daily_prune_range=2 ) # Update bundle authorizations. editor.update_bundle_authorization()
datetime_override = now_or_datetime.fromisoformat(options["datetime"]) now_or_datetime = datetime_override
conditional_block
user_update_eligibility.py
from datetime import timedelta import logging from django.utils.timezone import now from django.core.management.base import BaseCommand from TWLight.users.models import Editor from TWLight.users.helpers.editor_data import ( editor_global_userinfo, editor_valid, editor_enough_edits, editor_not_blocked, editor_bundle_eligible, editor_account_old_enough, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Updates editor info and Bundle eligibility for currently-eligible Editors." def add_arguments(self, parser):
def handle(self, *args, **options): """ Updates editor info and Bundle eligibility for currently-eligible Editors. Parameters ---------- args options Returns ------- None """ # Default behavior is to use current datetime for timestamps to check all editors. now_or_datetime = now() datetime_override = None timedelta_days = 0 wp_username = None editors = Editor.objects.all() # This may be overridden so that values may be treated as if they were valid for an arbitrary datetime. # This is also passed to the model method. if options["datetime"]: datetime_override = now_or_datetime.fromisoformat(options["datetime"]) now_or_datetime = datetime_override # These are used to limit the set of editors updated by the command. # Nothing is passed to the model method. if options["timedelta_days"]: timedelta_days = int(options["timedelta_days"]) # Get editors that haven't been updated in the specified time range, with an option to limit on wp_username. if timedelta_days: editors = editors.exclude( editorlogs__timestamp__gt=now_or_datetime - timedelta(days=timedelta_days), ) # Optional wp_username filter. if options["wp_username"]: editors = editors.filter(wp_username=str(options["wp_username"])) # Iterator reduces memory footprint for large querysets for editor in editors.iterator(): # T296853: avoid stale editor data while looping through big sets. editor.refresh_from_db() # `global_userinfo` data may be overridden. if options["global_userinfo"]: global_userinfo = options["global_userinfo"] editor.check_sub(global_userinfo["id"]) # Default behavior is to fetch live `global_userinfo` else: global_userinfo = editor_global_userinfo(editor.wp_sub) if global_userinfo: editor.update_editcount(global_userinfo["editcount"], datetime_override) # Determine editor validity. editor.wp_enough_edits = editor_enough_edits(editor.wp_editcount) editor.wp_not_blocked = editor_not_blocked(global_userinfo["merged"]) # We will only check if the account is old enough if the value is False # Accounts that are already old enough will never cease to be old enough if not editor.wp_account_old_enough: editor.wp_account_old_enough = editor_account_old_enough( editor.wp_registered ) editor.wp_valid = editor_valid( editor.wp_enough_edits, editor.wp_account_old_enough, # editor.wp_not_blocked can only be rechecked on login, so we're going with the existing value. editor.wp_not_blocked, editor.ignore_wp_blocks, ) # Determine Bundle eligibility. editor.wp_bundle_eligible = editor_bundle_eligible(editor) # Save editor. editor.save() # Prune EditorLogs, with daily_prune_range set to only check the previous day to improve performance. editor.prune_editcount( current_datetime=datetime_override, daily_prune_range=2 ) # Update bundle authorizations. editor.update_bundle_authorization()
""" Adds command arguments. """ parser.add_argument( "--datetime", action="store", help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.", ) parser.add_argument( "--global_userinfo", action="store", help="Specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.", ) parser.add_argument( "--timedelta_days", action="store", help="Number of days used to define 'recent' edits. Defaults to 30. Currently only used for faking command runs in tests.", ) parser.add_argument( "--wp_username", action="store", help="Specify a single editor to update. Other arguments and filters still apply.", )
identifier_body
user_update_eligibility.py
from datetime import timedelta import logging from django.utils.timezone import now from django.core.management.base import BaseCommand from TWLight.users.models import Editor from TWLight.users.helpers.editor_data import ( editor_global_userinfo, editor_valid, editor_enough_edits, editor_not_blocked, editor_bundle_eligible, editor_account_old_enough, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Updates editor info and Bundle eligibility for currently-eligible Editors." def
(self, parser): """ Adds command arguments. """ parser.add_argument( "--datetime", action="store", help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.", ) parser.add_argument( "--global_userinfo", action="store", help="Specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.", ) parser.add_argument( "--timedelta_days", action="store", help="Number of days used to define 'recent' edits. Defaults to 30. Currently only used for faking command runs in tests.", ) parser.add_argument( "--wp_username", action="store", help="Specify a single editor to update. Other arguments and filters still apply.", ) def handle(self, *args, **options): """ Updates editor info and Bundle eligibility for currently-eligible Editors. Parameters ---------- args options Returns ------- None """ # Default behavior is to use current datetime for timestamps to check all editors. now_or_datetime = now() datetime_override = None timedelta_days = 0 wp_username = None editors = Editor.objects.all() # This may be overridden so that values may be treated as if they were valid for an arbitrary datetime. # This is also passed to the model method. if options["datetime"]: datetime_override = now_or_datetime.fromisoformat(options["datetime"]) now_or_datetime = datetime_override # These are used to limit the set of editors updated by the command. # Nothing is passed to the model method. if options["timedelta_days"]: timedelta_days = int(options["timedelta_days"]) # Get editors that haven't been updated in the specified time range, with an option to limit on wp_username. if timedelta_days: editors = editors.exclude( editorlogs__timestamp__gt=now_or_datetime - timedelta(days=timedelta_days), ) # Optional wp_username filter. if options["wp_username"]: editors = editors.filter(wp_username=str(options["wp_username"])) # Iterator reduces memory footprint for large querysets for editor in editors.iterator(): # T296853: avoid stale editor data while looping through big sets. editor.refresh_from_db() # `global_userinfo` data may be overridden. if options["global_userinfo"]: global_userinfo = options["global_userinfo"] editor.check_sub(global_userinfo["id"]) # Default behavior is to fetch live `global_userinfo` else: global_userinfo = editor_global_userinfo(editor.wp_sub) if global_userinfo: editor.update_editcount(global_userinfo["editcount"], datetime_override) # Determine editor validity. editor.wp_enough_edits = editor_enough_edits(editor.wp_editcount) editor.wp_not_blocked = editor_not_blocked(global_userinfo["merged"]) # We will only check if the account is old enough if the value is False # Accounts that are already old enough will never cease to be old enough if not editor.wp_account_old_enough: editor.wp_account_old_enough = editor_account_old_enough( editor.wp_registered ) editor.wp_valid = editor_valid( editor.wp_enough_edits, editor.wp_account_old_enough, # editor.wp_not_blocked can only be rechecked on login, so we're going with the existing value. editor.wp_not_blocked, editor.ignore_wp_blocks, ) # Determine Bundle eligibility. editor.wp_bundle_eligible = editor_bundle_eligible(editor) # Save editor. editor.save() # Prune EditorLogs, with daily_prune_range set to only check the previous day to improve performance. editor.prune_editcount( current_datetime=datetime_override, daily_prune_range=2 ) # Update bundle authorizations. editor.update_bundle_authorization()
add_arguments
identifier_name
user_update_eligibility.py
from datetime import timedelta import logging from django.utils.timezone import now from django.core.management.base import BaseCommand from TWLight.users.models import Editor from TWLight.users.helpers.editor_data import ( editor_global_userinfo, editor_valid, editor_enough_edits, editor_not_blocked, editor_bundle_eligible, editor_account_old_enough, ) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Updates editor info and Bundle eligibility for currently-eligible Editors." def add_arguments(self, parser): """ Adds command arguments. """ parser.add_argument( "--datetime", action="store", help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.", ) parser.add_argument( "--global_userinfo", action="store",
) parser.add_argument( "--timedelta_days", action="store", help="Number of days used to define 'recent' edits. Defaults to 30. Currently only used for faking command runs in tests.", ) parser.add_argument( "--wp_username", action="store", help="Specify a single editor to update. Other arguments and filters still apply.", ) def handle(self, *args, **options): """ Updates editor info and Bundle eligibility for currently-eligible Editors. Parameters ---------- args options Returns ------- None """ # Default behavior is to use current datetime for timestamps to check all editors. now_or_datetime = now() datetime_override = None timedelta_days = 0 wp_username = None editors = Editor.objects.all() # This may be overridden so that values may be treated as if they were valid for an arbitrary datetime. # This is also passed to the model method. if options["datetime"]: datetime_override = now_or_datetime.fromisoformat(options["datetime"]) now_or_datetime = datetime_override # These are used to limit the set of editors updated by the command. # Nothing is passed to the model method. if options["timedelta_days"]: timedelta_days = int(options["timedelta_days"]) # Get editors that haven't been updated in the specified time range, with an option to limit on wp_username. if timedelta_days: editors = editors.exclude( editorlogs__timestamp__gt=now_or_datetime - timedelta(days=timedelta_days), ) # Optional wp_username filter. if options["wp_username"]: editors = editors.filter(wp_username=str(options["wp_username"])) # Iterator reduces memory footprint for large querysets for editor in editors.iterator(): # T296853: avoid stale editor data while looping through big sets. editor.refresh_from_db() # `global_userinfo` data may be overridden. if options["global_userinfo"]: global_userinfo = options["global_userinfo"] editor.check_sub(global_userinfo["id"]) # Default behavior is to fetch live `global_userinfo` else: global_userinfo = editor_global_userinfo(editor.wp_sub) if global_userinfo: editor.update_editcount(global_userinfo["editcount"], datetime_override) # Determine editor validity. editor.wp_enough_edits = editor_enough_edits(editor.wp_editcount) editor.wp_not_blocked = editor_not_blocked(global_userinfo["merged"]) # We will only check if the account is old enough if the value is False # Accounts that are already old enough will never cease to be old enough if not editor.wp_account_old_enough: editor.wp_account_old_enough = editor_account_old_enough( editor.wp_registered ) editor.wp_valid = editor_valid( editor.wp_enough_edits, editor.wp_account_old_enough, # editor.wp_not_blocked can only be rechecked on login, so we're going with the existing value. editor.wp_not_blocked, editor.ignore_wp_blocks, ) # Determine Bundle eligibility. editor.wp_bundle_eligible = editor_bundle_eligible(editor) # Save editor. editor.save() # Prune EditorLogs, with daily_prune_range set to only check the previous day to improve performance. editor.prune_editcount( current_datetime=datetime_override, daily_prune_range=2 ) # Update bundle authorizations. editor.update_bundle_authorization()
help="Specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.",
random_line_split
network_process.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on Jan 17, 2017 @author: hegxiten ''' import sys import geo.haversine as haversine from imposm.parser import OSMParser import geo.haversine as haversine import numpy import time from scipy import spatial import csv import codecs import math default_encoding='utf-8' if sys.getdefaultencoding()!=default_encoding: reload(sys) sys.setdefaultencoding(default_encoding)
def process_network(FOLDER,FILE,CONCURRENCYVAL,GLOBALROUNDINGDIGITS): stations={} '''stations[station_node_osmid]=[name, lat, lon]''' refnodes_index_dict={} '''refnodes_index_dict[nodeid]=listindex_of_nodeid''' refnodes=[] '''refnodes=[nodeid1,nodeid2,nodeid3...]''' refnodes_coord_list=[] '''refnodes_coord_list[coord1,coord2,coord3...]''' node_fromto_dict={} '''node_fromto_dict[fromnode]=[(fromnode,tonode1),(fromnode,tonode2),(fromnode,tonode3)...]''' distance_mapper={} '''distance_mapper[(fromnode,tonode)]=distance''' attribute_mapper={} '''attribute_mapper[(fromnode,tonode)]=attribute_dictionary''' midpoints_coord=[] '''miderpoint_map[(fromnode,tonode)]=(midercoord)''' midsegment=[] approxCoord_map={} '''approxCoord_map[coord]=nodeid(veryfirstone)''' refnode_mapper={} '''refnode_mapper[nodeid2]=nodeid1(previous_nodeid1 with the same coordinate as nodeid2 after digit rounding)''' edgeDict={} '''edgeDict[(vertex tuple)]=(edgereflist,edgelength)''' disconnected_stations=[] connected_stations=[] def loadstations(): '''Load stations from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_stations.csv', 'rb') as csvfile: '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: stations[int(row[0])]=[row[1],float(row[2]),float(row[3])] stopt=time.time() print("Loading stations. Time:("+str(stopt-startt)+")") def loadcoordinates(): '''Load coordinates of reference-nodes from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegment_nodecoords.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>123(osmid),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: c1,c2=float(row[1]),float(row[2]) '''c1--lat, c2--lon''' #c1,c2=round(float(row[1]),ROUNDINGDIGITS),round(float(row[2]),ROUNDINGDIGITS) if (c1,c2) not in approxCoord_map: approxCoord_map[(c1,c2)]=int(row[0]) '''row[0]--coordid''' refnodes_index_dict[int(row[0])]=len(refnodes_coord_list) refnodes.append(int(row[0])) refnodes_coord_list.append((c1,c2)) refnode_mapper[int(row[0])]=int(row[0]) else: refnode_mapper[int(row[0])]=approxCoord_map[(c1,c2)] stopt=time.time() print("Loading refnode coordinates. Time:("+str(stopt-startt)+")") def loadwaysegments(): '''Load way segments from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegments.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>1234567(osmid1),7654321(osmid2),1435(gauge),350(maxspeed in kph),yes(highspeed or not),N/A(service),main(usage)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') header=spamreader.next() attr_list=header[2:] attr_list.append('distance') for row in spamreader: if refnode_mapper.get(int(row[0])) is None: print ("none") else: mfrom=refnode_mapper[int(row[0])] mto=refnode_mapper[int(row[1])] if mfrom not in node_fromto_dict: node_fromto_dict[mfrom]=[] if mto not in node_fromto_dict: node_fromto_dict[mto]=[] distance=haversine.hav_distance(refnodes_coord_list[refnodes_index_dict[mfrom]][0],refnodes_coord_list[refnodes_index_dict[mfrom]][1], refnodes_coord_list[refnodes_index_dict[mto]][0],refnodes_coord_list[refnodes_index_dict[mto]][1]) attr_dict={} for i in attr_list: if i=='distance': attr_dict[i]=str(distance) else: attr_dict[i]=row[header.index(i)] attribute_mapper[(mfrom,mto)]=attr_dict attribute_mapper[(mto,mfrom)]=attr_dict if (mfrom,mto) not in node_fromto_dict[mfrom] and mfrom!=mto: node_fromto_dict[mfrom].append((mfrom,mto)) if (mto,mfrom) not in node_fromto_dict[mto] and mfrom!=mto: node_fromto_dict[mto].append((mto,mfrom)) '''station's connectivity judging by suffix''' for s in stations: if s not in node_fromto_dict: disconnected_stations.append(s) stations[s].append('disconnected') else: connected_stations.append(s) stations[s].append('connected') stopt=time.time() print("Loading way segments ("+str(stopt-startt)+")") def output_nodes_csv(): target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8') for x in node_fromto_dict: if x in stations: if len(node_fromto_dict[x])!=0: target.write(str(x)+",$"+stations[x][0].decode('utf-8')+"$,"+str(stations[x][1])+","+str(stations[x][2])+"\n") else: target.write(str(x)+",$$,"+str(refnodes_coord_list[refnodes_index_dict[x]][0])+","+str(refnodes_coord_list[refnodes_index_dict[x]][1])+"\n") target.close() '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' def output_links_csv(): target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8') headerkeys=attribute_mapper.values()[0].keys() header='vertex_1,vertex_2' for k in headerkeys: header=header+','+k target.write(header+'\n') for x in node_fromto_dict: for (a,b) in node_fromto_dict[x]: if a in node_fromto_dict and b in node_fromto_dict: row_to_write=str(a)+","+str(b) for attr in headerkeys: row_to_write=row_to_write+','+attribute_mapper[(a,b)].get(attr,"N/A") target.write(row_to_write+"\n") target.close() '''Example row: >>1234(osmid_vertex1),5678(osmid_vertex2),0.1534285(haversine_distance)<<''' loadstations() loadcoordinates() loadwaysegments() output_nodes_csv() output_links_csv() return node_fromto_dict if __name__ == '__main__': print ("===you're in test mode of network_process.py===") FILE='beijing_china_latest.osm.pbf' FOLDER='/home/hegxiten/workspace/data/'+FILE+'/' CONCURRENCYVAL=4 GLOBALROUNDINGDIGITS=5 node_fromto_dict=process_network(FOLDER, FILE, CONCURRENCYVAL, GLOBALROUNDINGDIGITS) print ("===test mode of network_process.py terminated===")
PI=3.14159265358
random_line_split
network_process.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on Jan 17, 2017 @author: hegxiten ''' import sys import geo.haversine as haversine from imposm.parser import OSMParser import geo.haversine as haversine import numpy import time from scipy import spatial import csv import codecs import math default_encoding='utf-8' if sys.getdefaultencoding()!=default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) PI=3.14159265358 def process_network(FOLDER,FILE,CONCURRENCYVAL,GLOBALROUNDINGDIGITS): stations={} '''stations[station_node_osmid]=[name, lat, lon]''' refnodes_index_dict={} '''refnodes_index_dict[nodeid]=listindex_of_nodeid''' refnodes=[] '''refnodes=[nodeid1,nodeid2,nodeid3...]''' refnodes_coord_list=[] '''refnodes_coord_list[coord1,coord2,coord3...]''' node_fromto_dict={} '''node_fromto_dict[fromnode]=[(fromnode,tonode1),(fromnode,tonode2),(fromnode,tonode3)...]''' distance_mapper={} '''distance_mapper[(fromnode,tonode)]=distance''' attribute_mapper={} '''attribute_mapper[(fromnode,tonode)]=attribute_dictionary''' midpoints_coord=[] '''miderpoint_map[(fromnode,tonode)]=(midercoord)''' midsegment=[] approxCoord_map={} '''approxCoord_map[coord]=nodeid(veryfirstone)''' refnode_mapper={} '''refnode_mapper[nodeid2]=nodeid1(previous_nodeid1 with the same coordinate as nodeid2 after digit rounding)''' edgeDict={} '''edgeDict[(vertex tuple)]=(edgereflist,edgelength)''' disconnected_stations=[] connected_stations=[] def loadstations(): '''Load stations from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_stations.csv', 'rb') as csvfile: '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: stations[int(row[0])]=[row[1],float(row[2]),float(row[3])] stopt=time.time() print("Loading stations. Time:("+str(stopt-startt)+")") def
(): '''Load coordinates of reference-nodes from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegment_nodecoords.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>123(osmid),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: c1,c2=float(row[1]),float(row[2]) '''c1--lat, c2--lon''' #c1,c2=round(float(row[1]),ROUNDINGDIGITS),round(float(row[2]),ROUNDINGDIGITS) if (c1,c2) not in approxCoord_map: approxCoord_map[(c1,c2)]=int(row[0]) '''row[0]--coordid''' refnodes_index_dict[int(row[0])]=len(refnodes_coord_list) refnodes.append(int(row[0])) refnodes_coord_list.append((c1,c2)) refnode_mapper[int(row[0])]=int(row[0]) else: refnode_mapper[int(row[0])]=approxCoord_map[(c1,c2)] stopt=time.time() print("Loading refnode coordinates. Time:("+str(stopt-startt)+")") def loadwaysegments(): '''Load way segments from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegments.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>1234567(osmid1),7654321(osmid2),1435(gauge),350(maxspeed in kph),yes(highspeed or not),N/A(service),main(usage)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') header=spamreader.next() attr_list=header[2:] attr_list.append('distance') for row in spamreader: if refnode_mapper.get(int(row[0])) is None: print ("none") else: mfrom=refnode_mapper[int(row[0])] mto=refnode_mapper[int(row[1])] if mfrom not in node_fromto_dict: node_fromto_dict[mfrom]=[] if mto not in node_fromto_dict: node_fromto_dict[mto]=[] distance=haversine.hav_distance(refnodes_coord_list[refnodes_index_dict[mfrom]][0],refnodes_coord_list[refnodes_index_dict[mfrom]][1], refnodes_coord_list[refnodes_index_dict[mto]][0],refnodes_coord_list[refnodes_index_dict[mto]][1]) attr_dict={} for i in attr_list: if i=='distance': attr_dict[i]=str(distance) else: attr_dict[i]=row[header.index(i)] attribute_mapper[(mfrom,mto)]=attr_dict attribute_mapper[(mto,mfrom)]=attr_dict if (mfrom,mto) not in node_fromto_dict[mfrom] and mfrom!=mto: node_fromto_dict[mfrom].append((mfrom,mto)) if (mto,mfrom) not in node_fromto_dict[mto] and mfrom!=mto: node_fromto_dict[mto].append((mto,mfrom)) '''station's connectivity judging by suffix''' for s in stations: if s not in node_fromto_dict: disconnected_stations.append(s) stations[s].append('disconnected') else: connected_stations.append(s) stations[s].append('connected') stopt=time.time() print("Loading way segments ("+str(stopt-startt)+")") def output_nodes_csv(): target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8') for x in node_fromto_dict: if x in stations: if len(node_fromto_dict[x])!=0: target.write(str(x)+",$"+stations[x][0].decode('utf-8')+"$,"+str(stations[x][1])+","+str(stations[x][2])+"\n") else: target.write(str(x)+",$$,"+str(refnodes_coord_list[refnodes_index_dict[x]][0])+","+str(refnodes_coord_list[refnodes_index_dict[x]][1])+"\n") target.close() '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' def output_links_csv(): target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8') headerkeys=attribute_mapper.values()[0].keys() header='vertex_1,vertex_2' for k in headerkeys: header=header+','+k target.write(header+'\n') for x in node_fromto_dict: for (a,b) in node_fromto_dict[x]: if a in node_fromto_dict and b in node_fromto_dict: row_to_write=str(a)+","+str(b) for attr in headerkeys: row_to_write=row_to_write+','+attribute_mapper[(a,b)].get(attr,"N/A") target.write(row_to_write+"\n") target.close() '''Example row: >>1234(osmid_vertex1),5678(osmid_vertex2),0.1534285(haversine_distance)<<''' loadstations() loadcoordinates() loadwaysegments() output_nodes_csv() output_links_csv() return node_fromto_dict if __name__ == '__main__': print ("===you're in test mode of network_process.py===") FILE='beijing_china_latest.osm.pbf' FOLDER='/home/hegxiten/workspace/data/'+FILE+'/' CONCURRENCYVAL=4 GLOBALROUNDINGDIGITS=5 node_fromto_dict=process_network(FOLDER, FILE, CONCURRENCYVAL, GLOBALROUNDINGDIGITS) print ("===test mode of network_process.py terminated===")
loadcoordinates
identifier_name
network_process.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on Jan 17, 2017 @author: hegxiten ''' import sys import geo.haversine as haversine from imposm.parser import OSMParser import geo.haversine as haversine import numpy import time from scipy import spatial import csv import codecs import math default_encoding='utf-8' if sys.getdefaultencoding()!=default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) PI=3.14159265358 def process_network(FOLDER,FILE,CONCURRENCYVAL,GLOBALROUNDINGDIGITS): stations={} '''stations[station_node_osmid]=[name, lat, lon]''' refnodes_index_dict={} '''refnodes_index_dict[nodeid]=listindex_of_nodeid''' refnodes=[] '''refnodes=[nodeid1,nodeid2,nodeid3...]''' refnodes_coord_list=[] '''refnodes_coord_list[coord1,coord2,coord3...]''' node_fromto_dict={} '''node_fromto_dict[fromnode]=[(fromnode,tonode1),(fromnode,tonode2),(fromnode,tonode3)...]''' distance_mapper={} '''distance_mapper[(fromnode,tonode)]=distance''' attribute_mapper={} '''attribute_mapper[(fromnode,tonode)]=attribute_dictionary''' midpoints_coord=[] '''miderpoint_map[(fromnode,tonode)]=(midercoord)''' midsegment=[] approxCoord_map={} '''approxCoord_map[coord]=nodeid(veryfirstone)''' refnode_mapper={} '''refnode_mapper[nodeid2]=nodeid1(previous_nodeid1 with the same coordinate as nodeid2 after digit rounding)''' edgeDict={} '''edgeDict[(vertex tuple)]=(edgereflist,edgelength)''' disconnected_stations=[] connected_stations=[] def loadstations(): '''Load stations from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_stations.csv', 'rb') as csvfile: '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: stations[int(row[0])]=[row[1],float(row[2]),float(row[3])] stopt=time.time() print("Loading stations. Time:("+str(stopt-startt)+")") def loadcoordinates(): '''Load coordinates of reference-nodes from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegment_nodecoords.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>123(osmid),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: c1,c2=float(row[1]),float(row[2]) '''c1--lat, c2--lon''' #c1,c2=round(float(row[1]),ROUNDINGDIGITS),round(float(row[2]),ROUNDINGDIGITS) if (c1,c2) not in approxCoord_map: approxCoord_map[(c1,c2)]=int(row[0]) '''row[0]--coordid''' refnodes_index_dict[int(row[0])]=len(refnodes_coord_list) refnodes.append(int(row[0])) refnodes_coord_list.append((c1,c2)) refnode_mapper[int(row[0])]=int(row[0]) else: refnode_mapper[int(row[0])]=approxCoord_map[(c1,c2)] stopt=time.time() print("Loading refnode coordinates. Time:("+str(stopt-startt)+")") def loadwaysegments(): '''Load way segments from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegments.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>1234567(osmid1),7654321(osmid2),1435(gauge),350(maxspeed in kph),yes(highspeed or not),N/A(service),main(usage)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') header=spamreader.next() attr_list=header[2:] attr_list.append('distance') for row in spamreader: if refnode_mapper.get(int(row[0])) is None: print ("none") else: mfrom=refnode_mapper[int(row[0])] mto=refnode_mapper[int(row[1])] if mfrom not in node_fromto_dict: node_fromto_dict[mfrom]=[] if mto not in node_fromto_dict: node_fromto_dict[mto]=[] distance=haversine.hav_distance(refnodes_coord_list[refnodes_index_dict[mfrom]][0],refnodes_coord_list[refnodes_index_dict[mfrom]][1], refnodes_coord_list[refnodes_index_dict[mto]][0],refnodes_coord_list[refnodes_index_dict[mto]][1]) attr_dict={} for i in attr_list: if i=='distance': attr_dict[i]=str(distance) else: attr_dict[i]=row[header.index(i)] attribute_mapper[(mfrom,mto)]=attr_dict attribute_mapper[(mto,mfrom)]=attr_dict if (mfrom,mto) not in node_fromto_dict[mfrom] and mfrom!=mto: node_fromto_dict[mfrom].append((mfrom,mto)) if (mto,mfrom) not in node_fromto_dict[mto] and mfrom!=mto: node_fromto_dict[mto].append((mto,mfrom)) '''station's connectivity judging by suffix''' for s in stations:
stopt=time.time() print("Loading way segments ("+str(stopt-startt)+")") def output_nodes_csv(): target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8') for x in node_fromto_dict: if x in stations: if len(node_fromto_dict[x])!=0: target.write(str(x)+",$"+stations[x][0].decode('utf-8')+"$,"+str(stations[x][1])+","+str(stations[x][2])+"\n") else: target.write(str(x)+",$$,"+str(refnodes_coord_list[refnodes_index_dict[x]][0])+","+str(refnodes_coord_list[refnodes_index_dict[x]][1])+"\n") target.close() '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' def output_links_csv(): target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8') headerkeys=attribute_mapper.values()[0].keys() header='vertex_1,vertex_2' for k in headerkeys: header=header+','+k target.write(header+'\n') for x in node_fromto_dict: for (a,b) in node_fromto_dict[x]: if a in node_fromto_dict and b in node_fromto_dict: row_to_write=str(a)+","+str(b) for attr in headerkeys: row_to_write=row_to_write+','+attribute_mapper[(a,b)].get(attr,"N/A") target.write(row_to_write+"\n") target.close() '''Example row: >>1234(osmid_vertex1),5678(osmid_vertex2),0.1534285(haversine_distance)<<''' loadstations() loadcoordinates() loadwaysegments() output_nodes_csv() output_links_csv() return node_fromto_dict if __name__ == '__main__': print ("===you're in test mode of network_process.py===") FILE='beijing_china_latest.osm.pbf' FOLDER='/home/hegxiten/workspace/data/'+FILE+'/' CONCURRENCYVAL=4 GLOBALROUNDINGDIGITS=5 node_fromto_dict=process_network(FOLDER, FILE, CONCURRENCYVAL, GLOBALROUNDINGDIGITS) print ("===test mode of network_process.py terminated===")
if s not in node_fromto_dict: disconnected_stations.append(s) stations[s].append('disconnected') else: connected_stations.append(s) stations[s].append('connected')
conditional_block
network_process.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on Jan 17, 2017 @author: hegxiten ''' import sys import geo.haversine as haversine from imposm.parser import OSMParser import geo.haversine as haversine import numpy import time from scipy import spatial import csv import codecs import math default_encoding='utf-8' if sys.getdefaultencoding()!=default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) PI=3.14159265358 def process_network(FOLDER,FILE,CONCURRENCYVAL,GLOBALROUNDINGDIGITS): stations={} '''stations[station_node_osmid]=[name, lat, lon]''' refnodes_index_dict={} '''refnodes_index_dict[nodeid]=listindex_of_nodeid''' refnodes=[] '''refnodes=[nodeid1,nodeid2,nodeid3...]''' refnodes_coord_list=[] '''refnodes_coord_list[coord1,coord2,coord3...]''' node_fromto_dict={} '''node_fromto_dict[fromnode]=[(fromnode,tonode1),(fromnode,tonode2),(fromnode,tonode3)...]''' distance_mapper={} '''distance_mapper[(fromnode,tonode)]=distance''' attribute_mapper={} '''attribute_mapper[(fromnode,tonode)]=attribute_dictionary''' midpoints_coord=[] '''miderpoint_map[(fromnode,tonode)]=(midercoord)''' midsegment=[] approxCoord_map={} '''approxCoord_map[coord]=nodeid(veryfirstone)''' refnode_mapper={} '''refnode_mapper[nodeid2]=nodeid1(previous_nodeid1 with the same coordinate as nodeid2 after digit rounding)''' edgeDict={} '''edgeDict[(vertex tuple)]=(edgereflist,edgelength)''' disconnected_stations=[] connected_stations=[] def loadstations(): '''Load stations from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_stations.csv', 'rb') as csvfile: '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: stations[int(row[0])]=[row[1],float(row[2]),float(row[3])] stopt=time.time() print("Loading stations. Time:("+str(stopt-startt)+")") def loadcoordinates(): '''Load coordinates of reference-nodes from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegment_nodecoords.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>123(osmid),40.11545(latitude),-88.24111(longitude)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') for row in spamreader: c1,c2=float(row[1]),float(row[2]) '''c1--lat, c2--lon''' #c1,c2=round(float(row[1]),ROUNDINGDIGITS),round(float(row[2]),ROUNDINGDIGITS) if (c1,c2) not in approxCoord_map: approxCoord_map[(c1,c2)]=int(row[0]) '''row[0]--coordid''' refnodes_index_dict[int(row[0])]=len(refnodes_coord_list) refnodes.append(int(row[0])) refnodes_coord_list.append((c1,c2)) refnode_mapper[int(row[0])]=int(row[0]) else: refnode_mapper[int(row[0])]=approxCoord_map[(c1,c2)] stopt=time.time() print("Loading refnode coordinates. Time:("+str(stopt-startt)+")") def loadwaysegments(): '''Load way segments from csv format output''' startt=time.time() with codecs.open(FOLDER+FILE+'_waysegments.csv', 'rb',encoding='utf-8') as csvfile: '''Example row: >>1234567(osmid1),7654321(osmid2),1435(gauge),350(maxspeed in kph),yes(highspeed or not),N/A(service),main(usage)<<''' spamreader = csv.reader(csvfile, delimiter=',', quotechar='$') header=spamreader.next() attr_list=header[2:] attr_list.append('distance') for row in spamreader: if refnode_mapper.get(int(row[0])) is None: print ("none") else: mfrom=refnode_mapper[int(row[0])] mto=refnode_mapper[int(row[1])] if mfrom not in node_fromto_dict: node_fromto_dict[mfrom]=[] if mto not in node_fromto_dict: node_fromto_dict[mto]=[] distance=haversine.hav_distance(refnodes_coord_list[refnodes_index_dict[mfrom]][0],refnodes_coord_list[refnodes_index_dict[mfrom]][1], refnodes_coord_list[refnodes_index_dict[mto]][0],refnodes_coord_list[refnodes_index_dict[mto]][1]) attr_dict={} for i in attr_list: if i=='distance': attr_dict[i]=str(distance) else: attr_dict[i]=row[header.index(i)] attribute_mapper[(mfrom,mto)]=attr_dict attribute_mapper[(mto,mfrom)]=attr_dict if (mfrom,mto) not in node_fromto_dict[mfrom] and mfrom!=mto: node_fromto_dict[mfrom].append((mfrom,mto)) if (mto,mfrom) not in node_fromto_dict[mto] and mfrom!=mto: node_fromto_dict[mto].append((mto,mfrom)) '''station's connectivity judging by suffix''' for s in stations: if s not in node_fromto_dict: disconnected_stations.append(s) stations[s].append('disconnected') else: connected_stations.append(s) stations[s].append('connected') stopt=time.time() print("Loading way segments ("+str(stopt-startt)+")") def output_nodes_csv():
def output_links_csv(): target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8') headerkeys=attribute_mapper.values()[0].keys() header='vertex_1,vertex_2' for k in headerkeys: header=header+','+k target.write(header+'\n') for x in node_fromto_dict: for (a,b) in node_fromto_dict[x]: if a in node_fromto_dict and b in node_fromto_dict: row_to_write=str(a)+","+str(b) for attr in headerkeys: row_to_write=row_to_write+','+attribute_mapper[(a,b)].get(attr,"N/A") target.write(row_to_write+"\n") target.close() '''Example row: >>1234(osmid_vertex1),5678(osmid_vertex2),0.1534285(haversine_distance)<<''' loadstations() loadcoordinates() loadwaysegments() output_nodes_csv() output_links_csv() return node_fromto_dict if __name__ == '__main__': print ("===you're in test mode of network_process.py===") FILE='beijing_china_latest.osm.pbf' FOLDER='/home/hegxiten/workspace/data/'+FILE+'/' CONCURRENCYVAL=4 GLOBALROUNDINGDIGITS=5 node_fromto_dict=process_network(FOLDER, FILE, CONCURRENCYVAL, GLOBALROUNDINGDIGITS) print ("===test mode of network_process.py terminated===")
target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8') for x in node_fromto_dict: if x in stations: if len(node_fromto_dict[x])!=0: target.write(str(x)+",$"+stations[x][0].decode('utf-8')+"$,"+str(stations[x][1])+","+str(stations[x][2])+"\n") else: target.write(str(x)+",$$,"+str(refnodes_coord_list[refnodes_index_dict[x]][0])+","+str(refnodes_coord_list[refnodes_index_dict[x]][1])+"\n") target.close() '''Example row: >>1234(osmid),$Illinois Terminal$($name$),40.11545(latitude),-88.24111(longitude)<<'''
identifier_body
__init__.py
"""Main module.""" import os import pygame import signal import logging import argparse from threading import Event from multiprocessing import Value from injector import Injector, singleton from ballercfg import ConfigurationManager from .locals import * # noqa from .events import EventManager, TickEvent from .modules import ModuleLoader from .logger import configure_logging from .states import StateManager from .assets import AssetManager from .entities import EntityManager from .session import SessionManager from .utils import get_data_path os.chdir(os.path.dirname(os.path.dirname(__file__))) logger = logging.getLogger(__name__) container = None def build_container(binder): """Build a service container by binding dependencies to an injector.""" # General flags and shared objects binder.bind(ShutdownFlag, to=Event()) binder.bind(DisplayClock, to=pygame.time.Clock()) # Core components binder.bind(EventManager, scope=singleton) binder.bind(EntityManager, scope=singleton) binder.bind(AssetManager, scope=singleton) binder.bind(SessionManager, scope=singleton) binder.bind(StateManager, scope=singleton) class Akurra: """Base game class.""" def __init__(self, game, log_level='INFO', debug=False): """Constructor.""" # Set up container global container self.container = container = Injector(build_container) self.game = game self.log_level = log_level self.debug = debug # Load configuration cfg_files = [ os.path.expanduser('~/.config/akurra/*.yml'), os.path.expanduser('~/.config/akurra/games/%s/*.yml' % self.game) ] cfg = ConfigurationManager.load([get_data_path('*.yml')] + cfg_files) self.container.binder.bind(Configuration, to=cfg) self.container.binder.bind(DebugFlag, to=Value('b', self.debug)) self.container.binder.bind(Akurra, to=self) # Start pygame (+ audio frequency, size, channels, buffersize) pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() configure_logging(log_level=self.log_level) logger.info('Initializing..') self.configuration = self.container.get(Configuration) self.shutdown = self.container.get(ShutdownFlag) self.clock = self.container.get(DisplayClock) self.modules = ModuleLoader( group=self.configuration.get('akurra.modules.entry_point_group', 'akurra.modules'), whitelist=self.configuration.get('akurra.modules.whitelist', None), blacklist=self.configuration.get('akurra.modules.blacklist', None), ) self.games = ModuleLoader( group=self.configuration.get('akurra.games.entry_point_group', 'akurra.games'), ) self.events = self.container.get(EventManager) self.entities = self.container.get(EntityManager) self.states = self.container.get(StateManager) self.assets = self.container.get(AssetManager) self.session = self.container.get(SessionManager) self.loop_wait_millis = self.configuration.get('akurra.core.loop_wait_millis', 5) self.max_fps = self.configuration.get('akurra.display.max_fps', 60) # Handle shutdown signals properly signal.signal(signal.SIGINT, self.handle_signal) signal.signal(signal.SIGTERM, self.handle_signal) def start(self): """Start.""" logger.debug('Starting..') # Reset shutdown flag self.shutdown.clear() self.modules.load() self.entities.start() self.modules.start() try: # Attempt to fetch and launch game self.games.load_single(self.game) game = self.games.modules.get(self.game)
while not self.shutdown.is_set(): # Pump/handle events (both pygame and akurra) self.events.poll() # Calculate time (in seconds) that has passed since last tick delta_time = self.clock.tick(self.max_fps) / 1000 # Dispatch tick self.events.dispatch(TickEvent(delta_time=delta_time)) # Wait a bit to lower CPU usage pygame.time.wait(self.loop_wait_millis) self.stop() def stop(self): """Stop.""" logger.info('Stopping..') self.shutdown.set() self.modules.stop() self.entities.stop() self.modules.unload() self.states.close() def handle_signal(self, signum, frame): """Handle a shutdown signal.""" logger.debug('Received signal, setting shutdown flag [signal=%s]', signum) self.shutdown.set() def main(): """Main entry point.""" # Parse command-line arguments and set required variables parser = argparse.ArgumentParser(description='Run the Akurra game engine.') parser.add_argument('--log-level', type=str, default='INFO', help='set the log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'INSANE']) parser.add_argument('-d', '--debug', action='store_true', help='toggle debugging') parser.add_argument('-g', '--game', required=True, type=str, help='game to run') args = parser.parse_args() akurra = Akurra(game=args.game, log_level=args.log_level, debug=args.debug) akurra.start() if __name__ == '__main__': main()
game.play() except AttributeError: raise ValueError('No game module named "%s" exists!' % self.game)
random_line_split
__init__.py
"""Main module.""" import os import pygame import signal import logging import argparse from threading import Event from multiprocessing import Value from injector import Injector, singleton from ballercfg import ConfigurationManager from .locals import * # noqa from .events import EventManager, TickEvent from .modules import ModuleLoader from .logger import configure_logging from .states import StateManager from .assets import AssetManager from .entities import EntityManager from .session import SessionManager from .utils import get_data_path os.chdir(os.path.dirname(os.path.dirname(__file__))) logger = logging.getLogger(__name__) container = None def build_container(binder): """Build a service container by binding dependencies to an injector.""" # General flags and shared objects binder.bind(ShutdownFlag, to=Event()) binder.bind(DisplayClock, to=pygame.time.Clock()) # Core components binder.bind(EventManager, scope=singleton) binder.bind(EntityManager, scope=singleton) binder.bind(AssetManager, scope=singleton) binder.bind(SessionManager, scope=singleton) binder.bind(StateManager, scope=singleton) class Akurra:
def main(): """Main entry point.""" # Parse command-line arguments and set required variables parser = argparse.ArgumentParser(description='Run the Akurra game engine.') parser.add_argument('--log-level', type=str, default='INFO', help='set the log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'INSANE']) parser.add_argument('-d', '--debug', action='store_true', help='toggle debugging') parser.add_argument('-g', '--game', required=True, type=str, help='game to run') args = parser.parse_args() akurra = Akurra(game=args.game, log_level=args.log_level, debug=args.debug) akurra.start() if __name__ == '__main__': main()
"""Base game class.""" def __init__(self, game, log_level='INFO', debug=False): """Constructor.""" # Set up container global container self.container = container = Injector(build_container) self.game = game self.log_level = log_level self.debug = debug # Load configuration cfg_files = [ os.path.expanduser('~/.config/akurra/*.yml'), os.path.expanduser('~/.config/akurra/games/%s/*.yml' % self.game) ] cfg = ConfigurationManager.load([get_data_path('*.yml')] + cfg_files) self.container.binder.bind(Configuration, to=cfg) self.container.binder.bind(DebugFlag, to=Value('b', self.debug)) self.container.binder.bind(Akurra, to=self) # Start pygame (+ audio frequency, size, channels, buffersize) pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() configure_logging(log_level=self.log_level) logger.info('Initializing..') self.configuration = self.container.get(Configuration) self.shutdown = self.container.get(ShutdownFlag) self.clock = self.container.get(DisplayClock) self.modules = ModuleLoader( group=self.configuration.get('akurra.modules.entry_point_group', 'akurra.modules'), whitelist=self.configuration.get('akurra.modules.whitelist', None), blacklist=self.configuration.get('akurra.modules.blacklist', None), ) self.games = ModuleLoader( group=self.configuration.get('akurra.games.entry_point_group', 'akurra.games'), ) self.events = self.container.get(EventManager) self.entities = self.container.get(EntityManager) self.states = self.container.get(StateManager) self.assets = self.container.get(AssetManager) self.session = self.container.get(SessionManager) self.loop_wait_millis = self.configuration.get('akurra.core.loop_wait_millis', 5) self.max_fps = self.configuration.get('akurra.display.max_fps', 60) # Handle shutdown signals properly signal.signal(signal.SIGINT, self.handle_signal) signal.signal(signal.SIGTERM, self.handle_signal) def start(self): """Start.""" logger.debug('Starting..') # Reset shutdown flag self.shutdown.clear() self.modules.load() self.entities.start() self.modules.start() try: # Attempt to fetch and launch game self.games.load_single(self.game) game = self.games.modules.get(self.game) game.play() except AttributeError: raise ValueError('No game module named "%s" exists!' % self.game) while not self.shutdown.is_set(): # Pump/handle events (both pygame and akurra) self.events.poll() # Calculate time (in seconds) that has passed since last tick delta_time = self.clock.tick(self.max_fps) / 1000 # Dispatch tick self.events.dispatch(TickEvent(delta_time=delta_time)) # Wait a bit to lower CPU usage pygame.time.wait(self.loop_wait_millis) self.stop() def stop(self): """Stop.""" logger.info('Stopping..') self.shutdown.set() self.modules.stop() self.entities.stop() self.modules.unload() self.states.close() def handle_signal(self, signum, frame): """Handle a shutdown signal.""" logger.debug('Received signal, setting shutdown flag [signal=%s]', signum) self.shutdown.set()
identifier_body
__init__.py
"""Main module.""" import os import pygame import signal import logging import argparse from threading import Event from multiprocessing import Value from injector import Injector, singleton from ballercfg import ConfigurationManager from .locals import * # noqa from .events import EventManager, TickEvent from .modules import ModuleLoader from .logger import configure_logging from .states import StateManager from .assets import AssetManager from .entities import EntityManager from .session import SessionManager from .utils import get_data_path os.chdir(os.path.dirname(os.path.dirname(__file__))) logger = logging.getLogger(__name__) container = None def build_container(binder): """Build a service container by binding dependencies to an injector.""" # General flags and shared objects binder.bind(ShutdownFlag, to=Event()) binder.bind(DisplayClock, to=pygame.time.Clock()) # Core components binder.bind(EventManager, scope=singleton) binder.bind(EntityManager, scope=singleton) binder.bind(AssetManager, scope=singleton) binder.bind(SessionManager, scope=singleton) binder.bind(StateManager, scope=singleton) class Akurra: """Base game class.""" def __init__(self, game, log_level='INFO', debug=False): """Constructor.""" # Set up container global container self.container = container = Injector(build_container) self.game = game self.log_level = log_level self.debug = debug # Load configuration cfg_files = [ os.path.expanduser('~/.config/akurra/*.yml'), os.path.expanduser('~/.config/akurra/games/%s/*.yml' % self.game) ] cfg = ConfigurationManager.load([get_data_path('*.yml')] + cfg_files) self.container.binder.bind(Configuration, to=cfg) self.container.binder.bind(DebugFlag, to=Value('b', self.debug)) self.container.binder.bind(Akurra, to=self) # Start pygame (+ audio frequency, size, channels, buffersize) pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() configure_logging(log_level=self.log_level) logger.info('Initializing..') self.configuration = self.container.get(Configuration) self.shutdown = self.container.get(ShutdownFlag) self.clock = self.container.get(DisplayClock) self.modules = ModuleLoader( group=self.configuration.get('akurra.modules.entry_point_group', 'akurra.modules'), whitelist=self.configuration.get('akurra.modules.whitelist', None), blacklist=self.configuration.get('akurra.modules.blacklist', None), ) self.games = ModuleLoader( group=self.configuration.get('akurra.games.entry_point_group', 'akurra.games'), ) self.events = self.container.get(EventManager) self.entities = self.container.get(EntityManager) self.states = self.container.get(StateManager) self.assets = self.container.get(AssetManager) self.session = self.container.get(SessionManager) self.loop_wait_millis = self.configuration.get('akurra.core.loop_wait_millis', 5) self.max_fps = self.configuration.get('akurra.display.max_fps', 60) # Handle shutdown signals properly signal.signal(signal.SIGINT, self.handle_signal) signal.signal(signal.SIGTERM, self.handle_signal) def start(self): """Start.""" logger.debug('Starting..') # Reset shutdown flag self.shutdown.clear() self.modules.load() self.entities.start() self.modules.start() try: # Attempt to fetch and launch game self.games.load_single(self.game) game = self.games.modules.get(self.game) game.play() except AttributeError: raise ValueError('No game module named "%s" exists!' % self.game) while not self.shutdown.is_set(): # Pump/handle events (both pygame and akurra) self.events.poll() # Calculate time (in seconds) that has passed since last tick delta_time = self.clock.tick(self.max_fps) / 1000 # Dispatch tick self.events.dispatch(TickEvent(delta_time=delta_time)) # Wait a bit to lower CPU usage pygame.time.wait(self.loop_wait_millis) self.stop() def stop(self): """Stop.""" logger.info('Stopping..') self.shutdown.set() self.modules.stop() self.entities.stop() self.modules.unload() self.states.close() def handle_signal(self, signum, frame): """Handle a shutdown signal.""" logger.debug('Received signal, setting shutdown flag [signal=%s]', signum) self.shutdown.set() def main(): """Main entry point.""" # Parse command-line arguments and set required variables parser = argparse.ArgumentParser(description='Run the Akurra game engine.') parser.add_argument('--log-level', type=str, default='INFO', help='set the log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'INSANE']) parser.add_argument('-d', '--debug', action='store_true', help='toggle debugging') parser.add_argument('-g', '--game', required=True, type=str, help='game to run') args = parser.parse_args() akurra = Akurra(game=args.game, log_level=args.log_level, debug=args.debug) akurra.start() if __name__ == '__main__':
main()
conditional_block
__init__.py
"""Main module.""" import os import pygame import signal import logging import argparse from threading import Event from multiprocessing import Value from injector import Injector, singleton from ballercfg import ConfigurationManager from .locals import * # noqa from .events import EventManager, TickEvent from .modules import ModuleLoader from .logger import configure_logging from .states import StateManager from .assets import AssetManager from .entities import EntityManager from .session import SessionManager from .utils import get_data_path os.chdir(os.path.dirname(os.path.dirname(__file__))) logger = logging.getLogger(__name__) container = None def build_container(binder): """Build a service container by binding dependencies to an injector.""" # General flags and shared objects binder.bind(ShutdownFlag, to=Event()) binder.bind(DisplayClock, to=pygame.time.Clock()) # Core components binder.bind(EventManager, scope=singleton) binder.bind(EntityManager, scope=singleton) binder.bind(AssetManager, scope=singleton) binder.bind(SessionManager, scope=singleton) binder.bind(StateManager, scope=singleton) class
: """Base game class.""" def __init__(self, game, log_level='INFO', debug=False): """Constructor.""" # Set up container global container self.container = container = Injector(build_container) self.game = game self.log_level = log_level self.debug = debug # Load configuration cfg_files = [ os.path.expanduser('~/.config/akurra/*.yml'), os.path.expanduser('~/.config/akurra/games/%s/*.yml' % self.game) ] cfg = ConfigurationManager.load([get_data_path('*.yml')] + cfg_files) self.container.binder.bind(Configuration, to=cfg) self.container.binder.bind(DebugFlag, to=Value('b', self.debug)) self.container.binder.bind(Akurra, to=self) # Start pygame (+ audio frequency, size, channels, buffersize) pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() configure_logging(log_level=self.log_level) logger.info('Initializing..') self.configuration = self.container.get(Configuration) self.shutdown = self.container.get(ShutdownFlag) self.clock = self.container.get(DisplayClock) self.modules = ModuleLoader( group=self.configuration.get('akurra.modules.entry_point_group', 'akurra.modules'), whitelist=self.configuration.get('akurra.modules.whitelist', None), blacklist=self.configuration.get('akurra.modules.blacklist', None), ) self.games = ModuleLoader( group=self.configuration.get('akurra.games.entry_point_group', 'akurra.games'), ) self.events = self.container.get(EventManager) self.entities = self.container.get(EntityManager) self.states = self.container.get(StateManager) self.assets = self.container.get(AssetManager) self.session = self.container.get(SessionManager) self.loop_wait_millis = self.configuration.get('akurra.core.loop_wait_millis', 5) self.max_fps = self.configuration.get('akurra.display.max_fps', 60) # Handle shutdown signals properly signal.signal(signal.SIGINT, self.handle_signal) signal.signal(signal.SIGTERM, self.handle_signal) def start(self): """Start.""" logger.debug('Starting..') # Reset shutdown flag self.shutdown.clear() self.modules.load() self.entities.start() self.modules.start() try: # Attempt to fetch and launch game self.games.load_single(self.game) game = self.games.modules.get(self.game) game.play() except AttributeError: raise ValueError('No game module named "%s" exists!' % self.game) while not self.shutdown.is_set(): # Pump/handle events (both pygame and akurra) self.events.poll() # Calculate time (in seconds) that has passed since last tick delta_time = self.clock.tick(self.max_fps) / 1000 # Dispatch tick self.events.dispatch(TickEvent(delta_time=delta_time)) # Wait a bit to lower CPU usage pygame.time.wait(self.loop_wait_millis) self.stop() def stop(self): """Stop.""" logger.info('Stopping..') self.shutdown.set() self.modules.stop() self.entities.stop() self.modules.unload() self.states.close() def handle_signal(self, signum, frame): """Handle a shutdown signal.""" logger.debug('Received signal, setting shutdown flag [signal=%s]', signum) self.shutdown.set() def main(): """Main entry point.""" # Parse command-line arguments and set required variables parser = argparse.ArgumentParser(description='Run the Akurra game engine.') parser.add_argument('--log-level', type=str, default='INFO', help='set the log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'INSANE']) parser.add_argument('-d', '--debug', action='store_true', help='toggle debugging') parser.add_argument('-g', '--game', required=True, type=str, help='game to run') args = parser.parse_args() akurra = Akurra(game=args.game, log_level=args.log_level, debug=args.debug) akurra.start() if __name__ == '__main__': main()
Akurra
identifier_name
textfiles.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEncodingSupport, ConfirmResult, IRevertOptions, IModeSupport } from 'vs/workbench/common/editor'; import { IBaseStatWithMetadata, IFileStatWithMetadata, IReadFileOptions, IWriteFileOptions, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer'; import { isUndefinedOrNull } from 'vs/base/common/types'; export const ITextFileService = createDecorator<ITextFileService>('textFileService'); export interface ITextFileService extends IDisposable { _serviceBrand: ServiceIdentifier<any>; readonly onWillMove: Event<IWillMoveEvent>; readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>; readonly onFilesAssociationChange: Event<void>; readonly isHotExitEnabled: boolean; /** * Access to the manager of text file editor models providing further methods to work with them. */ readonly models: ITextFileEditorModelManager; /** * Helper to determine encoding for resources. */ readonly encoding: IResourceEncodings; /** * A resource is dirty if it has unsaved changes or is an untitled file not yet saved. * * @param resource the resource to check for being dirty. If it is not specified, will check for * all dirty resources. */ isDirty(resource?: URI): boolean; /** * Returns all resources that are currently dirty matching the provided resources or all dirty resources. * * @param resources the resources to check for being dirty. If it is not specified, will check for * all dirty resources. */ getDirty(resources?: URI[]): URI[]; /** * Saves the resource. * * @param resource the resource to save * @param options optional save options * @return true if the resource was saved. */ save(resource: URI, options?: ISaveOptions): Promise<boolean>; /** * Saves the provided resource asking the user for a file name or using the provided one. * * @param resource the resource to save as. * @param targetResource the optional target to save to. * @param options optional save options * @return Path of the saved resource. */ saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined>; /** * Saves the set of resources and returns a promise with the operation result. * * @param resources can be null to save all. * @param includeUntitled to save all resources and optionally exclude untitled ones. */ saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>; saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>; /** * Reverts the provided resource. * * @param resource the resource of the file to revert. * @param force to force revert even when the file is not dirty */ revert(resource: URI, options?: IRevertOptions): Promise<boolean>; /** * Reverts all the provided resources and returns a promise with the operation result. */ revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult>; /** * Create a file. If the file exists it will be overwritten with the contents if * the options enable to overwrite. */ create(resource: URI, contents?: string | ITextSnapshot, options?: { overwrite?: boolean }): Promise<IFileStatWithMetadata>; /** * Read the contents of a file identified by the resource. */ read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>; /** * Read the contents of a file identified by the resource as stream. */ readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>; /** * Update a file with given contents. */ write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>; /** * Delete a file. If the file is dirty, it will get reverted and then deleted from disk. */ delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void>; /** * Move a file. If the file is dirty, its contents will be preserved and restored. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Brings up the confirm dialog to either save, don't save or cancel. * * @param resources the resources of the files to ask for confirmation or null if * confirming for all dirty resources. */ confirmSave(resources?: URI[]): Promise<ConfirmResult>; /** * Convenient fast access to the current auto save mode. */ getAutoSaveMode(): AutoSaveMode; /** * Convenient fast access to the raw configured auto save settings. */ getAutoSaveConfiguration(): IAutoSaveConfiguration; } export interface IReadTextFileOptions extends IReadFileOptions { /** * The optional acceptTextOnly parameter allows to fail this request early if the file * contents are not textual. */ acceptTextOnly?: boolean; /** * The optional encoding parameter allows to specify the desired encoding when resolving * the contents of the file. */ encoding?: string; /** * The optional guessEncoding parameter allows to guess encoding from content of the file. */ autoGuessEncoding?: boolean; } export interface IWriteTextFileOptions extends IWriteFileOptions { /** * The encoding to use when updating a file. */ encoding?: string; /** * If set to true, will enforce the selected encoding and not perform any detection using BOMs. */ overwriteEncoding?: boolean; /** * Whether to overwrite a file even if it is readonly. */ overwriteReadonly?: boolean; /** * Wether to write to the file as elevated (admin) user. When setting this option a prompt will * ask the user to authenticate as super user. */ writeElevated?: boolean; } export const enum TextFileOperationResult { FILE_IS_BINARY } export class TextFileOperationError extends FileOperationError { constructor(message: string, public textFileOperationResult: TextFileOperationResult, public options?: IReadTextFileOptions & IWriteTextFileOptions) { super(message, FileOperationResult.FILE_OTHER_ERROR); } static isTextFileOperationError(obj: unknown): obj is TextFileOperationError { return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult); } } export interface IResourceEncodings { getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding; } export interface IResourceEncoding { encoding: string; hasBOM: boolean; } /** * The save error handler can be installed on the text file editor model to install code that executes when save errors occur. */ export interface ISaveErrorHandler { /** * Called whenever a save fails. */ onSaveError(error: Error, model: ITextFileEditorModel): void; } export interface ISaveParticipant { /** * Participate in a save of a model. Allows to change the model before it is being saved to disk. */ participate(model: IResolvedTextFileEditorModel, env: { reason: SaveReason }): Promise<void>; } /** * States the text file editor model can be in. */ export const enum ModelState { /** * A model is saved. */ SAVED, /** * A model is dirty. */ DIRTY, /** * A model is transitioning from dirty to saved. */ PENDING_SAVE, /** * A model is in conflict mode when changes cannot be saved because the * underlying file has changed. Models in conflict mode are always dirty. */ CONFLICT, /** * A model is in orphan state when the underlying file has been deleted. */ ORPHAN, /** * Any error that happens during a save that is not causing the CONFLICT state. * Models in error mode are always diry. */ ERROR } export const enum StateChange { DIRTY, SAVING, SAVE_ERROR, SAVED, REVERTED, ENCODING, CONTENT_CHANGE, ORPHANED_CHANGE } export class TextFileModelChangeEvent { private _resource: URI; constructor(model: ITextFileEditorModel, private _kind: StateChange) { this._resource = model.getResource(); } get resource(): URI { return this._resource; } get kind(): StateChange { return this._kind; } } export const AutoSaveContext = new RawContextKey<string>('config.files.autoSave', undefined); export interface ITextFileOperationResult { results: IResult[]; } export interface IResult { source: URI; target?: URI; success?: boolean; } export interface IAutoSaveConfiguration { autoSaveDelay?: number; autoSaveFocusChange: boolean; autoSaveApplicationChange: boolean; } export const enum AutoSaveMode { OFF, AFTER_SHORT_DELAY, AFTER_LONG_DELAY, ON_FOCUS_CHANGE, ON_WINDOW_CHANGE } export const enum SaveReason { EXPLICIT = 1, AUTO = 2, FOCUS_CHANGE = 3, WINDOW_CHANGE = 4 } export const enum LoadReason { EDITOR = 1, REFERENCE = 2, OTHER = 3 } interface IBaseTextFileContent extends IBaseStatWithMetadata { /** * The encoding of the content if known. */ encoding: string; } export interface ITextFileContent extends IBaseTextFileContent { /** * The content of a text file. */ value: string; } export interface ITextFileStreamContent extends IBaseTextFileContent { /** * The line grouped content of a text file. */ value: ITextBufferFactory; } export interface IModelLoadOrCreateOptions { /** * Context why the model is being loaded or created. */ reason?: LoadReason; /** * The language mode to use for the model text content. */ mode?: string; /** * The encoding to use when resolving the model text content. */ encoding?: string; /** * If the model was already loaded before, allows to trigger * a reload of it to fetch the latest contents: * - async: loadOrCreate() will return immediately and trigger * a reload that will run in the background. * - sync: loadOrCreate() will only return resolved when the * model has finished reloading. */ reload?: { async: boolean }; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; } export interface ITextFileEditorModelManager { readonly onModelDisposed: Event<URI>; readonly onModelContentChanged: Event<TextFileModelChangeEvent>; readonly onModelEncodingChanged: Event<TextFileModelChangeEvent>; readonly onModelDirty: Event<TextFileModelChangeEvent>; readonly onModelSaveError: Event<TextFileModelChangeEvent>; readonly onModelSaved: Event<TextFileModelChangeEvent>; readonly onModelReverted: Event<TextFileModelChangeEvent>; readonly onModelOrphanedChanged: Event<TextFileModelChangeEvent>; readonly onModelsDirty: Event<TextFileModelChangeEvent[]>; readonly onModelsSaveError: Event<TextFileModelChangeEvent[]>; readonly onModelsSaved: Event<TextFileModelChangeEvent[]>; readonly onModelsReverted: Event<TextFileModelChangeEvent[]>; get(resource: URI): ITextFileEditorModel | undefined; getAll(resource?: URI): ITextFileEditorModel[]; loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): Promise<ITextFileEditorModel>; disposeModel(model: ITextFileEditorModel): void; } export interface ISaveOptions { force?: boolean; reason?: SaveReason; overwriteReadonly?: boolean; overwriteEncoding?: boolean; skipSaveParticipants?: boolean; writeElevated?: boolean; availableFileSystems?: string[]; } export interface ILoadOptions { /** * Go to disk bypassing any cache of the model if any. */ forceReadFromDisk?: boolean; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; /** * Context why the model is being loaded. */ reason?: LoadReason; } export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport { readonly onDidContentChange: Event<StateChange>; readonly onDidStateChange: Event<StateChange>; getResource(): URI; hasState(state: ModelState): boolean; updatePreferredEncoding(encoding: string): void; save(options?: ISaveOptions): Promise<void>; load(options?: ILoadOptions): Promise<ITextFileEditorModel>; revert(soft?: boolean): Promise<void>; backup(target?: URI): Promise<void>; hasBackup(): boolean; isDirty(): boolean; isResolved(): this is IResolvedTextFileEditorModel; isDisposed(): boolean; } export interface IResolvedTextFileEditorModel extends ITextFileEditorModel { readonly textEditorModel: ITextModel; createSnapshot(): ITextSnapshot; } export interface IWillMoveEvent { oldResource: URI; newResource: URI; waitUntil(p: Promise<unknown>): void; } /** * Helper method to convert a snapshot into its full string form. */ export function
(snapshot: ITextSnapshot): string { const chunks: string[] = []; let chunk: string | null; while (typeof (chunk = snapshot.read()) === 'string') { chunks.push(chunk); } return chunks.join(''); } export function stringToSnapshot(value: string): ITextSnapshot { let done = false; return { read(): string | null { if (!done) { done = true; return value; } return null; } }; } export class TextSnapshotReadable implements VSBufferReadable { private preambleHandled: boolean; constructor(private snapshot: ITextSnapshot, private preamble?: string) { } read(): VSBuffer | null { let value = this.snapshot.read(); // Handle preamble if provided if (!this.preambleHandled) { this.preambleHandled = true; if (typeof this.preamble === 'string') { if (typeof value === 'string') { value = this.preamble + value; } else { value = this.preamble; } } } if (typeof value === 'string') { return VSBuffer.fromString(value); } return null; } } export function toBufferOrReadable(value: string): VSBuffer; export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined { if (typeof value === 'undefined') { return undefined; } if (typeof value === 'string') { return VSBuffer.fromString(value); } return new TextSnapshotReadable(value); } export const SUPPORTED_ENCODINGS: { [encoding: string]: { labelLong: string; labelShort: string; order: number; encodeOnly?: boolean; alias?: string } } = { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' }, utf8bom: { labelLong: 'UTF-8 with BOM', labelShort: 'UTF-8 with BOM', encodeOnly: true, order: 2, alias: 'utf8' }, utf16le: { labelLong: 'UTF-16 LE', labelShort: 'UTF-16 LE', order: 3 }, utf16be: { labelLong: 'UTF-16 BE', labelShort: 'UTF-16 BE', order: 4 }, windows1252: { labelLong: 'Western (Windows 1252)', labelShort: 'Windows 1252', order: 5 }, iso88591: { labelLong: 'Western (ISO 8859-1)', labelShort: 'ISO 8859-1', order: 6 }, iso88593: { labelLong: 'Western (ISO 8859-3)', labelShort: 'ISO 8859-3', order: 7 }, iso885915: { labelLong: 'Western (ISO 8859-15)', labelShort: 'ISO 8859-15', order: 8 }, macroman: { labelLong: 'Western (Mac Roman)', labelShort: 'Mac Roman', order: 9 }, cp437: { labelLong: 'DOS (CP 437)', labelShort: 'CP437', order: 10 }, windows1256: { labelLong: 'Arabic (Windows 1256)', labelShort: 'Windows 1256', order: 11 }, iso88596: { labelLong: 'Arabic (ISO 8859-6)', labelShort: 'ISO 8859-6', order: 12 }, windows1257: { labelLong: 'Baltic (Windows 1257)', labelShort: 'Windows 1257', order: 13 }, iso88594: { labelLong: 'Baltic (ISO 8859-4)', labelShort: 'ISO 8859-4', order: 14 }, iso885914: { labelLong: 'Celtic (ISO 8859-14)', labelShort: 'ISO 8859-14', order: 15 }, windows1250: { labelLong: 'Central European (Windows 1250)', labelShort: 'Windows 1250', order: 16 }, iso88592: { labelLong: 'Central European (ISO 8859-2)', labelShort: 'ISO 8859-2', order: 17 }, cp852: { labelLong: 'Central European (CP 852)', labelShort: 'CP 852', order: 18 }, windows1251: { labelLong: 'Cyrillic (Windows 1251)', labelShort: 'Windows 1251', order: 19 }, cp866: { labelLong: 'Cyrillic (CP 866)', labelShort: 'CP 866', order: 20 }, iso88595: { labelLong: 'Cyrillic (ISO 8859-5)', labelShort: 'ISO 8859-5', order: 21 }, koi8r: { labelLong: 'Cyrillic (KOI8-R)', labelShort: 'KOI8-R', order: 22 }, koi8u: { labelLong: 'Cyrillic (KOI8-U)', labelShort: 'KOI8-U', order: 23 }, iso885913: { labelLong: 'Estonian (ISO 8859-13)', labelShort: 'ISO 8859-13', order: 24 }, windows1253: { labelLong: 'Greek (Windows 1253)', labelShort: 'Windows 1253', order: 25 }, iso88597: { labelLong: 'Greek (ISO 8859-7)', labelShort: 'ISO 8859-7', order: 26 }, windows1255: { labelLong: 'Hebrew (Windows 1255)', labelShort: 'Windows 1255', order: 27 }, iso88598: { labelLong: 'Hebrew (ISO 8859-8)', labelShort: 'ISO 8859-8', order: 28 }, iso885910: { labelLong: 'Nordic (ISO 8859-10)', labelShort: 'ISO 8859-10', order: 29 }, iso885916: { labelLong: 'Romanian (ISO 8859-16)', labelShort: 'ISO 8859-16', order: 30 }, windows1254: { labelLong: 'Turkish (Windows 1254)', labelShort: 'Windows 1254', order: 31 }, iso88599: { labelLong: 'Turkish (ISO 8859-9)', labelShort: 'ISO 8859-9', order: 32 }, windows1258: { labelLong: 'Vietnamese (Windows 1258)', labelShort: 'Windows 1258', order: 33 }, gbk: { labelLong: 'Simplified Chinese (GBK)', labelShort: 'GBK', order: 34 }, gb18030: { labelLong: 'Simplified Chinese (GB18030)', labelShort: 'GB18030', order: 35 }, cp950: { labelLong: 'Traditional Chinese (Big5)', labelShort: 'Big5', order: 36 }, big5hkscs: { labelLong: 'Traditional Chinese (Big5-HKSCS)', labelShort: 'Big5-HKSCS', order: 37 }, shiftjis: { labelLong: 'Japanese (Shift JIS)', labelShort: 'Shift JIS', order: 38 }, eucjp: { labelLong: 'Japanese (EUC-JP)', labelShort: 'EUC-JP', order: 39 }, euckr: { labelLong: 'Korean (EUC-KR)', labelShort: 'EUC-KR', order: 40 }, windows874: { labelLong: 'Thai (Windows 874)', labelShort: 'Windows 874', order: 41 }, iso885911: { labelLong: 'Latin/Thai (ISO 8859-11)', labelShort: 'ISO 8859-11', order: 42 }, koi8ru: { labelLong: 'Cyrillic (KOI8-RU)', labelShort: 'KOI8-RU', order: 43 }, koi8t: { labelLong: 'Tajik (KOI8-T)', labelShort: 'KOI8-T', order: 44 }, gb2312: { labelLong: 'Simplified Chinese (GB 2312)', labelShort: 'GB 2312', order: 45 }, cp865: { labelLong: 'Nordic DOS (CP 865)', labelShort: 'CP 865', order: 46 }, cp850: { labelLong: 'Western European DOS (CP 850)', labelShort: 'CP 850', order: 47 } };
snapshotToString
identifier_name
textfiles.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEncodingSupport, ConfirmResult, IRevertOptions, IModeSupport } from 'vs/workbench/common/editor'; import { IBaseStatWithMetadata, IFileStatWithMetadata, IReadFileOptions, IWriteFileOptions, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer'; import { isUndefinedOrNull } from 'vs/base/common/types'; export const ITextFileService = createDecorator<ITextFileService>('textFileService'); export interface ITextFileService extends IDisposable { _serviceBrand: ServiceIdentifier<any>; readonly onWillMove: Event<IWillMoveEvent>; readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>; readonly onFilesAssociationChange: Event<void>; readonly isHotExitEnabled: boolean; /** * Access to the manager of text file editor models providing further methods to work with them. */ readonly models: ITextFileEditorModelManager; /** * Helper to determine encoding for resources. */ readonly encoding: IResourceEncodings; /** * A resource is dirty if it has unsaved changes or is an untitled file not yet saved. * * @param resource the resource to check for being dirty. If it is not specified, will check for * all dirty resources. */ isDirty(resource?: URI): boolean; /** * Returns all resources that are currently dirty matching the provided resources or all dirty resources. * * @param resources the resources to check for being dirty. If it is not specified, will check for * all dirty resources. */ getDirty(resources?: URI[]): URI[]; /** * Saves the resource. * * @param resource the resource to save * @param options optional save options * @return true if the resource was saved. */ save(resource: URI, options?: ISaveOptions): Promise<boolean>; /** * Saves the provided resource asking the user for a file name or using the provided one. * * @param resource the resource to save as. * @param targetResource the optional target to save to. * @param options optional save options * @return Path of the saved resource. */ saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined>; /** * Saves the set of resources and returns a promise with the operation result. * * @param resources can be null to save all. * @param includeUntitled to save all resources and optionally exclude untitled ones. */ saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>; saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>; /** * Reverts the provided resource. * * @param resource the resource of the file to revert. * @param force to force revert even when the file is not dirty */ revert(resource: URI, options?: IRevertOptions): Promise<boolean>; /** * Reverts all the provided resources and returns a promise with the operation result. */ revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult>; /** * Create a file. If the file exists it will be overwritten with the contents if * the options enable to overwrite. */ create(resource: URI, contents?: string | ITextSnapshot, options?: { overwrite?: boolean }): Promise<IFileStatWithMetadata>; /** * Read the contents of a file identified by the resource. */ read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>; /** * Read the contents of a file identified by the resource as stream. */ readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>; /** * Update a file with given contents. */ write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>; /** * Delete a file. If the file is dirty, it will get reverted and then deleted from disk. */ delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void>; /** * Move a file. If the file is dirty, its contents will be preserved and restored. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Brings up the confirm dialog to either save, don't save or cancel. * * @param resources the resources of the files to ask for confirmation or null if * confirming for all dirty resources. */ confirmSave(resources?: URI[]): Promise<ConfirmResult>; /** * Convenient fast access to the current auto save mode. */ getAutoSaveMode(): AutoSaveMode; /** * Convenient fast access to the raw configured auto save settings. */ getAutoSaveConfiguration(): IAutoSaveConfiguration; } export interface IReadTextFileOptions extends IReadFileOptions { /** * The optional acceptTextOnly parameter allows to fail this request early if the file * contents are not textual. */ acceptTextOnly?: boolean; /** * The optional encoding parameter allows to specify the desired encoding when resolving * the contents of the file. */ encoding?: string; /** * The optional guessEncoding parameter allows to guess encoding from content of the file. */ autoGuessEncoding?: boolean; } export interface IWriteTextFileOptions extends IWriteFileOptions { /** * The encoding to use when updating a file. */ encoding?: string; /** * If set to true, will enforce the selected encoding and not perform any detection using BOMs. */ overwriteEncoding?: boolean; /** * Whether to overwrite a file even if it is readonly. */ overwriteReadonly?: boolean; /** * Wether to write to the file as elevated (admin) user. When setting this option a prompt will * ask the user to authenticate as super user. */ writeElevated?: boolean; } export const enum TextFileOperationResult { FILE_IS_BINARY } export class TextFileOperationError extends FileOperationError { constructor(message: string, public textFileOperationResult: TextFileOperationResult, public options?: IReadTextFileOptions & IWriteTextFileOptions) { super(message, FileOperationResult.FILE_OTHER_ERROR); } static isTextFileOperationError(obj: unknown): obj is TextFileOperationError { return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult); } } export interface IResourceEncodings { getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding; } export interface IResourceEncoding { encoding: string; hasBOM: boolean; } /** * The save error handler can be installed on the text file editor model to install code that executes when save errors occur. */ export interface ISaveErrorHandler { /** * Called whenever a save fails. */ onSaveError(error: Error, model: ITextFileEditorModel): void; } export interface ISaveParticipant { /** * Participate in a save of a model. Allows to change the model before it is being saved to disk. */ participate(model: IResolvedTextFileEditorModel, env: { reason: SaveReason }): Promise<void>; } /** * States the text file editor model can be in. */ export const enum ModelState { /** * A model is saved. */ SAVED, /** * A model is dirty. */ DIRTY, /** * A model is transitioning from dirty to saved. */ PENDING_SAVE, /** * A model is in conflict mode when changes cannot be saved because the * underlying file has changed. Models in conflict mode are always dirty. */ CONFLICT, /** * A model is in orphan state when the underlying file has been deleted. */ ORPHAN, /** * Any error that happens during a save that is not causing the CONFLICT state. * Models in error mode are always diry. */ ERROR } export const enum StateChange { DIRTY, SAVING, SAVE_ERROR, SAVED, REVERTED, ENCODING, CONTENT_CHANGE, ORPHANED_CHANGE } export class TextFileModelChangeEvent { private _resource: URI; constructor(model: ITextFileEditorModel, private _kind: StateChange) { this._resource = model.getResource(); } get resource(): URI { return this._resource; } get kind(): StateChange { return this._kind; } } export const AutoSaveContext = new RawContextKey<string>('config.files.autoSave', undefined); export interface ITextFileOperationResult { results: IResult[]; } export interface IResult { source: URI; target?: URI; success?: boolean; } export interface IAutoSaveConfiguration { autoSaveDelay?: number; autoSaveFocusChange: boolean; autoSaveApplicationChange: boolean; } export const enum AutoSaveMode { OFF, AFTER_SHORT_DELAY, AFTER_LONG_DELAY, ON_FOCUS_CHANGE, ON_WINDOW_CHANGE } export const enum SaveReason { EXPLICIT = 1, AUTO = 2, FOCUS_CHANGE = 3, WINDOW_CHANGE = 4 } export const enum LoadReason { EDITOR = 1, REFERENCE = 2, OTHER = 3 } interface IBaseTextFileContent extends IBaseStatWithMetadata { /** * The encoding of the content if known. */ encoding: string; } export interface ITextFileContent extends IBaseTextFileContent { /** * The content of a text file. */ value: string; } export interface ITextFileStreamContent extends IBaseTextFileContent { /** * The line grouped content of a text file. */ value: ITextBufferFactory; } export interface IModelLoadOrCreateOptions { /** * Context why the model is being loaded or created. */ reason?: LoadReason; /** * The language mode to use for the model text content. */ mode?: string; /** * The encoding to use when resolving the model text content. */ encoding?: string; /** * If the model was already loaded before, allows to trigger * a reload of it to fetch the latest contents: * - async: loadOrCreate() will return immediately and trigger * a reload that will run in the background. * - sync: loadOrCreate() will only return resolved when the * model has finished reloading. */ reload?: { async: boolean }; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; } export interface ITextFileEditorModelManager { readonly onModelDisposed: Event<URI>; readonly onModelContentChanged: Event<TextFileModelChangeEvent>; readonly onModelEncodingChanged: Event<TextFileModelChangeEvent>; readonly onModelDirty: Event<TextFileModelChangeEvent>; readonly onModelSaveError: Event<TextFileModelChangeEvent>; readonly onModelSaved: Event<TextFileModelChangeEvent>; readonly onModelReverted: Event<TextFileModelChangeEvent>; readonly onModelOrphanedChanged: Event<TextFileModelChangeEvent>; readonly onModelsDirty: Event<TextFileModelChangeEvent[]>; readonly onModelsSaveError: Event<TextFileModelChangeEvent[]>; readonly onModelsSaved: Event<TextFileModelChangeEvent[]>; readonly onModelsReverted: Event<TextFileModelChangeEvent[]>; get(resource: URI): ITextFileEditorModel | undefined; getAll(resource?: URI): ITextFileEditorModel[]; loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): Promise<ITextFileEditorModel>; disposeModel(model: ITextFileEditorModel): void; } export interface ISaveOptions { force?: boolean; reason?: SaveReason; overwriteReadonly?: boolean; overwriteEncoding?: boolean; skipSaveParticipants?: boolean; writeElevated?: boolean; availableFileSystems?: string[]; } export interface ILoadOptions { /** * Go to disk bypassing any cache of the model if any. */ forceReadFromDisk?: boolean; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; /** * Context why the model is being loaded. */ reason?: LoadReason; } export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport { readonly onDidContentChange: Event<StateChange>; readonly onDidStateChange: Event<StateChange>; getResource(): URI; hasState(state: ModelState): boolean; updatePreferredEncoding(encoding: string): void; save(options?: ISaveOptions): Promise<void>; load(options?: ILoadOptions): Promise<ITextFileEditorModel>; revert(soft?: boolean): Promise<void>; backup(target?: URI): Promise<void>; hasBackup(): boolean; isDirty(): boolean; isResolved(): this is IResolvedTextFileEditorModel; isDisposed(): boolean; } export interface IResolvedTextFileEditorModel extends ITextFileEditorModel { readonly textEditorModel: ITextModel; createSnapshot(): ITextSnapshot; } export interface IWillMoveEvent { oldResource: URI; newResource: URI; waitUntil(p: Promise<unknown>): void; } /** * Helper method to convert a snapshot into its full string form. */ export function snapshotToString(snapshot: ITextSnapshot): string { const chunks: string[] = []; let chunk: string | null; while (typeof (chunk = snapshot.read()) === 'string') { chunks.push(chunk); } return chunks.join(''); } export function stringToSnapshot(value: string): ITextSnapshot { let done = false; return { read(): string | null { if (!done) { done = true; return value; } return null; } }; } export class TextSnapshotReadable implements VSBufferReadable { private preambleHandled: boolean; constructor(private snapshot: ITextSnapshot, private preamble?: string)
read(): VSBuffer | null { let value = this.snapshot.read(); // Handle preamble if provided if (!this.preambleHandled) { this.preambleHandled = true; if (typeof this.preamble === 'string') { if (typeof value === 'string') { value = this.preamble + value; } else { value = this.preamble; } } } if (typeof value === 'string') { return VSBuffer.fromString(value); } return null; } } export function toBufferOrReadable(value: string): VSBuffer; export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined { if (typeof value === 'undefined') { return undefined; } if (typeof value === 'string') { return VSBuffer.fromString(value); } return new TextSnapshotReadable(value); } export const SUPPORTED_ENCODINGS: { [encoding: string]: { labelLong: string; labelShort: string; order: number; encodeOnly?: boolean; alias?: string } } = { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' }, utf8bom: { labelLong: 'UTF-8 with BOM', labelShort: 'UTF-8 with BOM', encodeOnly: true, order: 2, alias: 'utf8' }, utf16le: { labelLong: 'UTF-16 LE', labelShort: 'UTF-16 LE', order: 3 }, utf16be: { labelLong: 'UTF-16 BE', labelShort: 'UTF-16 BE', order: 4 }, windows1252: { labelLong: 'Western (Windows 1252)', labelShort: 'Windows 1252', order: 5 }, iso88591: { labelLong: 'Western (ISO 8859-1)', labelShort: 'ISO 8859-1', order: 6 }, iso88593: { labelLong: 'Western (ISO 8859-3)', labelShort: 'ISO 8859-3', order: 7 }, iso885915: { labelLong: 'Western (ISO 8859-15)', labelShort: 'ISO 8859-15', order: 8 }, macroman: { labelLong: 'Western (Mac Roman)', labelShort: 'Mac Roman', order: 9 }, cp437: { labelLong: 'DOS (CP 437)', labelShort: 'CP437', order: 10 }, windows1256: { labelLong: 'Arabic (Windows 1256)', labelShort: 'Windows 1256', order: 11 }, iso88596: { labelLong: 'Arabic (ISO 8859-6)', labelShort: 'ISO 8859-6', order: 12 }, windows1257: { labelLong: 'Baltic (Windows 1257)', labelShort: 'Windows 1257', order: 13 }, iso88594: { labelLong: 'Baltic (ISO 8859-4)', labelShort: 'ISO 8859-4', order: 14 }, iso885914: { labelLong: 'Celtic (ISO 8859-14)', labelShort: 'ISO 8859-14', order: 15 }, windows1250: { labelLong: 'Central European (Windows 1250)', labelShort: 'Windows 1250', order: 16 }, iso88592: { labelLong: 'Central European (ISO 8859-2)', labelShort: 'ISO 8859-2', order: 17 }, cp852: { labelLong: 'Central European (CP 852)', labelShort: 'CP 852', order: 18 }, windows1251: { labelLong: 'Cyrillic (Windows 1251)', labelShort: 'Windows 1251', order: 19 }, cp866: { labelLong: 'Cyrillic (CP 866)', labelShort: 'CP 866', order: 20 }, iso88595: { labelLong: 'Cyrillic (ISO 8859-5)', labelShort: 'ISO 8859-5', order: 21 }, koi8r: { labelLong: 'Cyrillic (KOI8-R)', labelShort: 'KOI8-R', order: 22 }, koi8u: { labelLong: 'Cyrillic (KOI8-U)', labelShort: 'KOI8-U', order: 23 }, iso885913: { labelLong: 'Estonian (ISO 8859-13)', labelShort: 'ISO 8859-13', order: 24 }, windows1253: { labelLong: 'Greek (Windows 1253)', labelShort: 'Windows 1253', order: 25 }, iso88597: { labelLong: 'Greek (ISO 8859-7)', labelShort: 'ISO 8859-7', order: 26 }, windows1255: { labelLong: 'Hebrew (Windows 1255)', labelShort: 'Windows 1255', order: 27 }, iso88598: { labelLong: 'Hebrew (ISO 8859-8)', labelShort: 'ISO 8859-8', order: 28 }, iso885910: { labelLong: 'Nordic (ISO 8859-10)', labelShort: 'ISO 8859-10', order: 29 }, iso885916: { labelLong: 'Romanian (ISO 8859-16)', labelShort: 'ISO 8859-16', order: 30 }, windows1254: { labelLong: 'Turkish (Windows 1254)', labelShort: 'Windows 1254', order: 31 }, iso88599: { labelLong: 'Turkish (ISO 8859-9)', labelShort: 'ISO 8859-9', order: 32 }, windows1258: { labelLong: 'Vietnamese (Windows 1258)', labelShort: 'Windows 1258', order: 33 }, gbk: { labelLong: 'Simplified Chinese (GBK)', labelShort: 'GBK', order: 34 }, gb18030: { labelLong: 'Simplified Chinese (GB18030)', labelShort: 'GB18030', order: 35 }, cp950: { labelLong: 'Traditional Chinese (Big5)', labelShort: 'Big5', order: 36 }, big5hkscs: { labelLong: 'Traditional Chinese (Big5-HKSCS)', labelShort: 'Big5-HKSCS', order: 37 }, shiftjis: { labelLong: 'Japanese (Shift JIS)', labelShort: 'Shift JIS', order: 38 }, eucjp: { labelLong: 'Japanese (EUC-JP)', labelShort: 'EUC-JP', order: 39 }, euckr: { labelLong: 'Korean (EUC-KR)', labelShort: 'EUC-KR', order: 40 }, windows874: { labelLong: 'Thai (Windows 874)', labelShort: 'Windows 874', order: 41 }, iso885911: { labelLong: 'Latin/Thai (ISO 8859-11)', labelShort: 'ISO 8859-11', order: 42 }, koi8ru: { labelLong: 'Cyrillic (KOI8-RU)', labelShort: 'KOI8-RU', order: 43 }, koi8t: { labelLong: 'Tajik (KOI8-T)', labelShort: 'KOI8-T', order: 44 }, gb2312: { labelLong: 'Simplified Chinese (GB 2312)', labelShort: 'GB 2312', order: 45 }, cp865: { labelLong: 'Nordic DOS (CP 865)', labelShort: 'CP 865', order: 46 }, cp850: { labelLong: 'Western European DOS (CP 850)', labelShort: 'CP 850', order: 47 } };
{ }
identifier_body
textfiles.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEncodingSupport, ConfirmResult, IRevertOptions, IModeSupport } from 'vs/workbench/common/editor'; import { IBaseStatWithMetadata, IFileStatWithMetadata, IReadFileOptions, IWriteFileOptions, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer'; import { isUndefinedOrNull } from 'vs/base/common/types'; export const ITextFileService = createDecorator<ITextFileService>('textFileService'); export interface ITextFileService extends IDisposable { _serviceBrand: ServiceIdentifier<any>; readonly onWillMove: Event<IWillMoveEvent>; readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>; readonly onFilesAssociationChange: Event<void>; readonly isHotExitEnabled: boolean; /** * Access to the manager of text file editor models providing further methods to work with them. */ readonly models: ITextFileEditorModelManager; /** * Helper to determine encoding for resources. */ readonly encoding: IResourceEncodings; /** * A resource is dirty if it has unsaved changes or is an untitled file not yet saved. * * @param resource the resource to check for being dirty. If it is not specified, will check for * all dirty resources. */ isDirty(resource?: URI): boolean; /** * Returns all resources that are currently dirty matching the provided resources or all dirty resources. * * @param resources the resources to check for being dirty. If it is not specified, will check for * all dirty resources. */ getDirty(resources?: URI[]): URI[]; /** * Saves the resource. * * @param resource the resource to save * @param options optional save options * @return true if the resource was saved. */ save(resource: URI, options?: ISaveOptions): Promise<boolean>; /** * Saves the provided resource asking the user for a file name or using the provided one. * * @param resource the resource to save as. * @param targetResource the optional target to save to. * @param options optional save options * @return Path of the saved resource. */ saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined>; /** * Saves the set of resources and returns a promise with the operation result. * * @param resources can be null to save all. * @param includeUntitled to save all resources and optionally exclude untitled ones. */ saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>; saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>; /** * Reverts the provided resource. * * @param resource the resource of the file to revert. * @param force to force revert even when the file is not dirty */ revert(resource: URI, options?: IRevertOptions): Promise<boolean>; /** * Reverts all the provided resources and returns a promise with the operation result. */ revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult>; /** * Create a file. If the file exists it will be overwritten with the contents if * the options enable to overwrite. */ create(resource: URI, contents?: string | ITextSnapshot, options?: { overwrite?: boolean }): Promise<IFileStatWithMetadata>; /** * Read the contents of a file identified by the resource. */ read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>; /** * Read the contents of a file identified by the resource as stream. */ readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>; /** * Update a file with given contents. */ write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>; /** * Delete a file. If the file is dirty, it will get reverted and then deleted from disk. */ delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void>; /** * Move a file. If the file is dirty, its contents will be preserved and restored. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Brings up the confirm dialog to either save, don't save or cancel. * * @param resources the resources of the files to ask for confirmation or null if * confirming for all dirty resources. */ confirmSave(resources?: URI[]): Promise<ConfirmResult>; /** * Convenient fast access to the current auto save mode. */ getAutoSaveMode(): AutoSaveMode; /** * Convenient fast access to the raw configured auto save settings. */ getAutoSaveConfiguration(): IAutoSaveConfiguration; } export interface IReadTextFileOptions extends IReadFileOptions { /** * The optional acceptTextOnly parameter allows to fail this request early if the file * contents are not textual. */ acceptTextOnly?: boolean; /** * The optional encoding parameter allows to specify the desired encoding when resolving * the contents of the file. */ encoding?: string; /** * The optional guessEncoding parameter allows to guess encoding from content of the file. */ autoGuessEncoding?: boolean; } export interface IWriteTextFileOptions extends IWriteFileOptions { /** * The encoding to use when updating a file. */ encoding?: string; /** * If set to true, will enforce the selected encoding and not perform any detection using BOMs. */ overwriteEncoding?: boolean; /** * Whether to overwrite a file even if it is readonly. */ overwriteReadonly?: boolean; /** * Wether to write to the file as elevated (admin) user. When setting this option a prompt will * ask the user to authenticate as super user. */ writeElevated?: boolean; } export const enum TextFileOperationResult { FILE_IS_BINARY } export class TextFileOperationError extends FileOperationError { constructor(message: string, public textFileOperationResult: TextFileOperationResult, public options?: IReadTextFileOptions & IWriteTextFileOptions) { super(message, FileOperationResult.FILE_OTHER_ERROR); } static isTextFileOperationError(obj: unknown): obj is TextFileOperationError { return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult); } } export interface IResourceEncodings { getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding; } export interface IResourceEncoding { encoding: string; hasBOM: boolean; } /** * The save error handler can be installed on the text file editor model to install code that executes when save errors occur. */ export interface ISaveErrorHandler { /** * Called whenever a save fails. */ onSaveError(error: Error, model: ITextFileEditorModel): void; } export interface ISaveParticipant { /** * Participate in a save of a model. Allows to change the model before it is being saved to disk. */ participate(model: IResolvedTextFileEditorModel, env: { reason: SaveReason }): Promise<void>; } /** * States the text file editor model can be in. */ export const enum ModelState { /** * A model is saved. */ SAVED, /** * A model is dirty. */ DIRTY, /** * A model is transitioning from dirty to saved. */ PENDING_SAVE, /** * A model is in conflict mode when changes cannot be saved because the * underlying file has changed. Models in conflict mode are always dirty. */ CONFLICT, /** * A model is in orphan state when the underlying file has been deleted. */ ORPHAN, /** * Any error that happens during a save that is not causing the CONFLICT state. * Models in error mode are always diry. */ ERROR } export const enum StateChange { DIRTY, SAVING, SAVE_ERROR, SAVED, REVERTED, ENCODING, CONTENT_CHANGE, ORPHANED_CHANGE } export class TextFileModelChangeEvent { private _resource: URI; constructor(model: ITextFileEditorModel, private _kind: StateChange) { this._resource = model.getResource(); } get resource(): URI { return this._resource; } get kind(): StateChange { return this._kind; } } export const AutoSaveContext = new RawContextKey<string>('config.files.autoSave', undefined); export interface ITextFileOperationResult { results: IResult[]; } export interface IResult { source: URI; target?: URI; success?: boolean; } export interface IAutoSaveConfiguration { autoSaveDelay?: number; autoSaveFocusChange: boolean; autoSaveApplicationChange: boolean; } export const enum AutoSaveMode { OFF, AFTER_SHORT_DELAY, AFTER_LONG_DELAY, ON_FOCUS_CHANGE, ON_WINDOW_CHANGE } export const enum SaveReason { EXPLICIT = 1, AUTO = 2, FOCUS_CHANGE = 3, WINDOW_CHANGE = 4 } export const enum LoadReason { EDITOR = 1, REFERENCE = 2, OTHER = 3 } interface IBaseTextFileContent extends IBaseStatWithMetadata { /** * The encoding of the content if known. */ encoding: string; } export interface ITextFileContent extends IBaseTextFileContent { /** * The content of a text file. */ value: string; } export interface ITextFileStreamContent extends IBaseTextFileContent { /** * The line grouped content of a text file. */ value: ITextBufferFactory; } export interface IModelLoadOrCreateOptions { /** * Context why the model is being loaded or created. */ reason?: LoadReason; /** * The language mode to use for the model text content. */ mode?: string; /** * The encoding to use when resolving the model text content. */ encoding?: string; /** * If the model was already loaded before, allows to trigger * a reload of it to fetch the latest contents: * - async: loadOrCreate() will return immediately and trigger * a reload that will run in the background. * - sync: loadOrCreate() will only return resolved when the * model has finished reloading. */ reload?: { async: boolean }; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; } export interface ITextFileEditorModelManager { readonly onModelDisposed: Event<URI>; readonly onModelContentChanged: Event<TextFileModelChangeEvent>; readonly onModelEncodingChanged: Event<TextFileModelChangeEvent>; readonly onModelDirty: Event<TextFileModelChangeEvent>; readonly onModelSaveError: Event<TextFileModelChangeEvent>; readonly onModelSaved: Event<TextFileModelChangeEvent>; readonly onModelReverted: Event<TextFileModelChangeEvent>; readonly onModelOrphanedChanged: Event<TextFileModelChangeEvent>; readonly onModelsDirty: Event<TextFileModelChangeEvent[]>; readonly onModelsSaveError: Event<TextFileModelChangeEvent[]>; readonly onModelsSaved: Event<TextFileModelChangeEvent[]>; readonly onModelsReverted: Event<TextFileModelChangeEvent[]>; get(resource: URI): ITextFileEditorModel | undefined; getAll(resource?: URI): ITextFileEditorModel[]; loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): Promise<ITextFileEditorModel>; disposeModel(model: ITextFileEditorModel): void; } export interface ISaveOptions { force?: boolean; reason?: SaveReason; overwriteReadonly?: boolean; overwriteEncoding?: boolean; skipSaveParticipants?: boolean; writeElevated?: boolean; availableFileSystems?: string[]; } export interface ILoadOptions { /** * Go to disk bypassing any cache of the model if any. */ forceReadFromDisk?: boolean; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; /** * Context why the model is being loaded. */ reason?: LoadReason; } export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport { readonly onDidContentChange: Event<StateChange>; readonly onDidStateChange: Event<StateChange>; getResource(): URI; hasState(state: ModelState): boolean; updatePreferredEncoding(encoding: string): void; save(options?: ISaveOptions): Promise<void>; load(options?: ILoadOptions): Promise<ITextFileEditorModel>; revert(soft?: boolean): Promise<void>; backup(target?: URI): Promise<void>; hasBackup(): boolean; isDirty(): boolean; isResolved(): this is IResolvedTextFileEditorModel; isDisposed(): boolean; } export interface IResolvedTextFileEditorModel extends ITextFileEditorModel { readonly textEditorModel: ITextModel; createSnapshot(): ITextSnapshot; } export interface IWillMoveEvent { oldResource: URI; newResource: URI; waitUntil(p: Promise<unknown>): void; } /** * Helper method to convert a snapshot into its full string form. */ export function snapshotToString(snapshot: ITextSnapshot): string { const chunks: string[] = []; let chunk: string | null; while (typeof (chunk = snapshot.read()) === 'string')
return chunks.join(''); } export function stringToSnapshot(value: string): ITextSnapshot { let done = false; return { read(): string | null { if (!done) { done = true; return value; } return null; } }; } export class TextSnapshotReadable implements VSBufferReadable { private preambleHandled: boolean; constructor(private snapshot: ITextSnapshot, private preamble?: string) { } read(): VSBuffer | null { let value = this.snapshot.read(); // Handle preamble if provided if (!this.preambleHandled) { this.preambleHandled = true; if (typeof this.preamble === 'string') { if (typeof value === 'string') { value = this.preamble + value; } else { value = this.preamble; } } } if (typeof value === 'string') { return VSBuffer.fromString(value); } return null; } } export function toBufferOrReadable(value: string): VSBuffer; export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined { if (typeof value === 'undefined') { return undefined; } if (typeof value === 'string') { return VSBuffer.fromString(value); } return new TextSnapshotReadable(value); } export const SUPPORTED_ENCODINGS: { [encoding: string]: { labelLong: string; labelShort: string; order: number; encodeOnly?: boolean; alias?: string } } = { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' }, utf8bom: { labelLong: 'UTF-8 with BOM', labelShort: 'UTF-8 with BOM', encodeOnly: true, order: 2, alias: 'utf8' }, utf16le: { labelLong: 'UTF-16 LE', labelShort: 'UTF-16 LE', order: 3 }, utf16be: { labelLong: 'UTF-16 BE', labelShort: 'UTF-16 BE', order: 4 }, windows1252: { labelLong: 'Western (Windows 1252)', labelShort: 'Windows 1252', order: 5 }, iso88591: { labelLong: 'Western (ISO 8859-1)', labelShort: 'ISO 8859-1', order: 6 }, iso88593: { labelLong: 'Western (ISO 8859-3)', labelShort: 'ISO 8859-3', order: 7 }, iso885915: { labelLong: 'Western (ISO 8859-15)', labelShort: 'ISO 8859-15', order: 8 }, macroman: { labelLong: 'Western (Mac Roman)', labelShort: 'Mac Roman', order: 9 }, cp437: { labelLong: 'DOS (CP 437)', labelShort: 'CP437', order: 10 }, windows1256: { labelLong: 'Arabic (Windows 1256)', labelShort: 'Windows 1256', order: 11 }, iso88596: { labelLong: 'Arabic (ISO 8859-6)', labelShort: 'ISO 8859-6', order: 12 }, windows1257: { labelLong: 'Baltic (Windows 1257)', labelShort: 'Windows 1257', order: 13 }, iso88594: { labelLong: 'Baltic (ISO 8859-4)', labelShort: 'ISO 8859-4', order: 14 }, iso885914: { labelLong: 'Celtic (ISO 8859-14)', labelShort: 'ISO 8859-14', order: 15 }, windows1250: { labelLong: 'Central European (Windows 1250)', labelShort: 'Windows 1250', order: 16 }, iso88592: { labelLong: 'Central European (ISO 8859-2)', labelShort: 'ISO 8859-2', order: 17 }, cp852: { labelLong: 'Central European (CP 852)', labelShort: 'CP 852', order: 18 }, windows1251: { labelLong: 'Cyrillic (Windows 1251)', labelShort: 'Windows 1251', order: 19 }, cp866: { labelLong: 'Cyrillic (CP 866)', labelShort: 'CP 866', order: 20 }, iso88595: { labelLong: 'Cyrillic (ISO 8859-5)', labelShort: 'ISO 8859-5', order: 21 }, koi8r: { labelLong: 'Cyrillic (KOI8-R)', labelShort: 'KOI8-R', order: 22 }, koi8u: { labelLong: 'Cyrillic (KOI8-U)', labelShort: 'KOI8-U', order: 23 }, iso885913: { labelLong: 'Estonian (ISO 8859-13)', labelShort: 'ISO 8859-13', order: 24 }, windows1253: { labelLong: 'Greek (Windows 1253)', labelShort: 'Windows 1253', order: 25 }, iso88597: { labelLong: 'Greek (ISO 8859-7)', labelShort: 'ISO 8859-7', order: 26 }, windows1255: { labelLong: 'Hebrew (Windows 1255)', labelShort: 'Windows 1255', order: 27 }, iso88598: { labelLong: 'Hebrew (ISO 8859-8)', labelShort: 'ISO 8859-8', order: 28 }, iso885910: { labelLong: 'Nordic (ISO 8859-10)', labelShort: 'ISO 8859-10', order: 29 }, iso885916: { labelLong: 'Romanian (ISO 8859-16)', labelShort: 'ISO 8859-16', order: 30 }, windows1254: { labelLong: 'Turkish (Windows 1254)', labelShort: 'Windows 1254', order: 31 }, iso88599: { labelLong: 'Turkish (ISO 8859-9)', labelShort: 'ISO 8859-9', order: 32 }, windows1258: { labelLong: 'Vietnamese (Windows 1258)', labelShort: 'Windows 1258', order: 33 }, gbk: { labelLong: 'Simplified Chinese (GBK)', labelShort: 'GBK', order: 34 }, gb18030: { labelLong: 'Simplified Chinese (GB18030)', labelShort: 'GB18030', order: 35 }, cp950: { labelLong: 'Traditional Chinese (Big5)', labelShort: 'Big5', order: 36 }, big5hkscs: { labelLong: 'Traditional Chinese (Big5-HKSCS)', labelShort: 'Big5-HKSCS', order: 37 }, shiftjis: { labelLong: 'Japanese (Shift JIS)', labelShort: 'Shift JIS', order: 38 }, eucjp: { labelLong: 'Japanese (EUC-JP)', labelShort: 'EUC-JP', order: 39 }, euckr: { labelLong: 'Korean (EUC-KR)', labelShort: 'EUC-KR', order: 40 }, windows874: { labelLong: 'Thai (Windows 874)', labelShort: 'Windows 874', order: 41 }, iso885911: { labelLong: 'Latin/Thai (ISO 8859-11)', labelShort: 'ISO 8859-11', order: 42 }, koi8ru: { labelLong: 'Cyrillic (KOI8-RU)', labelShort: 'KOI8-RU', order: 43 }, koi8t: { labelLong: 'Tajik (KOI8-T)', labelShort: 'KOI8-T', order: 44 }, gb2312: { labelLong: 'Simplified Chinese (GB 2312)', labelShort: 'GB 2312', order: 45 }, cp865: { labelLong: 'Nordic DOS (CP 865)', labelShort: 'CP 865', order: 46 }, cp850: { labelLong: 'Western European DOS (CP 850)', labelShort: 'CP 850', order: 47 } };
{ chunks.push(chunk); }
conditional_block
textfiles.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEncodingSupport, ConfirmResult, IRevertOptions, IModeSupport } from 'vs/workbench/common/editor'; import { IBaseStatWithMetadata, IFileStatWithMetadata, IReadFileOptions, IWriteFileOptions, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export interface ITextFileService extends IDisposable { _serviceBrand: ServiceIdentifier<any>; readonly onWillMove: Event<IWillMoveEvent>; readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>; readonly onFilesAssociationChange: Event<void>; readonly isHotExitEnabled: boolean; /** * Access to the manager of text file editor models providing further methods to work with them. */ readonly models: ITextFileEditorModelManager; /** * Helper to determine encoding for resources. */ readonly encoding: IResourceEncodings; /** * A resource is dirty if it has unsaved changes or is an untitled file not yet saved. * * @param resource the resource to check for being dirty. If it is not specified, will check for * all dirty resources. */ isDirty(resource?: URI): boolean; /** * Returns all resources that are currently dirty matching the provided resources or all dirty resources. * * @param resources the resources to check for being dirty. If it is not specified, will check for * all dirty resources. */ getDirty(resources?: URI[]): URI[]; /** * Saves the resource. * * @param resource the resource to save * @param options optional save options * @return true if the resource was saved. */ save(resource: URI, options?: ISaveOptions): Promise<boolean>; /** * Saves the provided resource asking the user for a file name or using the provided one. * * @param resource the resource to save as. * @param targetResource the optional target to save to. * @param options optional save options * @return Path of the saved resource. */ saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined>; /** * Saves the set of resources and returns a promise with the operation result. * * @param resources can be null to save all. * @param includeUntitled to save all resources and optionally exclude untitled ones. */ saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>; saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>; /** * Reverts the provided resource. * * @param resource the resource of the file to revert. * @param force to force revert even when the file is not dirty */ revert(resource: URI, options?: IRevertOptions): Promise<boolean>; /** * Reverts all the provided resources and returns a promise with the operation result. */ revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult>; /** * Create a file. If the file exists it will be overwritten with the contents if * the options enable to overwrite. */ create(resource: URI, contents?: string | ITextSnapshot, options?: { overwrite?: boolean }): Promise<IFileStatWithMetadata>; /** * Read the contents of a file identified by the resource. */ read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>; /** * Read the contents of a file identified by the resource as stream. */ readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>; /** * Update a file with given contents. */ write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>; /** * Delete a file. If the file is dirty, it will get reverted and then deleted from disk. */ delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void>; /** * Move a file. If the file is dirty, its contents will be preserved and restored. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Brings up the confirm dialog to either save, don't save or cancel. * * @param resources the resources of the files to ask for confirmation or null if * confirming for all dirty resources. */ confirmSave(resources?: URI[]): Promise<ConfirmResult>; /** * Convenient fast access to the current auto save mode. */ getAutoSaveMode(): AutoSaveMode; /** * Convenient fast access to the raw configured auto save settings. */ getAutoSaveConfiguration(): IAutoSaveConfiguration; } export interface IReadTextFileOptions extends IReadFileOptions { /** * The optional acceptTextOnly parameter allows to fail this request early if the file * contents are not textual. */ acceptTextOnly?: boolean; /** * The optional encoding parameter allows to specify the desired encoding when resolving * the contents of the file. */ encoding?: string; /** * The optional guessEncoding parameter allows to guess encoding from content of the file. */ autoGuessEncoding?: boolean; } export interface IWriteTextFileOptions extends IWriteFileOptions { /** * The encoding to use when updating a file. */ encoding?: string; /** * If set to true, will enforce the selected encoding and not perform any detection using BOMs. */ overwriteEncoding?: boolean; /** * Whether to overwrite a file even if it is readonly. */ overwriteReadonly?: boolean; /** * Wether to write to the file as elevated (admin) user. When setting this option a prompt will * ask the user to authenticate as super user. */ writeElevated?: boolean; } export const enum TextFileOperationResult { FILE_IS_BINARY } export class TextFileOperationError extends FileOperationError { constructor(message: string, public textFileOperationResult: TextFileOperationResult, public options?: IReadTextFileOptions & IWriteTextFileOptions) { super(message, FileOperationResult.FILE_OTHER_ERROR); } static isTextFileOperationError(obj: unknown): obj is TextFileOperationError { return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult); } } export interface IResourceEncodings { getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding; } export interface IResourceEncoding { encoding: string; hasBOM: boolean; } /** * The save error handler can be installed on the text file editor model to install code that executes when save errors occur. */ export interface ISaveErrorHandler { /** * Called whenever a save fails. */ onSaveError(error: Error, model: ITextFileEditorModel): void; } export interface ISaveParticipant { /** * Participate in a save of a model. Allows to change the model before it is being saved to disk. */ participate(model: IResolvedTextFileEditorModel, env: { reason: SaveReason }): Promise<void>; } /** * States the text file editor model can be in. */ export const enum ModelState { /** * A model is saved. */ SAVED, /** * A model is dirty. */ DIRTY, /** * A model is transitioning from dirty to saved. */ PENDING_SAVE, /** * A model is in conflict mode when changes cannot be saved because the * underlying file has changed. Models in conflict mode are always dirty. */ CONFLICT, /** * A model is in orphan state when the underlying file has been deleted. */ ORPHAN, /** * Any error that happens during a save that is not causing the CONFLICT state. * Models in error mode are always diry. */ ERROR } export const enum StateChange { DIRTY, SAVING, SAVE_ERROR, SAVED, REVERTED, ENCODING, CONTENT_CHANGE, ORPHANED_CHANGE } export class TextFileModelChangeEvent { private _resource: URI; constructor(model: ITextFileEditorModel, private _kind: StateChange) { this._resource = model.getResource(); } get resource(): URI { return this._resource; } get kind(): StateChange { return this._kind; } } export const AutoSaveContext = new RawContextKey<string>('config.files.autoSave', undefined); export interface ITextFileOperationResult { results: IResult[]; } export interface IResult { source: URI; target?: URI; success?: boolean; } export interface IAutoSaveConfiguration { autoSaveDelay?: number; autoSaveFocusChange: boolean; autoSaveApplicationChange: boolean; } export const enum AutoSaveMode { OFF, AFTER_SHORT_DELAY, AFTER_LONG_DELAY, ON_FOCUS_CHANGE, ON_WINDOW_CHANGE } export const enum SaveReason { EXPLICIT = 1, AUTO = 2, FOCUS_CHANGE = 3, WINDOW_CHANGE = 4 } export const enum LoadReason { EDITOR = 1, REFERENCE = 2, OTHER = 3 } interface IBaseTextFileContent extends IBaseStatWithMetadata { /** * The encoding of the content if known. */ encoding: string; } export interface ITextFileContent extends IBaseTextFileContent { /** * The content of a text file. */ value: string; } export interface ITextFileStreamContent extends IBaseTextFileContent { /** * The line grouped content of a text file. */ value: ITextBufferFactory; } export interface IModelLoadOrCreateOptions { /** * Context why the model is being loaded or created. */ reason?: LoadReason; /** * The language mode to use for the model text content. */ mode?: string; /** * The encoding to use when resolving the model text content. */ encoding?: string; /** * If the model was already loaded before, allows to trigger * a reload of it to fetch the latest contents: * - async: loadOrCreate() will return immediately and trigger * a reload that will run in the background. * - sync: loadOrCreate() will only return resolved when the * model has finished reloading. */ reload?: { async: boolean }; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; } export interface ITextFileEditorModelManager { readonly onModelDisposed: Event<URI>; readonly onModelContentChanged: Event<TextFileModelChangeEvent>; readonly onModelEncodingChanged: Event<TextFileModelChangeEvent>; readonly onModelDirty: Event<TextFileModelChangeEvent>; readonly onModelSaveError: Event<TextFileModelChangeEvent>; readonly onModelSaved: Event<TextFileModelChangeEvent>; readonly onModelReverted: Event<TextFileModelChangeEvent>; readonly onModelOrphanedChanged: Event<TextFileModelChangeEvent>; readonly onModelsDirty: Event<TextFileModelChangeEvent[]>; readonly onModelsSaveError: Event<TextFileModelChangeEvent[]>; readonly onModelsSaved: Event<TextFileModelChangeEvent[]>; readonly onModelsReverted: Event<TextFileModelChangeEvent[]>; get(resource: URI): ITextFileEditorModel | undefined; getAll(resource?: URI): ITextFileEditorModel[]; loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): Promise<ITextFileEditorModel>; disposeModel(model: ITextFileEditorModel): void; } export interface ISaveOptions { force?: boolean; reason?: SaveReason; overwriteReadonly?: boolean; overwriteEncoding?: boolean; skipSaveParticipants?: boolean; writeElevated?: boolean; availableFileSystems?: string[]; } export interface ILoadOptions { /** * Go to disk bypassing any cache of the model if any. */ forceReadFromDisk?: boolean; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; /** * Context why the model is being loaded. */ reason?: LoadReason; } export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport { readonly onDidContentChange: Event<StateChange>; readonly onDidStateChange: Event<StateChange>; getResource(): URI; hasState(state: ModelState): boolean; updatePreferredEncoding(encoding: string): void; save(options?: ISaveOptions): Promise<void>; load(options?: ILoadOptions): Promise<ITextFileEditorModel>; revert(soft?: boolean): Promise<void>; backup(target?: URI): Promise<void>; hasBackup(): boolean; isDirty(): boolean; isResolved(): this is IResolvedTextFileEditorModel; isDisposed(): boolean; } export interface IResolvedTextFileEditorModel extends ITextFileEditorModel { readonly textEditorModel: ITextModel; createSnapshot(): ITextSnapshot; } export interface IWillMoveEvent { oldResource: URI; newResource: URI; waitUntil(p: Promise<unknown>): void; } /** * Helper method to convert a snapshot into its full string form. */ export function snapshotToString(snapshot: ITextSnapshot): string { const chunks: string[] = []; let chunk: string | null; while (typeof (chunk = snapshot.read()) === 'string') { chunks.push(chunk); } return chunks.join(''); } export function stringToSnapshot(value: string): ITextSnapshot { let done = false; return { read(): string | null { if (!done) { done = true; return value; } return null; } }; } export class TextSnapshotReadable implements VSBufferReadable { private preambleHandled: boolean; constructor(private snapshot: ITextSnapshot, private preamble?: string) { } read(): VSBuffer | null { let value = this.snapshot.read(); // Handle preamble if provided if (!this.preambleHandled) { this.preambleHandled = true; if (typeof this.preamble === 'string') { if (typeof value === 'string') { value = this.preamble + value; } else { value = this.preamble; } } } if (typeof value === 'string') { return VSBuffer.fromString(value); } return null; } } export function toBufferOrReadable(value: string): VSBuffer; export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined { if (typeof value === 'undefined') { return undefined; } if (typeof value === 'string') { return VSBuffer.fromString(value); } return new TextSnapshotReadable(value); } export const SUPPORTED_ENCODINGS: { [encoding: string]: { labelLong: string; labelShort: string; order: number; encodeOnly?: boolean; alias?: string } } = { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' }, utf8bom: { labelLong: 'UTF-8 with BOM', labelShort: 'UTF-8 with BOM', encodeOnly: true, order: 2, alias: 'utf8' }, utf16le: { labelLong: 'UTF-16 LE', labelShort: 'UTF-16 LE', order: 3 }, utf16be: { labelLong: 'UTF-16 BE', labelShort: 'UTF-16 BE', order: 4 }, windows1252: { labelLong: 'Western (Windows 1252)', labelShort: 'Windows 1252', order: 5 }, iso88591: { labelLong: 'Western (ISO 8859-1)', labelShort: 'ISO 8859-1', order: 6 }, iso88593: { labelLong: 'Western (ISO 8859-3)', labelShort: 'ISO 8859-3', order: 7 }, iso885915: { labelLong: 'Western (ISO 8859-15)', labelShort: 'ISO 8859-15', order: 8 }, macroman: { labelLong: 'Western (Mac Roman)', labelShort: 'Mac Roman', order: 9 }, cp437: { labelLong: 'DOS (CP 437)', labelShort: 'CP437', order: 10 }, windows1256: { labelLong: 'Arabic (Windows 1256)', labelShort: 'Windows 1256', order: 11 }, iso88596: { labelLong: 'Arabic (ISO 8859-6)', labelShort: 'ISO 8859-6', order: 12 }, windows1257: { labelLong: 'Baltic (Windows 1257)', labelShort: 'Windows 1257', order: 13 }, iso88594: { labelLong: 'Baltic (ISO 8859-4)', labelShort: 'ISO 8859-4', order: 14 }, iso885914: { labelLong: 'Celtic (ISO 8859-14)', labelShort: 'ISO 8859-14', order: 15 }, windows1250: { labelLong: 'Central European (Windows 1250)', labelShort: 'Windows 1250', order: 16 }, iso88592: { labelLong: 'Central European (ISO 8859-2)', labelShort: 'ISO 8859-2', order: 17 }, cp852: { labelLong: 'Central European (CP 852)', labelShort: 'CP 852', order: 18 }, windows1251: { labelLong: 'Cyrillic (Windows 1251)', labelShort: 'Windows 1251', order: 19 }, cp866: { labelLong: 'Cyrillic (CP 866)', labelShort: 'CP 866', order: 20 }, iso88595: { labelLong: 'Cyrillic (ISO 8859-5)', labelShort: 'ISO 8859-5', order: 21 }, koi8r: { labelLong: 'Cyrillic (KOI8-R)', labelShort: 'KOI8-R', order: 22 }, koi8u: { labelLong: 'Cyrillic (KOI8-U)', labelShort: 'KOI8-U', order: 23 }, iso885913: { labelLong: 'Estonian (ISO 8859-13)', labelShort: 'ISO 8859-13', order: 24 }, windows1253: { labelLong: 'Greek (Windows 1253)', labelShort: 'Windows 1253', order: 25 }, iso88597: { labelLong: 'Greek (ISO 8859-7)', labelShort: 'ISO 8859-7', order: 26 }, windows1255: { labelLong: 'Hebrew (Windows 1255)', labelShort: 'Windows 1255', order: 27 }, iso88598: { labelLong: 'Hebrew (ISO 8859-8)', labelShort: 'ISO 8859-8', order: 28 }, iso885910: { labelLong: 'Nordic (ISO 8859-10)', labelShort: 'ISO 8859-10', order: 29 }, iso885916: { labelLong: 'Romanian (ISO 8859-16)', labelShort: 'ISO 8859-16', order: 30 }, windows1254: { labelLong: 'Turkish (Windows 1254)', labelShort: 'Windows 1254', order: 31 }, iso88599: { labelLong: 'Turkish (ISO 8859-9)', labelShort: 'ISO 8859-9', order: 32 }, windows1258: { labelLong: 'Vietnamese (Windows 1258)', labelShort: 'Windows 1258', order: 33 }, gbk: { labelLong: 'Simplified Chinese (GBK)', labelShort: 'GBK', order: 34 }, gb18030: { labelLong: 'Simplified Chinese (GB18030)', labelShort: 'GB18030', order: 35 }, cp950: { labelLong: 'Traditional Chinese (Big5)', labelShort: 'Big5', order: 36 }, big5hkscs: { labelLong: 'Traditional Chinese (Big5-HKSCS)', labelShort: 'Big5-HKSCS', order: 37 }, shiftjis: { labelLong: 'Japanese (Shift JIS)', labelShort: 'Shift JIS', order: 38 }, eucjp: { labelLong: 'Japanese (EUC-JP)', labelShort: 'EUC-JP', order: 39 }, euckr: { labelLong: 'Korean (EUC-KR)', labelShort: 'EUC-KR', order: 40 }, windows874: { labelLong: 'Thai (Windows 874)', labelShort: 'Windows 874', order: 41 }, iso885911: { labelLong: 'Latin/Thai (ISO 8859-11)', labelShort: 'ISO 8859-11', order: 42 }, koi8ru: { labelLong: 'Cyrillic (KOI8-RU)', labelShort: 'KOI8-RU', order: 43 }, koi8t: { labelLong: 'Tajik (KOI8-T)', labelShort: 'KOI8-T', order: 44 }, gb2312: { labelLong: 'Simplified Chinese (GB 2312)', labelShort: 'GB 2312', order: 45 }, cp865: { labelLong: 'Nordic DOS (CP 865)', labelShort: 'CP 865', order: 46 }, cp850: { labelLong: 'Western European DOS (CP 850)', labelShort: 'CP 850', order: 47 } };
import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer'; import { isUndefinedOrNull } from 'vs/base/common/types'; export const ITextFileService = createDecorator<ITextFileService>('textFileService');
random_line_split
chris_app.js
'use strict'; var key_arr = document.getElementsByClassName('key'); var border = document.getElementById('key-container'); var keycode_letters = { key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys key_sounds: ['sounds/lastsound.mp3', 'sounds/sound2.mp3', 'sounds/sound3.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound7.mp3', 'sounds/sound8.mp3', 'sounds/sound9.mp3' , 'sounds/last_sound2.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound10.mp3'],//array of file names for sounds }; //var rotate = document.getElementsByClassName('record-div'); //rotate[i].classList.toggle('spinning-div'); //adds a listener to the page that records keycodes and plays corresponding sounds + vids window.addEventListener('keydown', keyHandler); window.addEventListener('keyup', upHandler); function keyHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { var audio = document.getElementById(event.keyCode.toString()); var filepath = keycode_letters.key_sounds[i]; audio.src = filepath; audio.play(); key_arr[i].classList.toggle('keythree'); border.style.boxShadow = '2px 2px 5px 5px white'; } } } }; function upHandler (event)
//toggle method, class list
{ if(keycode_letters.key_nums.includes(event.keyCode)){ border.style.boxShadow = 'none'; for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { key_arr[i].classList.toggle('keythree'); } } } }
identifier_body
chris_app.js
'use strict'; var key_arr = document.getElementsByClassName('key'); var border = document.getElementById('key-container'); var keycode_letters = { key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys key_sounds: ['sounds/lastsound.mp3', 'sounds/sound2.mp3', 'sounds/sound3.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound7.mp3', 'sounds/sound8.mp3', 'sounds/sound9.mp3' , 'sounds/last_sound2.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound10.mp3'],//array of file names for sounds }; //var rotate = document.getElementsByClassName('record-div'); //rotate[i].classList.toggle('spinning-div'); //adds a listener to the page that records keycodes and plays corresponding sounds + vids window.addEventListener('keydown', keyHandler); window.addEventListener('keyup', upHandler); function
(event) { if(keycode_letters.key_nums.includes(event.keyCode)){ for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { var audio = document.getElementById(event.keyCode.toString()); var filepath = keycode_letters.key_sounds[i]; audio.src = filepath; audio.play(); key_arr[i].classList.toggle('keythree'); border.style.boxShadow = '2px 2px 5px 5px white'; } } } }; function upHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ border.style.boxShadow = 'none'; for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { key_arr[i].classList.toggle('keythree'); } } } } //toggle method, class list
keyHandler
identifier_name
chris_app.js
'use strict'; var key_arr = document.getElementsByClassName('key'); var border = document.getElementById('key-container'); var keycode_letters = { key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys key_sounds: ['sounds/lastsound.mp3', 'sounds/sound2.mp3', 'sounds/sound3.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound7.mp3', 'sounds/sound8.mp3', 'sounds/sound9.mp3' , 'sounds/last_sound2.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound10.mp3'],//array of file names for sounds }; //var rotate = document.getElementsByClassName('record-div'); //rotate[i].classList.toggle('spinning-div'); //adds a listener to the page that records keycodes and plays corresponding sounds + vids window.addEventListener('keydown', keyHandler); window.addEventListener('keyup', upHandler); function keyHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { var audio = document.getElementById(event.keyCode.toString()); var filepath = keycode_letters.key_sounds[i]; audio.src = filepath; audio.play(); key_arr[i].classList.toggle('keythree'); border.style.boxShadow = '2px 2px 5px 5px white'; } } } };
for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { key_arr[i].classList.toggle('keythree'); } } } } //toggle method, class list
function upHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ border.style.boxShadow = 'none';
random_line_split
chris_app.js
'use strict'; var key_arr = document.getElementsByClassName('key'); var border = document.getElementById('key-container'); var keycode_letters = { key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys key_sounds: ['sounds/lastsound.mp3', 'sounds/sound2.mp3', 'sounds/sound3.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound7.mp3', 'sounds/sound8.mp3', 'sounds/sound9.mp3' , 'sounds/last_sound2.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound10.mp3'],//array of file names for sounds }; //var rotate = document.getElementsByClassName('record-div'); //rotate[i].classList.toggle('spinning-div'); //adds a listener to the page that records keycodes and plays corresponding sounds + vids window.addEventListener('keydown', keyHandler); window.addEventListener('keyup', upHandler); function keyHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i])
} } }; function upHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ border.style.boxShadow = 'none'; for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { key_arr[i].classList.toggle('keythree'); } } } } //toggle method, class list
{ var audio = document.getElementById(event.keyCode.toString()); var filepath = keycode_letters.key_sounds[i]; audio.src = filepath; audio.play(); key_arr[i].classList.toggle('keythree'); border.style.boxShadow = '2px 2px 5px 5px white'; }
conditional_block
release.py
#!/usr/bin/env python from __future__ import print_function import re import ast import subprocess import sys from optparse import OptionParser DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def skip_step(): """ Asks for user's response whether to run a step. Default is yes. :return: boolean """ global CONFIRM_STEPS if CONFIRM_STEPS: choice = raw_input("--- Confirm step? (y/N) [y] ") if choice.lower() == 'n': return True return False def run_step(*args): """ Prints out the command and asks if it should be run. If yes (default), runs it. :param args: list of strings (command and args) """ global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN: print('--- Pretending to run...') else:
def version(version_file): _version_re = re.compile(r'__version__\s+=\s+(.*)') with open(version_file, 'rb') as f: ver = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) return ver def commit_for_release(version_file, ver): run_step('git', 'reset') run_step('git', 'add', version_file) run_step('git', 'commit', '--message', 'Releasing version %s' % ver) def create_git_tag(tag_name): run_step('git', 'tag', '-s', '-m', tag_name, tag_name) def create_source_tarball(): run_step('python', 'setup.py', 'sdist') def upload_source_tarball(): run_step('python', 'setup.py', 'sdist', 'upload') def push_to_github(): run_step('git', 'push', 'origin', 'master') def push_tags_to_github(): run_step('git', 'push', '--tags', 'origin') if __name__ == '__main__': if DEBUG: subprocess.check_output = lambda x: x ver = version('pgcli/__init__.py') print('Releasing Version:', ver) parser = OptionParser() parser.add_option( "-c", "--confirm-steps", action="store_true", dest="confirm_steps", default=False, help=("Confirm every step. If the step is not " "confirmed, it will be skipped.") ) parser.add_option( "-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Print out, but not actually run any steps." ) popts, pargs = parser.parse_args() CONFIRM_STEPS = popts.confirm_steps DRY_RUN = popts.dry_run choice = raw_input('Are you sure? (y/N) [n] ') if choice.lower() != 'y': sys.exit(1) commit_for_release('pgcli/__init__.py', ver) create_git_tag('v%s' % ver) create_source_tarball() push_to_github() push_tags_to_github() upload_source_tarball()
subprocess.check_output(cmd)
conditional_block
release.py
#!/usr/bin/env python from __future__ import print_function import re import ast import subprocess import sys from optparse import OptionParser DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def
(): """ Asks for user's response whether to run a step. Default is yes. :return: boolean """ global CONFIRM_STEPS if CONFIRM_STEPS: choice = raw_input("--- Confirm step? (y/N) [y] ") if choice.lower() == 'n': return True return False def run_step(*args): """ Prints out the command and asks if it should be run. If yes (default), runs it. :param args: list of strings (command and args) """ global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN: print('--- Pretending to run...') else: subprocess.check_output(cmd) def version(version_file): _version_re = re.compile(r'__version__\s+=\s+(.*)') with open(version_file, 'rb') as f: ver = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) return ver def commit_for_release(version_file, ver): run_step('git', 'reset') run_step('git', 'add', version_file) run_step('git', 'commit', '--message', 'Releasing version %s' % ver) def create_git_tag(tag_name): run_step('git', 'tag', '-s', '-m', tag_name, tag_name) def create_source_tarball(): run_step('python', 'setup.py', 'sdist') def upload_source_tarball(): run_step('python', 'setup.py', 'sdist', 'upload') def push_to_github(): run_step('git', 'push', 'origin', 'master') def push_tags_to_github(): run_step('git', 'push', '--tags', 'origin') if __name__ == '__main__': if DEBUG: subprocess.check_output = lambda x: x ver = version('pgcli/__init__.py') print('Releasing Version:', ver) parser = OptionParser() parser.add_option( "-c", "--confirm-steps", action="store_true", dest="confirm_steps", default=False, help=("Confirm every step. If the step is not " "confirmed, it will be skipped.") ) parser.add_option( "-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Print out, but not actually run any steps." ) popts, pargs = parser.parse_args() CONFIRM_STEPS = popts.confirm_steps DRY_RUN = popts.dry_run choice = raw_input('Are you sure? (y/N) [n] ') if choice.lower() != 'y': sys.exit(1) commit_for_release('pgcli/__init__.py', ver) create_git_tag('v%s' % ver) create_source_tarball() push_to_github() push_tags_to_github() upload_source_tarball()
skip_step
identifier_name
release.py
#!/usr/bin/env python from __future__ import print_function import re import ast import subprocess import sys from optparse import OptionParser DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def skip_step(): """ Asks for user's response whether to run a step. Default is yes. :return: boolean """ global CONFIRM_STEPS if CONFIRM_STEPS:
return True return False def run_step(*args): """ Prints out the command and asks if it should be run. If yes (default), runs it. :param args: list of strings (command and args) """ global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN: print('--- Pretending to run...') else: subprocess.check_output(cmd) def version(version_file): _version_re = re.compile(r'__version__\s+=\s+(.*)') with open(version_file, 'rb') as f: ver = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) return ver def commit_for_release(version_file, ver): run_step('git', 'reset') run_step('git', 'add', version_file) run_step('git', 'commit', '--message', 'Releasing version %s' % ver) def create_git_tag(tag_name): run_step('git', 'tag', '-s', '-m', tag_name, tag_name) def create_source_tarball(): run_step('python', 'setup.py', 'sdist') def upload_source_tarball(): run_step('python', 'setup.py', 'sdist', 'upload') def push_to_github(): run_step('git', 'push', 'origin', 'master') def push_tags_to_github(): run_step('git', 'push', '--tags', 'origin') if __name__ == '__main__': if DEBUG: subprocess.check_output = lambda x: x ver = version('pgcli/__init__.py') print('Releasing Version:', ver) parser = OptionParser() parser.add_option( "-c", "--confirm-steps", action="store_true", dest="confirm_steps", default=False, help=("Confirm every step. If the step is not " "confirmed, it will be skipped.") ) parser.add_option( "-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Print out, but not actually run any steps." ) popts, pargs = parser.parse_args() CONFIRM_STEPS = popts.confirm_steps DRY_RUN = popts.dry_run choice = raw_input('Are you sure? (y/N) [n] ') if choice.lower() != 'y': sys.exit(1) commit_for_release('pgcli/__init__.py', ver) create_git_tag('v%s' % ver) create_source_tarball() push_to_github() push_tags_to_github() upload_source_tarball()
choice = raw_input("--- Confirm step? (y/N) [y] ") if choice.lower() == 'n':
random_line_split
release.py
#!/usr/bin/env python from __future__ import print_function import re import ast import subprocess import sys from optparse import OptionParser DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def skip_step(): """ Asks for user's response whether to run a step. Default is yes. :return: boolean """ global CONFIRM_STEPS if CONFIRM_STEPS: choice = raw_input("--- Confirm step? (y/N) [y] ") if choice.lower() == 'n': return True return False def run_step(*args): """ Prints out the command and asks if it should be run. If yes (default), runs it. :param args: list of strings (command and args) """ global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN: print('--- Pretending to run...') else: subprocess.check_output(cmd) def version(version_file): _version_re = re.compile(r'__version__\s+=\s+(.*)') with open(version_file, 'rb') as f: ver = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) return ver def commit_for_release(version_file, ver):
def create_git_tag(tag_name): run_step('git', 'tag', '-s', '-m', tag_name, tag_name) def create_source_tarball(): run_step('python', 'setup.py', 'sdist') def upload_source_tarball(): run_step('python', 'setup.py', 'sdist', 'upload') def push_to_github(): run_step('git', 'push', 'origin', 'master') def push_tags_to_github(): run_step('git', 'push', '--tags', 'origin') if __name__ == '__main__': if DEBUG: subprocess.check_output = lambda x: x ver = version('pgcli/__init__.py') print('Releasing Version:', ver) parser = OptionParser() parser.add_option( "-c", "--confirm-steps", action="store_true", dest="confirm_steps", default=False, help=("Confirm every step. If the step is not " "confirmed, it will be skipped.") ) parser.add_option( "-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Print out, but not actually run any steps." ) popts, pargs = parser.parse_args() CONFIRM_STEPS = popts.confirm_steps DRY_RUN = popts.dry_run choice = raw_input('Are you sure? (y/N) [n] ') if choice.lower() != 'y': sys.exit(1) commit_for_release('pgcli/__init__.py', ver) create_git_tag('v%s' % ver) create_source_tarball() push_to_github() push_tags_to_github() upload_source_tarball()
run_step('git', 'reset') run_step('git', 'add', version_file) run_step('git', 'commit', '--message', 'Releasing version %s' % ver)
identifier_body
log.js
/** * Logger configuration * * Configure the log level for your app, as well as the transport * (Underneath the covers, Sails uses Winston for logging, which * allows for some pretty neat custom transports/adapters for log messages) * * For more information on the Sails logger, check out: * http://sailsjs.org/#documentation
*/ module.exports = { // Valid `level` configs: // i.e. the minimum log level to capture with sails.log.*() // // 'error' : Display calls to `.error()` // 'warn' : Display calls from `.error()` to `.warn()` // 'debug' : Display calls from `.error()`, `.warn()` to `.debug()` // 'info' : Display calls from `.error()`, `.warn()`, `.debug()` to `.info()` // 'verbose': Display calls from `.error()`, `.warn()`, `.debug()`, `.info()` to `.verbose()` // log: { level: 'info' } };
random_line_split
ThemeSwitcher.tsx
import React, { useContext, useState } from 'react'; import { useTranslation } from 'react-i18next'; import Toggle from '../../Toggle'; import ThemeContext from '../ThemeContext'; import { dark, light } from '../../../themes'; const ThemeSwitcher = () => { const { switchTheme, theme } = useContext(ThemeContext); const [hasDarkMode, setDarkMode] = useState(false); const { t } = useTranslation();
setDarkMode(theme === dark); }, [theme]); const toggle = () => { if (switchTheme) { switchTheme(hasDarkMode ? light : dark); } }; return ( <Toggle icon={hasDarkMode ? 'talend-eye-slash' : 'talend-eye'} onChange={toggle}> {t('THEME_TOGGLE_DARK_MODE', 'Toggle dark mode')} </Toggle> ); }; export default ThemeSwitcher;
React.useEffect(() => {
random_line_split
ThemeSwitcher.tsx
import React, { useContext, useState } from 'react'; import { useTranslation } from 'react-i18next'; import Toggle from '../../Toggle'; import ThemeContext from '../ThemeContext'; import { dark, light } from '../../../themes'; const ThemeSwitcher = () => { const { switchTheme, theme } = useContext(ThemeContext); const [hasDarkMode, setDarkMode] = useState(false); const { t } = useTranslation(); React.useEffect(() => { setDarkMode(theme === dark); }, [theme]); const toggle = () => { if (switchTheme)
}; return ( <Toggle icon={hasDarkMode ? 'talend-eye-slash' : 'talend-eye'} onChange={toggle}> {t('THEME_TOGGLE_DARK_MODE', 'Toggle dark mode')} </Toggle> ); }; export default ThemeSwitcher;
{ switchTheme(hasDarkMode ? light : dark); }
conditional_block
convex_try_new3d.rs
extern crate nalgebra as na; use na::Point3; use ncollide3d::shape::ConvexHull; fn main()
{ let points = vec![ Point3::new(0.0f32, 0.0, 1.0), Point3::new(0.0, 0.0, -1.0), Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, -1.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(-1.0, 0.0, 0.0), ]; let indices = vec![ 0, 4, 2, 0, 3, 4, 5, 0, 2, 5, 3, 0, 1, 5, 2, 1, 3, 5, 4, 1, 2, 4, 3, 1, ]; let convex = ConvexHull::try_new(points, &indices).expect("Invalid convex shape."); convex.check_geometry(); }
identifier_body
convex_try_new3d.rs
extern crate nalgebra as na; use na::Point3; use ncollide3d::shape::ConvexHull; fn
() { let points = vec![ Point3::new(0.0f32, 0.0, 1.0), Point3::new(0.0, 0.0, -1.0), Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, -1.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(-1.0, 0.0, 0.0), ]; let indices = vec![ 0, 4, 2, 0, 3, 4, 5, 0, 2, 5, 3, 0, 1, 5, 2, 1, 3, 5, 4, 1, 2, 4, 3, 1, ]; let convex = ConvexHull::try_new(points, &indices).expect("Invalid convex shape."); convex.check_geometry(); }
main
identifier_name
convex_try_new3d.rs
extern crate nalgebra as na; use na::Point3; use ncollide3d::shape::ConvexHull; fn main() { let points = vec![ Point3::new(0.0f32, 0.0, 1.0), Point3::new(0.0, 0.0, -1.0), Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, -1.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(-1.0, 0.0, 0.0), ]; let indices = vec![ 0, 4, 2, 0, 3, 4, 5, 0, 2, 5, 3, 0, 1, 5, 2, 1, 3, 5, 4, 1, 2, 4, 3, 1,
}
]; let convex = ConvexHull::try_new(points, &indices).expect("Invalid convex shape."); convex.check_geometry();
random_line_split
product.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # Copyright 2016 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api, _ from openerp.exceptions import ValidationError class ProductProduct(models.Model): _inherit = 'product.product' # Link rental service -> rented HW product rented_product_id = fields.Many2one( 'product.product', string='Related Rented Product', domain=[('type', 'in', ('product', 'consu'))]) # Link rented HW product -> rental service rental_service_ids = fields.One2many( 'product.product', 'rented_product_id', string='Related Rental Services') @api.one @api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id') def
(self): if self.rented_product_id and self.type != 'service': raise ValidationError(_( "The rental product '%s' must be of type 'Service'.") % self.name) if self.rented_product_id and not self.must_have_dates: raise ValidationError(_( "The rental product '%s' must have the option " "'Must Have Start and End Dates' checked.") % self.name) # In the future, we would like to support all time UoMs # but it is more complex and requires additionnal developments day_uom = self.env.ref('product.product_uom_day') if self.rented_product_id and self.uom_id != day_uom: raise ValidationError(_( "The unit of measure of the rental product '%s' must " "be 'Day'.") % self.name) @api.multi def _need_procurement(self): # Missing self.ensure_one() in the native code ! res = super(ProductProduct, self)._need_procurement() if not res: for product in self: if product.type == 'service' and product.rented_product_id: return True # TODO find a replacement for soline.rental_type == 'new_rental') return res
_check_rental
identifier_name
product.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # Copyright 2016 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api, _ from openerp.exceptions import ValidationError class ProductProduct(models.Model): _inherit = 'product.product' # Link rental service -> rented HW product rented_product_id = fields.Many2one( 'product.product', string='Related Rented Product', domain=[('type', 'in', ('product', 'consu'))]) # Link rented HW product -> rental service rental_service_ids = fields.One2many( 'product.product', 'rented_product_id', string='Related Rental Services') @api.one @api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id') def _check_rental(self): if self.rented_product_id and self.type != 'service': raise ValidationError(_( "The rental product '%s' must be of type 'Service'.") % self.name) if self.rented_product_id and not self.must_have_dates: raise ValidationError(_( "The rental product '%s' must have the option " "'Must Have Start and End Dates' checked.") % self.name) # In the future, we would like to support all time UoMs # but it is more complex and requires additionnal developments day_uom = self.env.ref('product.product_uom_day') if self.rented_product_id and self.uom_id != day_uom: raise ValidationError(_( "The unit of measure of the rental product '%s' must " "be 'Day'.") % self.name) @api.multi def _need_procurement(self): # Missing self.ensure_one() in the native code !
res = super(ProductProduct, self)._need_procurement() if not res: for product in self: if product.type == 'service' and product.rented_product_id: return True # TODO find a replacement for soline.rental_type == 'new_rental') return res
identifier_body
product.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # Copyright 2016 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api, _ from openerp.exceptions import ValidationError class ProductProduct(models.Model): _inherit = 'product.product' # Link rental service -> rented HW product
rented_product_id = fields.Many2one( 'product.product', string='Related Rented Product', domain=[('type', 'in', ('product', 'consu'))]) # Link rented HW product -> rental service rental_service_ids = fields.One2many( 'product.product', 'rented_product_id', string='Related Rental Services') @api.one @api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id') def _check_rental(self): if self.rented_product_id and self.type != 'service': raise ValidationError(_( "The rental product '%s' must be of type 'Service'.") % self.name) if self.rented_product_id and not self.must_have_dates: raise ValidationError(_( "The rental product '%s' must have the option " "'Must Have Start and End Dates' checked.") % self.name) # In the future, we would like to support all time UoMs # but it is more complex and requires additionnal developments day_uom = self.env.ref('product.product_uom_day') if self.rented_product_id and self.uom_id != day_uom: raise ValidationError(_( "The unit of measure of the rental product '%s' must " "be 'Day'.") % self.name) @api.multi def _need_procurement(self): # Missing self.ensure_one() in the native code ! res = super(ProductProduct, self)._need_procurement() if not res: for product in self: if product.type == 'service' and product.rented_product_id: return True # TODO find a replacement for soline.rental_type == 'new_rental') return res
random_line_split
product.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # Copyright 2016 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api, _ from openerp.exceptions import ValidationError class ProductProduct(models.Model): _inherit = 'product.product' # Link rental service -> rented HW product rented_product_id = fields.Many2one( 'product.product', string='Related Rented Product', domain=[('type', 'in', ('product', 'consu'))]) # Link rented HW product -> rental service rental_service_ids = fields.One2many( 'product.product', 'rented_product_id', string='Related Rental Services') @api.one @api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id') def _check_rental(self): if self.rented_product_id and self.type != 'service': raise ValidationError(_( "The rental product '%s' must be of type 'Service'.") % self.name) if self.rented_product_id and not self.must_have_dates: raise ValidationError(_( "The rental product '%s' must have the option " "'Must Have Start and End Dates' checked.") % self.name) # In the future, we would like to support all time UoMs # but it is more complex and requires additionnal developments day_uom = self.env.ref('product.product_uom_day') if self.rented_product_id and self.uom_id != day_uom: raise ValidationError(_( "The unit of measure of the rental product '%s' must " "be 'Day'.") % self.name) @api.multi def _need_procurement(self): # Missing self.ensure_one() in the native code ! res = super(ProductProduct, self)._need_procurement() if not res:
# TODO find a replacement for soline.rental_type == 'new_rental') return res
for product in self: if product.type == 'service' and product.rented_product_id: return True
conditional_block
status.js
'use strict'; var utils = this.utils || {}; utils.status = (function() { // This constant is essential to resolve what is the path of the CSS file // that defines the animations //var FILE_NAME = 'status'; // How many milliseconds is displayed the status component by default var DISPLAYED_TIME = 2000; // References to the DOMElement(s) that renders the status UI component var section, content; // The numerical ID of the timeout in order to hide UI component var timeoutID; /* * Clears the callback in charge of hiding the component after timeout */ function
() { if (timeoutID === null) { return; } window.clearTimeout(timeoutID); timeoutID = null; } /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms. This * parameter is optional * */ function show(message, duration) { clearHideTimeout(); content.innerHTML = ''; if (typeof message === 'string') { content.textContent = message; } else { try { // Here we should have a DOMFragment content.appendChild(message); } catch(ex) { console.error('DOMException: ' + ex.message); } } section.classList.remove('hidden'); section.classList.add('onviewport'); timeoutID = window.setTimeout(hide, duration || DISPLAYED_TIME); } /* * This function is invoked when some animation is ended */ function animationEnd(evt) { var eventName = 'status-showed'; if (evt.animationName === 'hide') { clearHideTimeout(); section.classList.add('hidden'); eventName = 'status-hidden'; } window.dispatchEvent(new CustomEvent(eventName)); } /* * Hides the status component */ function hide() { section.classList.remove('onviewport'); } /* * Releases memory */ function destroy() { section.removeEventListener('animationend', animationEnd); document.body.removeChild(section); clearHideTimeout(); section = content = null; } /*function getPath() { var path = document.querySelector('[src*="' + FILE_NAME + '.js"]').src; return path.substring(0, path.lastIndexOf('/') + 1); } function addStylesheet() { var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = getPath() + 'status-behavior.css'; document.head.appendChild(link); }*/ function build() { section = document.createElement('section'); //addStylesheet(); section.setAttribute('role', 'status'); section.classList.add('hidden'); content = document.createElement('p'); section.appendChild(content); document.body.appendChild(section); section.addEventListener('animationend', animationEnd); } /* * Initializes the library. Basically it creates the markup: * * <section role="status"> * <p>xxx</p> * </section> */ function initialize() { if (section) { return; } build(); } // Initializing the library if (document.readyState === 'complete') { initialize(); } else { document.addEventListener('DOMContentLoaded', function loaded() { document.removeEventListener('DOMContentLoaded', loaded); initialize(); }); } return { /* * The library is auto-initialized but it is for unit testing purposes */ init: initialize, /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms * */ show: show, /* * Hides the status component */ hide: hide, /* * Releases memory */ destroy: destroy, /* * Sets up the duration in milliseconds that a status is displayed * * @param{int} The time in milliseconds * */ setDuration: function setDuration(time) { DISPLAYED_TIME = time || DISPLAYED_TIME; } }; })();
clearHideTimeout
identifier_name
status.js
'use strict'; var utils = this.utils || {}; utils.status = (function() { // This constant is essential to resolve what is the path of the CSS file // that defines the animations //var FILE_NAME = 'status'; // How many milliseconds is displayed the status component by default var DISPLAYED_TIME = 2000; // References to the DOMElement(s) that renders the status UI component var section, content; // The numerical ID of the timeout in order to hide UI component var timeoutID; /* * Clears the callback in charge of hiding the component after timeout */ function clearHideTimeout() { if (timeoutID === null) { return; } window.clearTimeout(timeoutID); timeoutID = null; } /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms. This * parameter is optional * */ function show(message, duration)
/* * This function is invoked when some animation is ended */ function animationEnd(evt) { var eventName = 'status-showed'; if (evt.animationName === 'hide') { clearHideTimeout(); section.classList.add('hidden'); eventName = 'status-hidden'; } window.dispatchEvent(new CustomEvent(eventName)); } /* * Hides the status component */ function hide() { section.classList.remove('onviewport'); } /* * Releases memory */ function destroy() { section.removeEventListener('animationend', animationEnd); document.body.removeChild(section); clearHideTimeout(); section = content = null; } /*function getPath() { var path = document.querySelector('[src*="' + FILE_NAME + '.js"]').src; return path.substring(0, path.lastIndexOf('/') + 1); } function addStylesheet() { var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = getPath() + 'status-behavior.css'; document.head.appendChild(link); }*/ function build() { section = document.createElement('section'); //addStylesheet(); section.setAttribute('role', 'status'); section.classList.add('hidden'); content = document.createElement('p'); section.appendChild(content); document.body.appendChild(section); section.addEventListener('animationend', animationEnd); } /* * Initializes the library. Basically it creates the markup: * * <section role="status"> * <p>xxx</p> * </section> */ function initialize() { if (section) { return; } build(); } // Initializing the library if (document.readyState === 'complete') { initialize(); } else { document.addEventListener('DOMContentLoaded', function loaded() { document.removeEventListener('DOMContentLoaded', loaded); initialize(); }); } return { /* * The library is auto-initialized but it is for unit testing purposes */ init: initialize, /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms * */ show: show, /* * Hides the status component */ hide: hide, /* * Releases memory */ destroy: destroy, /* * Sets up the duration in milliseconds that a status is displayed * * @param{int} The time in milliseconds * */ setDuration: function setDuration(time) { DISPLAYED_TIME = time || DISPLAYED_TIME; } }; })();
{ clearHideTimeout(); content.innerHTML = ''; if (typeof message === 'string') { content.textContent = message; } else { try { // Here we should have a DOMFragment content.appendChild(message); } catch(ex) { console.error('DOMException: ' + ex.message); } } section.classList.remove('hidden'); section.classList.add('onviewport'); timeoutID = window.setTimeout(hide, duration || DISPLAYED_TIME); }
identifier_body
status.js
'use strict'; var utils = this.utils || {}; utils.status = (function() { // This constant is essential to resolve what is the path of the CSS file // that defines the animations //var FILE_NAME = 'status'; // How many milliseconds is displayed the status component by default var DISPLAYED_TIME = 2000; // References to the DOMElement(s) that renders the status UI component var section, content; // The numerical ID of the timeout in order to hide UI component var timeoutID; /* * Clears the callback in charge of hiding the component after timeout */ function clearHideTimeout() { if (timeoutID === null) { return; } window.clearTimeout(timeoutID); timeoutID = null; } /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms. This * parameter is optional * */ function show(message, duration) { clearHideTimeout(); content.innerHTML = ''; if (typeof message === 'string') { content.textContent = message; } else { try { // Here we should have a DOMFragment content.appendChild(message); } catch(ex) { console.error('DOMException: ' + ex.message); } } section.classList.remove('hidden'); section.classList.add('onviewport'); timeoutID = window.setTimeout(hide, duration || DISPLAYED_TIME); } /* * This function is invoked when some animation is ended */ function animationEnd(evt) { var eventName = 'status-showed'; if (evt.animationName === 'hide') { clearHideTimeout(); section.classList.add('hidden'); eventName = 'status-hidden'; } window.dispatchEvent(new CustomEvent(eventName)); } /* * Hides the status component */ function hide() { section.classList.remove('onviewport'); } /* * Releases memory */ function destroy() { section.removeEventListener('animationend', animationEnd); document.body.removeChild(section); clearHideTimeout(); section = content = null; } /*function getPath() { var path = document.querySelector('[src*="' + FILE_NAME + '.js"]').src; return path.substring(0, path.lastIndexOf('/') + 1); } function addStylesheet() { var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = getPath() + 'status-behavior.css'; document.head.appendChild(link); }*/ function build() { section = document.createElement('section'); //addStylesheet(); section.setAttribute('role', 'status'); section.classList.add('hidden'); content = document.createElement('p'); section.appendChild(content); document.body.appendChild(section); section.addEventListener('animationend', animationEnd); } /* * Initializes the library. Basically it creates the markup: * * <section role="status"> * <p>xxx</p> * </section> */ function initialize() { if (section)
build(); } // Initializing the library if (document.readyState === 'complete') { initialize(); } else { document.addEventListener('DOMContentLoaded', function loaded() { document.removeEventListener('DOMContentLoaded', loaded); initialize(); }); } return { /* * The library is auto-initialized but it is for unit testing purposes */ init: initialize, /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms * */ show: show, /* * Hides the status component */ hide: hide, /* * Releases memory */ destroy: destroy, /* * Sets up the duration in milliseconds that a status is displayed * * @param{int} The time in milliseconds * */ setDuration: function setDuration(time) { DISPLAYED_TIME = time || DISPLAYED_TIME; } }; })();
{ return; }
conditional_block
status.js
'use strict'; var utils = this.utils || {}; utils.status = (function() { // This constant is essential to resolve what is the path of the CSS file // that defines the animations //var FILE_NAME = 'status'; // How many milliseconds is displayed the status component by default var DISPLAYED_TIME = 2000; // References to the DOMElement(s) that renders the status UI component var section, content; // The numerical ID of the timeout in order to hide UI component var timeoutID; /* * Clears the callback in charge of hiding the component after timeout */ function clearHideTimeout() { if (timeoutID === null) { return; } window.clearTimeout(timeoutID); timeoutID = null; } /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms. This * parameter is optional * */ function show(message, duration) { clearHideTimeout(); content.innerHTML = ''; if (typeof message === 'string') { content.textContent = message; } else { try { // Here we should have a DOMFragment content.appendChild(message); } catch(ex) { console.error('DOMException: ' + ex.message); } } section.classList.remove('hidden'); section.classList.add('onviewport'); timeoutID = window.setTimeout(hide, duration || DISPLAYED_TIME); } /* * This function is invoked when some animation is ended */ function animationEnd(evt) { var eventName = 'status-showed'; if (evt.animationName === 'hide') { clearHideTimeout(); section.classList.add('hidden'); eventName = 'status-hidden'; } window.dispatchEvent(new CustomEvent(eventName)); } /* * Hides the status component */ function hide() { section.classList.remove('onviewport'); } /* * Releases memory */ function destroy() { section.removeEventListener('animationend', animationEnd); document.body.removeChild(section); clearHideTimeout(); section = content = null; } /*function getPath() { var path = document.querySelector('[src*="' + FILE_NAME + '.js"]').src; return path.substring(0, path.lastIndexOf('/') + 1); } function addStylesheet() { var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = getPath() + 'status-behavior.css'; document.head.appendChild(link); }*/ function build() { section = document.createElement('section'); //addStylesheet(); section.setAttribute('role', 'status'); section.classList.add('hidden'); content = document.createElement('p'); section.appendChild(content); document.body.appendChild(section); section.addEventListener('animationend', animationEnd); } /* * Initializes the library. Basically it creates the markup: * * <section role="status"> * <p>xxx</p> * </section> */ function initialize() { if (section) { return; } build(); } // Initializing the library if (document.readyState === 'complete') { initialize(); } else { document.addEventListener('DOMContentLoaded', function loaded() { document.removeEventListener('DOMContentLoaded', loaded); initialize(); }); } return { /* * The library is auto-initialized but it is for unit testing purposes */ init: initialize, /* * Shows the status component * * @param{Object} Message. It could be a string or a DOMFragment that * represents the normal and strong strings * * @param{int} It defines the time that the status is displayed in ms * */ show: show, /* * Hides the status component */ hide: hide, /* * Releases memory */ destroy: destroy, /* * Sets up the duration in milliseconds that a status is displayed * * @param{int} The time in milliseconds
*/ setDuration: function setDuration(time) { DISPLAYED_TIME = time || DISPLAYED_TIME; } }; })();
*
random_line_split
release_entry.rs
use hex::*; use regex::Regex; use semver::Version; use std::iter::*; use std::error::{Error}; use url::{Url}; use url::percent_encoding::{percent_decode}; /* Example lines: # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 123 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 34567 full 5% */ #[derive(Debug)] pub struct ReleaseEntry { pub sha256: [u8; 32], pub filename_or_url: String, pub version: Version, pub length: i64, pub is_delta: bool, pub percentage: i32, } impl Default for ReleaseEntry { fn default() -> ReleaseEntry { ReleaseEntry { filename_or_url: "Foobdar".to_owned(), version: Version::parse("1.0.0").unwrap(), is_delta: true, length: 42, sha256: [0; 32], percentage: 100, } } } lazy_static! { static ref SCHEME: Regex = Regex::new(r"^https:").unwrap(); } lazy_static! { static ref COMMENT: Regex = Regex::new(r"#.*$").unwrap(); } impl ReleaseEntry { fn parse_sha256(sha256: &str, to_fill: &mut ReleaseEntry) -> Result<bool, Box<Error>> { let ret = try!(Vec::from_hex(sha256)); if ret.len() != 32 { return Err(From::from("SHA256 is malformed")); } for i in 0..32 { to_fill.sha256[i] = ret[i]; } return Ok(true); } fn parse_delta_full(delta_or_full: &str) -> Result<bool, Box<Error>> { match delta_or_full { "delta" => Ok(true), "full" => Ok(false), _ => Err(From::from("Package type must be either 'delta' or 'full'")) } } fn parse_name(filename_or_url: &str) -> Result<String, Box<Error>> { if SCHEME.is_match(filename_or_url) { try!(Url::parse(filename_or_url)); return Ok(filename_or_url.to_owned()) } else { let u = format!("file:///{}", filename_or_url); let url = try!(Url::parse(&u)); let decoded = try!(percent_decode(url.path().as_bytes()).decode_utf8()); return Ok(decoded.trim_left_matches("/").to_owned()); } } fn parse_percentage(percent: &str) -> Result<i32, Box<Error>> { let n = try!(percent.trim_right_matches("%").parse::<i32>()); if n > 100 || n < 0 { return Err(From::from("Percentage must be between 0 and 100 inclusive")); } return Ok(n); } pub fn parse(entry: &str) -> Result<Self, Box<Error>> { let e = entry.split_whitespace().collect::<Vec<_>>(); return match e.len() { 5 => { let (sha256, name, version, size, delta_or_full) = (e[0], e[1], e[2], e[3], e[4]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: 100, }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, 6 =>
, _ => Err(From::from("Invalid Release Entry string")) } } pub fn parse_entries(content: &str) -> Result<Vec<ReleaseEntry>, Box<Error>> { let mut was_error: Option<Box<Error>> = None; let r: Vec<ReleaseEntry> = content.split("\n").filter_map(|x| { let r = COMMENT.replace_all(x, ""); if r.len() == 0 { return None; } match ReleaseEntry::parse(&r) { Err(err) => { was_error = Some(err); return None; }, Ok(val) => Some(val) } }).collect(); return match was_error { Some(err) => Err(err), None => Ok(r) }; } } #[cfg(test)] mod tests { use sha2::Sha256; use sha2::Digest; use super::ReleaseEntry; fn print_result(sum: &[u8], name: &str) { for byte in sum { print!("{:02x}", byte); } println!("\t{}", name); } #[test] fn create_a_release_entry() { let f = ReleaseEntry::default(); assert_eq!(f.length, 42); } #[test] fn parse_should_read_valid_sha256() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.sha256[0], 0xE4); assert_eq!(result.sha256[1], 0x54); assert_eq!(result.sha256[31], 0x35); } #[test] fn parse_should_fail_invalid_sha256() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_very_invalid_sha256() { let input = "48Z myproject.7z 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_invalid_type() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 foobar"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_set_delta_package() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.is_delta, true); let input2 = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result2 = ReleaseEntry::parse(input2).unwrap(); assert_eq!(result2.is_delta, false); } #[test] fn parse_should_accept_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 45%"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.percentage, 45); } #[test] fn parse_should_fail_giant_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_negative_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn url_encoded_filenames_should_end_up_decoded() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 my%20project.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.filename_or_url, "my project.7z"); } #[test] fn parse_all_entries() { let input = " # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 1.2.3 555 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 2.0.0-beta.1 34567 full 5%"; let result = ReleaseEntry::parse_entries(input).unwrap(); assert_eq!(result.len(), 3); } #[test] fn stringify_a_sha256() { let mut sha = Sha256::default(); sha.input("This is a test".as_bytes()); let hash = sha.result(); print_result(&hash, "SHA256"); println!("Wat."); } }
{ let (sha256, name, version, size, delta_or_full, percent) = (e[0], e[1], e[2], e[3], e[4], e[5]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)).to_owned(), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: try!(ReleaseEntry::parse_percentage(percent)) }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }
conditional_block
release_entry.rs
use hex::*; use regex::Regex; use semver::Version; use std::iter::*; use std::error::{Error}; use url::{Url}; use url::percent_encoding::{percent_decode}; /* Example lines: # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 123 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 34567 full 5% */ #[derive(Debug)] pub struct ReleaseEntry { pub sha256: [u8; 32], pub filename_or_url: String, pub version: Version, pub length: i64, pub is_delta: bool, pub percentage: i32, } impl Default for ReleaseEntry { fn default() -> ReleaseEntry { ReleaseEntry { filename_or_url: "Foobdar".to_owned(), version: Version::parse("1.0.0").unwrap(), is_delta: true, length: 42, sha256: [0; 32], percentage: 100, } } } lazy_static! { static ref SCHEME: Regex = Regex::new(r"^https:").unwrap(); } lazy_static! { static ref COMMENT: Regex = Regex::new(r"#.*$").unwrap(); } impl ReleaseEntry { fn parse_sha256(sha256: &str, to_fill: &mut ReleaseEntry) -> Result<bool, Box<Error>> { let ret = try!(Vec::from_hex(sha256)); if ret.len() != 32 { return Err(From::from("SHA256 is malformed")); } for i in 0..32 { to_fill.sha256[i] = ret[i]; } return Ok(true); } fn parse_delta_full(delta_or_full: &str) -> Result<bool, Box<Error>> { match delta_or_full { "delta" => Ok(true), "full" => Ok(false), _ => Err(From::from("Package type must be either 'delta' or 'full'")) } } fn parse_name(filename_or_url: &str) -> Result<String, Box<Error>> { if SCHEME.is_match(filename_or_url) { try!(Url::parse(filename_or_url)); return Ok(filename_or_url.to_owned()) } else { let u = format!("file:///{}", filename_or_url); let url = try!(Url::parse(&u)); let decoded = try!(percent_decode(url.path().as_bytes()).decode_utf8()); return Ok(decoded.trim_left_matches("/").to_owned()); } } fn parse_percentage(percent: &str) -> Result<i32, Box<Error>> { let n = try!(percent.trim_right_matches("%").parse::<i32>()); if n > 100 || n < 0 { return Err(From::from("Percentage must be between 0 and 100 inclusive")); } return Ok(n); } pub fn parse(entry: &str) -> Result<Self, Box<Error>> { let e = entry.split_whitespace().collect::<Vec<_>>(); return match e.len() { 5 => { let (sha256, name, version, size, delta_or_full) = (e[0], e[1], e[2], e[3], e[4]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: 100, }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, 6 => { let (sha256, name, version, size, delta_or_full, percent) = (e[0], e[1], e[2], e[3], e[4], e[5]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)).to_owned(), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: try!(ReleaseEntry::parse_percentage(percent)) }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, _ => Err(From::from("Invalid Release Entry string")) } } pub fn parse_entries(content: &str) -> Result<Vec<ReleaseEntry>, Box<Error>> { let mut was_error: Option<Box<Error>> = None; let r: Vec<ReleaseEntry> = content.split("\n").filter_map(|x| { let r = COMMENT.replace_all(x, ""); if r.len() == 0 { return None; } match ReleaseEntry::parse(&r) { Err(err) => { was_error = Some(err); return None; }, Ok(val) => Some(val) } }).collect(); return match was_error { Some(err) => Err(err), None => Ok(r) }; } } #[cfg(test)] mod tests { use sha2::Sha256; use sha2::Digest; use super::ReleaseEntry; fn print_result(sum: &[u8], name: &str) { for byte in sum { print!("{:02x}", byte); } println!("\t{}", name); } #[test] fn create_a_release_entry() { let f = ReleaseEntry::default(); assert_eq!(f.length, 42); } #[test] fn parse_should_read_valid_sha256() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.sha256[0], 0xE4); assert_eq!(result.sha256[1], 0x54); assert_eq!(result.sha256[31], 0x35); } #[test] fn parse_should_fail_invalid_sha256() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_very_invalid_sha256() { let input = "48Z myproject.7z 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_invalid_type() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 foobar"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_set_delta_package() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.is_delta, true); let input2 = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result2 = ReleaseEntry::parse(input2).unwrap(); assert_eq!(result2.is_delta, false); } #[test] fn parse_should_accept_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 45%"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.percentage, 45); } #[test] fn parse_should_fail_giant_percentages()
#[test] fn parse_should_fail_negative_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn url_encoded_filenames_should_end_up_decoded() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 my%20project.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.filename_or_url, "my project.7z"); } #[test] fn parse_all_entries() { let input = " # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 1.2.3 555 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 2.0.0-beta.1 34567 full 5%"; let result = ReleaseEntry::parse_entries(input).unwrap(); assert_eq!(result.len(), 3); } #[test] fn stringify_a_sha256() { let mut sha = Sha256::default(); sha.input("This is a test".as_bytes()); let hash = sha.result(); print_result(&hash, "SHA256"); println!("Wat."); } }
{ let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 145%"; ReleaseEntry::parse(input).unwrap_err(); }
identifier_body
release_entry.rs
use hex::*; use regex::Regex; use semver::Version; use std::iter::*; use std::error::{Error}; use url::{Url}; use url::percent_encoding::{percent_decode}; /* Example lines: # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 123 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 34567 full 5% */ #[derive(Debug)] pub struct ReleaseEntry { pub sha256: [u8; 32], pub filename_or_url: String, pub version: Version, pub length: i64, pub is_delta: bool, pub percentage: i32, } impl Default for ReleaseEntry { fn default() -> ReleaseEntry { ReleaseEntry { filename_or_url: "Foobdar".to_owned(), version: Version::parse("1.0.0").unwrap(), is_delta: true, length: 42, sha256: [0; 32], percentage: 100, } } } lazy_static! { static ref SCHEME: Regex = Regex::new(r"^https:").unwrap(); } lazy_static! { static ref COMMENT: Regex = Regex::new(r"#.*$").unwrap(); } impl ReleaseEntry { fn parse_sha256(sha256: &str, to_fill: &mut ReleaseEntry) -> Result<bool, Box<Error>> { let ret = try!(Vec::from_hex(sha256)); if ret.len() != 32 { return Err(From::from("SHA256 is malformed")); } for i in 0..32 { to_fill.sha256[i] = ret[i]; } return Ok(true); } fn parse_delta_full(delta_or_full: &str) -> Result<bool, Box<Error>> { match delta_or_full { "delta" => Ok(true), "full" => Ok(false), _ => Err(From::from("Package type must be either 'delta' or 'full'")) } } fn parse_name(filename_or_url: &str) -> Result<String, Box<Error>> { if SCHEME.is_match(filename_or_url) { try!(Url::parse(filename_or_url)); return Ok(filename_or_url.to_owned()) } else { let u = format!("file:///{}", filename_or_url); let url = try!(Url::parse(&u)); let decoded = try!(percent_decode(url.path().as_bytes()).decode_utf8()); return Ok(decoded.trim_left_matches("/").to_owned()); } } fn parse_percentage(percent: &str) -> Result<i32, Box<Error>> { let n = try!(percent.trim_right_matches("%").parse::<i32>()); if n > 100 || n < 0 { return Err(From::from("Percentage must be between 0 and 100 inclusive")); } return Ok(n); } pub fn parse(entry: &str) -> Result<Self, Box<Error>> { let e = entry.split_whitespace().collect::<Vec<_>>(); return match e.len() { 5 => { let (sha256, name, version, size, delta_or_full) = (e[0], e[1], e[2], e[3], e[4]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: 100, }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, 6 => { let (sha256, name, version, size, delta_or_full, percent) = (e[0], e[1], e[2], e[3], e[4], e[5]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)).to_owned(), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: try!(ReleaseEntry::parse_percentage(percent)) }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, _ => Err(From::from("Invalid Release Entry string")) } } pub fn parse_entries(content: &str) -> Result<Vec<ReleaseEntry>, Box<Error>> { let mut was_error: Option<Box<Error>> = None; let r: Vec<ReleaseEntry> = content.split("\n").filter_map(|x| { let r = COMMENT.replace_all(x, ""); if r.len() == 0 { return None; } match ReleaseEntry::parse(&r) { Err(err) => { was_error = Some(err); return None; }, Ok(val) => Some(val) } }).collect(); return match was_error { Some(err) => Err(err), None => Ok(r) }; } } #[cfg(test)] mod tests { use sha2::Sha256; use sha2::Digest; use super::ReleaseEntry; fn print_result(sum: &[u8], name: &str) { for byte in sum { print!("{:02x}", byte); } println!("\t{}", name); } #[test] fn create_a_release_entry() { let f = ReleaseEntry::default(); assert_eq!(f.length, 42); } #[test] fn parse_should_read_valid_sha256() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.sha256[0], 0xE4); assert_eq!(result.sha256[1], 0x54); assert_eq!(result.sha256[31], 0x35); } #[test] fn parse_should_fail_invalid_sha256() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_very_invalid_sha256() { let input = "48Z myproject.7z 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_invalid_type() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 foobar"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_set_delta_package() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.is_delta, true); let input2 = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result2 = ReleaseEntry::parse(input2).unwrap(); assert_eq!(result2.is_delta, false); } #[test] fn parse_should_accept_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 45%"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.percentage, 45); } #[test] fn parse_should_fail_giant_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn
() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn url_encoded_filenames_should_end_up_decoded() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 my%20project.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.filename_or_url, "my project.7z"); } #[test] fn parse_all_entries() { let input = " # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 1.2.3 555 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 2.0.0-beta.1 34567 full 5%"; let result = ReleaseEntry::parse_entries(input).unwrap(); assert_eq!(result.len(), 3); } #[test] fn stringify_a_sha256() { let mut sha = Sha256::default(); sha.input("This is a test".as_bytes()); let hash = sha.result(); print_result(&hash, "SHA256"); println!("Wat."); } }
parse_should_fail_negative_percentages
identifier_name
release_entry.rs
use hex::*; use regex::Regex; use semver::Version; use std::iter::*; use std::error::{Error}; use url::{Url}; use url::percent_encoding::{percent_decode}; /* Example lines: # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 123 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 34567 full 5% */ #[derive(Debug)]
pub sha256: [u8; 32], pub filename_or_url: String, pub version: Version, pub length: i64, pub is_delta: bool, pub percentage: i32, } impl Default for ReleaseEntry { fn default() -> ReleaseEntry { ReleaseEntry { filename_or_url: "Foobdar".to_owned(), version: Version::parse("1.0.0").unwrap(), is_delta: true, length: 42, sha256: [0; 32], percentage: 100, } } } lazy_static! { static ref SCHEME: Regex = Regex::new(r"^https:").unwrap(); } lazy_static! { static ref COMMENT: Regex = Regex::new(r"#.*$").unwrap(); } impl ReleaseEntry { fn parse_sha256(sha256: &str, to_fill: &mut ReleaseEntry) -> Result<bool, Box<Error>> { let ret = try!(Vec::from_hex(sha256)); if ret.len() != 32 { return Err(From::from("SHA256 is malformed")); } for i in 0..32 { to_fill.sha256[i] = ret[i]; } return Ok(true); } fn parse_delta_full(delta_or_full: &str) -> Result<bool, Box<Error>> { match delta_or_full { "delta" => Ok(true), "full" => Ok(false), _ => Err(From::from("Package type must be either 'delta' or 'full'")) } } fn parse_name(filename_or_url: &str) -> Result<String, Box<Error>> { if SCHEME.is_match(filename_or_url) { try!(Url::parse(filename_or_url)); return Ok(filename_or_url.to_owned()) } else { let u = format!("file:///{}", filename_or_url); let url = try!(Url::parse(&u)); let decoded = try!(percent_decode(url.path().as_bytes()).decode_utf8()); return Ok(decoded.trim_left_matches("/").to_owned()); } } fn parse_percentage(percent: &str) -> Result<i32, Box<Error>> { let n = try!(percent.trim_right_matches("%").parse::<i32>()); if n > 100 || n < 0 { return Err(From::from("Percentage must be between 0 and 100 inclusive")); } return Ok(n); } pub fn parse(entry: &str) -> Result<Self, Box<Error>> { let e = entry.split_whitespace().collect::<Vec<_>>(); return match e.len() { 5 => { let (sha256, name, version, size, delta_or_full) = (e[0], e[1], e[2], e[3], e[4]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: 100, }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, 6 => { let (sha256, name, version, size, delta_or_full, percent) = (e[0], e[1], e[2], e[3], e[4], e[5]); let mut ret = ReleaseEntry { sha256: [0; 32], is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)), filename_or_url: try!(ReleaseEntry::parse_name(name)).to_owned(), version: try!(Version::parse(version)), length: try!(size.parse::<i64>()), percentage: try!(ReleaseEntry::parse_percentage(percent)) }; try!(ReleaseEntry::parse_sha256(sha256, &mut ret)); return Ok(ret); }, _ => Err(From::from("Invalid Release Entry string")) } } pub fn parse_entries(content: &str) -> Result<Vec<ReleaseEntry>, Box<Error>> { let mut was_error: Option<Box<Error>> = None; let r: Vec<ReleaseEntry> = content.split("\n").filter_map(|x| { let r = COMMENT.replace_all(x, ""); if r.len() == 0 { return None; } match ReleaseEntry::parse(&r) { Err(err) => { was_error = Some(err); return None; }, Ok(val) => Some(val) } }).collect(); return match was_error { Some(err) => Err(err), None => Ok(r) }; } } #[cfg(test)] mod tests { use sha2::Sha256; use sha2::Digest; use super::ReleaseEntry; fn print_result(sum: &[u8], name: &str) { for byte in sum { print!("{:02x}", byte); } println!("\t{}", name); } #[test] fn create_a_release_entry() { let f = ReleaseEntry::default(); assert_eq!(f.length, 42); } #[test] fn parse_should_read_valid_sha256() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.sha256[0], 0xE4); assert_eq!(result.sha256[1], 0x54); assert_eq!(result.sha256[31], 0x35); } #[test] fn parse_should_fail_invalid_sha256() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_very_invalid_sha256() { let input = "48Z myproject.7z 12345 full"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_invalid_type() { let input = "48fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 foobar"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_set_delta_package() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.is_delta, true); let input2 = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full"; let result2 = ReleaseEntry::parse(input2).unwrap(); assert_eq!(result2.is_delta, false); } #[test] fn parse_should_accept_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 45%"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.percentage, 45); } #[test] fn parse_should_fail_giant_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn parse_should_fail_negative_percentages() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%"; ReleaseEntry::parse(input).unwrap_err(); } #[test] fn url_encoded_filenames_should_end_up_decoded() { let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 my%20project.7z 1.2.3 12345 full"; let result = ReleaseEntry::parse(input).unwrap(); assert_eq!(result.filename_or_url, "my project.7z"); } #[test] fn parse_all_entries() { let input = " # SHA256 of the file Name Version Size [delta/full] release% e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 full a4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-delta.7z 1.2.3 555 delta b4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject-beta.7z 2.0.0-beta.1 34567 full 5%"; let result = ReleaseEntry::parse_entries(input).unwrap(); assert_eq!(result.len(), 3); } #[test] fn stringify_a_sha256() { let mut sha = Sha256::default(); sha.input("This is a test".as_bytes()); let hash = sha.result(); print_result(&hash, "SHA256"); println!("Wat."); } }
pub struct ReleaseEntry {
random_line_split
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] pub struct HTMLTrackElement { htmlelement: HTMLElement, } impl HTMLTrackElementDerived for EventTarget { fn is_htmltrackelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement))) } } impl HTMLTrackElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTrackElement
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTrackElement> { let element = HTMLTrackElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap) } }
{ HTMLTrackElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document) } }
identifier_body
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct]
htmlelement: HTMLElement, } impl HTMLTrackElementDerived for EventTarget { fn is_htmltrackelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement))) } } impl HTMLTrackElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTrackElement { HTMLTrackElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTrackElement> { let element = HTMLTrackElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap) } }
pub struct HTMLTrackElement {
random_line_split
htmltrackelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] pub struct HTMLTrackElement { htmlelement: HTMLElement, } impl HTMLTrackElementDerived for EventTarget { fn
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement))) } } impl HTMLTrackElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTrackElement { HTMLTrackElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTrackElement> { let element = HTMLTrackElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap) } }
is_htmltrackelement
identifier_name
generic.py
# -*- coding: utf-8 -*- """Operating system independent (generic) preprocessor plugins.""" from dfvfs.helpers import file_system_searcher from plaso.lib import definitions from plaso.preprocessors import interface from plaso.preprocessors import manager class DetermineOperatingSystemPlugin( interface.FileSystemArtifactPreprocessorPlugin): """Plugin to determine the operating system.""" # pylint: disable=abstract-method # This plugin does not use an artifact definition and therefore does not # use _ParsePathSpecification. # We need to check for both forward and backward slashes since the path # specification will be dfVFS back-end dependent. _WINDOWS_LOCATIONS = set([ '/windows/system32', '\\windows\\system32', '/winnt/system32', '\\winnt\\system32', '/winnt35/system32', '\\winnt35\\system32', '\\wtsrv\\system32', '/wtsrv/system32']) def __init__(self): """Initializes a plugin to determine the operating system.""" super(DetermineOperatingSystemPlugin, self).__init__() self._find_specs = [ file_system_searcher.FindSpec( case_sensitive=False, location='/etc', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='/System/Library', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='\\Windows\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT35\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WTSRV\\System32', location_separator='\\')] # pylint: disable=unused-argument def Collect(self, mediator, artifact_definition, searcher, file_system): """Collects values using a file artifact definition. Args: mediator (PreprocessMediator): mediates interactions between preprocess plugins and other components, such as storage and knowledge base. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file system. file_system (dfvfs.FileSystem): file system to be preprocessed. Raises: PreProcessFail: if the preprocessing fails. """ locations = [] for path_spec in searcher.Find(find_specs=self._find_specs): relative_path = searcher.GetRelativePath(path_spec) if relative_path: locations.append(relative_path.lower()) operating_system = definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN if self._WINDOWS_LOCATIONS.intersection(set(locations)):
elif '/system/library' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_MACOS elif '/etc' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_LINUX if operating_system != definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN: mediator.SetValue('operating_system', operating_system) manager.PreprocessPluginsManager.RegisterPlugins([ DetermineOperatingSystemPlugin])
operating_system = definitions.OPERATING_SYSTEM_FAMILY_WINDOWS_NT
conditional_block
generic.py
# -*- coding: utf-8 -*- """Operating system independent (generic) preprocessor plugins.""" from dfvfs.helpers import file_system_searcher from plaso.lib import definitions from plaso.preprocessors import interface from plaso.preprocessors import manager class
( interface.FileSystemArtifactPreprocessorPlugin): """Plugin to determine the operating system.""" # pylint: disable=abstract-method # This plugin does not use an artifact definition and therefore does not # use _ParsePathSpecification. # We need to check for both forward and backward slashes since the path # specification will be dfVFS back-end dependent. _WINDOWS_LOCATIONS = set([ '/windows/system32', '\\windows\\system32', '/winnt/system32', '\\winnt\\system32', '/winnt35/system32', '\\winnt35\\system32', '\\wtsrv\\system32', '/wtsrv/system32']) def __init__(self): """Initializes a plugin to determine the operating system.""" super(DetermineOperatingSystemPlugin, self).__init__() self._find_specs = [ file_system_searcher.FindSpec( case_sensitive=False, location='/etc', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='/System/Library', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='\\Windows\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT35\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WTSRV\\System32', location_separator='\\')] # pylint: disable=unused-argument def Collect(self, mediator, artifact_definition, searcher, file_system): """Collects values using a file artifact definition. Args: mediator (PreprocessMediator): mediates interactions between preprocess plugins and other components, such as storage and knowledge base. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file system. file_system (dfvfs.FileSystem): file system to be preprocessed. Raises: PreProcessFail: if the preprocessing fails. """ locations = [] for path_spec in searcher.Find(find_specs=self._find_specs): relative_path = searcher.GetRelativePath(path_spec) if relative_path: locations.append(relative_path.lower()) operating_system = definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN if self._WINDOWS_LOCATIONS.intersection(set(locations)): operating_system = definitions.OPERATING_SYSTEM_FAMILY_WINDOWS_NT elif '/system/library' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_MACOS elif '/etc' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_LINUX if operating_system != definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN: mediator.SetValue('operating_system', operating_system) manager.PreprocessPluginsManager.RegisterPlugins([ DetermineOperatingSystemPlugin])
DetermineOperatingSystemPlugin
identifier_name
generic.py
# -*- coding: utf-8 -*- """Operating system independent (generic) preprocessor plugins.""" from dfvfs.helpers import file_system_searcher from plaso.lib import definitions from plaso.preprocessors import interface from plaso.preprocessors import manager class DetermineOperatingSystemPlugin( interface.FileSystemArtifactPreprocessorPlugin): """Plugin to determine the operating system.""" # pylint: disable=abstract-method # This plugin does not use an artifact definition and therefore does not # use _ParsePathSpecification. # We need to check for both forward and backward slashes since the path # specification will be dfVFS back-end dependent. _WINDOWS_LOCATIONS = set([ '/windows/system32', '\\windows\\system32', '/winnt/system32', '\\winnt\\system32', '/winnt35/system32', '\\winnt35\\system32', '\\wtsrv\\system32', '/wtsrv/system32']) def __init__(self):
# pylint: disable=unused-argument def Collect(self, mediator, artifact_definition, searcher, file_system): """Collects values using a file artifact definition. Args: mediator (PreprocessMediator): mediates interactions between preprocess plugins and other components, such as storage and knowledge base. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file system. file_system (dfvfs.FileSystem): file system to be preprocessed. Raises: PreProcessFail: if the preprocessing fails. """ locations = [] for path_spec in searcher.Find(find_specs=self._find_specs): relative_path = searcher.GetRelativePath(path_spec) if relative_path: locations.append(relative_path.lower()) operating_system = definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN if self._WINDOWS_LOCATIONS.intersection(set(locations)): operating_system = definitions.OPERATING_SYSTEM_FAMILY_WINDOWS_NT elif '/system/library' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_MACOS elif '/etc' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_LINUX if operating_system != definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN: mediator.SetValue('operating_system', operating_system) manager.PreprocessPluginsManager.RegisterPlugins([ DetermineOperatingSystemPlugin])
"""Initializes a plugin to determine the operating system.""" super(DetermineOperatingSystemPlugin, self).__init__() self._find_specs = [ file_system_searcher.FindSpec( case_sensitive=False, location='/etc', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='/System/Library', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='\\Windows\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT35\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WTSRV\\System32', location_separator='\\')]
identifier_body
generic.py
# -*- coding: utf-8 -*- """Operating system independent (generic) preprocessor plugins.""" from dfvfs.helpers import file_system_searcher from plaso.lib import definitions from plaso.preprocessors import interface from plaso.preprocessors import manager
"""Plugin to determine the operating system.""" # pylint: disable=abstract-method # This plugin does not use an artifact definition and therefore does not # use _ParsePathSpecification. # We need to check for both forward and backward slashes since the path # specification will be dfVFS back-end dependent. _WINDOWS_LOCATIONS = set([ '/windows/system32', '\\windows\\system32', '/winnt/system32', '\\winnt\\system32', '/winnt35/system32', '\\winnt35\\system32', '\\wtsrv\\system32', '/wtsrv/system32']) def __init__(self): """Initializes a plugin to determine the operating system.""" super(DetermineOperatingSystemPlugin, self).__init__() self._find_specs = [ file_system_searcher.FindSpec( case_sensitive=False, location='/etc', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='/System/Library', location_separator='/'), file_system_searcher.FindSpec( case_sensitive=False, location='\\Windows\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WINNT35\\System32', location_separator='\\'), file_system_searcher.FindSpec( case_sensitive=False, location='\\WTSRV\\System32', location_separator='\\')] # pylint: disable=unused-argument def Collect(self, mediator, artifact_definition, searcher, file_system): """Collects values using a file artifact definition. Args: mediator (PreprocessMediator): mediates interactions between preprocess plugins and other components, such as storage and knowledge base. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file system. file_system (dfvfs.FileSystem): file system to be preprocessed. Raises: PreProcessFail: if the preprocessing fails. """ locations = [] for path_spec in searcher.Find(find_specs=self._find_specs): relative_path = searcher.GetRelativePath(path_spec) if relative_path: locations.append(relative_path.lower()) operating_system = definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN if self._WINDOWS_LOCATIONS.intersection(set(locations)): operating_system = definitions.OPERATING_SYSTEM_FAMILY_WINDOWS_NT elif '/system/library' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_MACOS elif '/etc' in locations: operating_system = definitions.OPERATING_SYSTEM_FAMILY_LINUX if operating_system != definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN: mediator.SetValue('operating_system', operating_system) manager.PreprocessPluginsManager.RegisterPlugins([ DetermineOperatingSystemPlugin])
class DetermineOperatingSystemPlugin( interface.FileSystemArtifactPreprocessorPlugin):
random_line_split
cryptauth.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import httplib import json import logging import pprint import time logger = logging.getLogger('proximity_auth.%s' % __name__) _GOOGLE_APIS_URL = 'www.googleapis.com' _REQUEST_PATH = '/cryptauth/v1/%s?alt=JSON' class CryptAuthClient(object): """ A client for making blocking CryptAuth API calls. """ def __init__(self, access_token, google_apis_url=_GOOGLE_APIS_URL): self._access_token = access_token self._google_apis_url = google_apis_url def GetMyDevices(self): """ Invokes the GetMyDevices API. Returns: A list of devices or None if the API call fails. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = { 'approvedForUnlockRequired': False, 'allowStaleRead': False, 'invocationReason': 13 # REASON_MANUAL } response = self._SendRequest('deviceSync/getmydevices', request_data) return response['devices'] if response is not None else None def GetUnlockKey(self): """ Returns: The unlock key registered with CryptAuth if it exists or None. The device is a dictionary of the deserialized JSON returned by CryptAuth. """ devices = self.GetMyDevices() if devices is None: return None for device in devices: if device['unlockKey']: return device return None def ToggleEasyUnlock(self, enable, public_key=''): """ Calls the ToggleEasyUnlock API. Args: enable: True to designate the device specified by |public_key| as an unlock key. public_key: The public key of the device to toggle. Ignored if |enable| is False, which toggles all unlock keys off. Returns: True upon success, else False. """ request_data = { 'enable': enable, } if not enable: request_data['applyToAll'] = True else: request_data['publicKey'] = public_key response = self._SendRequest('deviceSync/toggleeasyunlock', request_data) return response is not None def FindEligibleUnlockDevices(self, time_delta_millis=None): """ Finds devices eligible to be an unlock key. Args: time_delta_millis: If specified, then only return eligible devices that have contacted CryptAuth in the last time delta. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = {} if time_delta_millis is not None: request_data['maxLastUpdateTimeDeltaMillis'] = time_delta_millis * 1000; response = self._SendRequest( 'deviceSync/findeligibleunlockdevices', request_data) if response is None: return None eligibleDevices = ( response['eligibleDevices'] if 'eligibleDevices' in response else []) ineligibleDevices = ( response['ineligibleDevices'] if ( 'ineligibleDevices' in response) else []) return eligibleDevices, ineligibleDevices def PingPhones(self, timeout_secs=10): """ Asks CryptAuth to ping registered phones and determine their status. Args: timeout_secs: The number of seconds to wait for phones to respond. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ response = self._SendRequest( 'deviceSync/senddevicesynctickle', { 'tickleType': 'updateEnrollment' }) if response is None: return None # We wait for phones to update their status with CryptAuth. logger.info('Waiting for %s seconds for phone status...' % timeout_secs)
response. """ conn = httplib.HTTPSConnection(self._google_apis_url) path = _REQUEST_PATH % function_path headers = { 'authorization': 'Bearer ' + self._access_token, 'Content-Type': 'application/json' } body = json.dumps(request_data) logger.info('Making request to %s with body:\n%s' % ( path, pprint.pformat(request_data))) conn.request('POST', path, body, headers) response = conn.getresponse() if response.status == 204: return {} if response.status != 200: logger.warning('Request to %s failed: %s' % (path, response.status)) return None return json.loads(response.read())
time.sleep(timeout_secs) return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs) def _SendRequest(self, function_path, request_data): """ Sends an HTTP request to CryptAuth and returns the deserialized
random_line_split
cryptauth.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import httplib import json import logging import pprint import time logger = logging.getLogger('proximity_auth.%s' % __name__) _GOOGLE_APIS_URL = 'www.googleapis.com' _REQUEST_PATH = '/cryptauth/v1/%s?alt=JSON' class CryptAuthClient(object): """ A client for making blocking CryptAuth API calls. """ def __init__(self, access_token, google_apis_url=_GOOGLE_APIS_URL): self._access_token = access_token self._google_apis_url = google_apis_url def GetMyDevices(self): """ Invokes the GetMyDevices API. Returns: A list of devices or None if the API call fails. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = { 'approvedForUnlockRequired': False, 'allowStaleRead': False, 'invocationReason': 13 # REASON_MANUAL } response = self._SendRequest('deviceSync/getmydevices', request_data) return response['devices'] if response is not None else None def GetUnlockKey(self): """ Returns: The unlock key registered with CryptAuth if it exists or None. The device is a dictionary of the deserialized JSON returned by CryptAuth. """ devices = self.GetMyDevices() if devices is None: return None for device in devices: if device['unlockKey']: return device return None def ToggleEasyUnlock(self, enable, public_key=''): """ Calls the ToggleEasyUnlock API. Args: enable: True to designate the device specified by |public_key| as an unlock key. public_key: The public key of the device to toggle. Ignored if |enable| is False, which toggles all unlock keys off. Returns: True upon success, else False. """ request_data = { 'enable': enable, } if not enable: request_data['applyToAll'] = True else: request_data['publicKey'] = public_key response = self._SendRequest('deviceSync/toggleeasyunlock', request_data) return response is not None def
(self, time_delta_millis=None): """ Finds devices eligible to be an unlock key. Args: time_delta_millis: If specified, then only return eligible devices that have contacted CryptAuth in the last time delta. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = {} if time_delta_millis is not None: request_data['maxLastUpdateTimeDeltaMillis'] = time_delta_millis * 1000; response = self._SendRequest( 'deviceSync/findeligibleunlockdevices', request_data) if response is None: return None eligibleDevices = ( response['eligibleDevices'] if 'eligibleDevices' in response else []) ineligibleDevices = ( response['ineligibleDevices'] if ( 'ineligibleDevices' in response) else []) return eligibleDevices, ineligibleDevices def PingPhones(self, timeout_secs=10): """ Asks CryptAuth to ping registered phones and determine their status. Args: timeout_secs: The number of seconds to wait for phones to respond. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ response = self._SendRequest( 'deviceSync/senddevicesynctickle', { 'tickleType': 'updateEnrollment' }) if response is None: return None # We wait for phones to update their status with CryptAuth. logger.info('Waiting for %s seconds for phone status...' % timeout_secs) time.sleep(timeout_secs) return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs) def _SendRequest(self, function_path, request_data): """ Sends an HTTP request to CryptAuth and returns the deserialized response. """ conn = httplib.HTTPSConnection(self._google_apis_url) path = _REQUEST_PATH % function_path headers = { 'authorization': 'Bearer ' + self._access_token, 'Content-Type': 'application/json' } body = json.dumps(request_data) logger.info('Making request to %s with body:\n%s' % ( path, pprint.pformat(request_data))) conn.request('POST', path, body, headers) response = conn.getresponse() if response.status == 204: return {} if response.status != 200: logger.warning('Request to %s failed: %s' % (path, response.status)) return None return json.loads(response.read())
FindEligibleUnlockDevices
identifier_name
cryptauth.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import httplib import json import logging import pprint import time logger = logging.getLogger('proximity_auth.%s' % __name__) _GOOGLE_APIS_URL = 'www.googleapis.com' _REQUEST_PATH = '/cryptauth/v1/%s?alt=JSON' class CryptAuthClient(object): """ A client for making blocking CryptAuth API calls. """ def __init__(self, access_token, google_apis_url=_GOOGLE_APIS_URL): self._access_token = access_token self._google_apis_url = google_apis_url def GetMyDevices(self): """ Invokes the GetMyDevices API. Returns: A list of devices or None if the API call fails. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = { 'approvedForUnlockRequired': False, 'allowStaleRead': False, 'invocationReason': 13 # REASON_MANUAL } response = self._SendRequest('deviceSync/getmydevices', request_data) return response['devices'] if response is not None else None def GetUnlockKey(self): """ Returns: The unlock key registered with CryptAuth if it exists or None. The device is a dictionary of the deserialized JSON returned by CryptAuth. """ devices = self.GetMyDevices() if devices is None: return None for device in devices: if device['unlockKey']: return device return None def ToggleEasyUnlock(self, enable, public_key=''): """ Calls the ToggleEasyUnlock API. Args: enable: True to designate the device specified by |public_key| as an unlock key. public_key: The public key of the device to toggle. Ignored if |enable| is False, which toggles all unlock keys off. Returns: True upon success, else False. """ request_data = { 'enable': enable, } if not enable: request_data['applyToAll'] = True else: request_data['publicKey'] = public_key response = self._SendRequest('deviceSync/toggleeasyunlock', request_data) return response is not None def FindEligibleUnlockDevices(self, time_delta_millis=None): """ Finds devices eligible to be an unlock key. Args: time_delta_millis: If specified, then only return eligible devices that have contacted CryptAuth in the last time delta. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = {} if time_delta_millis is not None: request_data['maxLastUpdateTimeDeltaMillis'] = time_delta_millis * 1000; response = self._SendRequest( 'deviceSync/findeligibleunlockdevices', request_data) if response is None: return None eligibleDevices = ( response['eligibleDevices'] if 'eligibleDevices' in response else []) ineligibleDevices = ( response['ineligibleDevices'] if ( 'ineligibleDevices' in response) else []) return eligibleDevices, ineligibleDevices def PingPhones(self, timeout_secs=10): """ Asks CryptAuth to ping registered phones and determine their status. Args: timeout_secs: The number of seconds to wait for phones to respond. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ response = self._SendRequest( 'deviceSync/senddevicesynctickle', { 'tickleType': 'updateEnrollment' }) if response is None:
# We wait for phones to update their status with CryptAuth. logger.info('Waiting for %s seconds for phone status...' % timeout_secs) time.sleep(timeout_secs) return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs) def _SendRequest(self, function_path, request_data): """ Sends an HTTP request to CryptAuth and returns the deserialized response. """ conn = httplib.HTTPSConnection(self._google_apis_url) path = _REQUEST_PATH % function_path headers = { 'authorization': 'Bearer ' + self._access_token, 'Content-Type': 'application/json' } body = json.dumps(request_data) logger.info('Making request to %s with body:\n%s' % ( path, pprint.pformat(request_data))) conn.request('POST', path, body, headers) response = conn.getresponse() if response.status == 204: return {} if response.status != 200: logger.warning('Request to %s failed: %s' % (path, response.status)) return None return json.loads(response.read())
return None
conditional_block
cryptauth.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import httplib import json import logging import pprint import time logger = logging.getLogger('proximity_auth.%s' % __name__) _GOOGLE_APIS_URL = 'www.googleapis.com' _REQUEST_PATH = '/cryptauth/v1/%s?alt=JSON' class CryptAuthClient(object): """ A client for making blocking CryptAuth API calls. """ def __init__(self, access_token, google_apis_url=_GOOGLE_APIS_URL):
def GetMyDevices(self): """ Invokes the GetMyDevices API. Returns: A list of devices or None if the API call fails. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = { 'approvedForUnlockRequired': False, 'allowStaleRead': False, 'invocationReason': 13 # REASON_MANUAL } response = self._SendRequest('deviceSync/getmydevices', request_data) return response['devices'] if response is not None else None def GetUnlockKey(self): """ Returns: The unlock key registered with CryptAuth if it exists or None. The device is a dictionary of the deserialized JSON returned by CryptAuth. """ devices = self.GetMyDevices() if devices is None: return None for device in devices: if device['unlockKey']: return device return None def ToggleEasyUnlock(self, enable, public_key=''): """ Calls the ToggleEasyUnlock API. Args: enable: True to designate the device specified by |public_key| as an unlock key. public_key: The public key of the device to toggle. Ignored if |enable| is False, which toggles all unlock keys off. Returns: True upon success, else False. """ request_data = { 'enable': enable, } if not enable: request_data['applyToAll'] = True else: request_data['publicKey'] = public_key response = self._SendRequest('deviceSync/toggleeasyunlock', request_data) return response is not None def FindEligibleUnlockDevices(self, time_delta_millis=None): """ Finds devices eligible to be an unlock key. Args: time_delta_millis: If specified, then only return eligible devices that have contacted CryptAuth in the last time delta. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ request_data = {} if time_delta_millis is not None: request_data['maxLastUpdateTimeDeltaMillis'] = time_delta_millis * 1000; response = self._SendRequest( 'deviceSync/findeligibleunlockdevices', request_data) if response is None: return None eligibleDevices = ( response['eligibleDevices'] if 'eligibleDevices' in response else []) ineligibleDevices = ( response['ineligibleDevices'] if ( 'ineligibleDevices' in response) else []) return eligibleDevices, ineligibleDevices def PingPhones(self, timeout_secs=10): """ Asks CryptAuth to ping registered phones and determine their status. Args: timeout_secs: The number of seconds to wait for phones to respond. Returns: A tuple containing two lists, one of eligible devices and the other of ineligible devices. Each device is a dictionary of the deserialized JSON returned by CryptAuth. """ response = self._SendRequest( 'deviceSync/senddevicesynctickle', { 'tickleType': 'updateEnrollment' }) if response is None: return None # We wait for phones to update their status with CryptAuth. logger.info('Waiting for %s seconds for phone status...' % timeout_secs) time.sleep(timeout_secs) return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs) def _SendRequest(self, function_path, request_data): """ Sends an HTTP request to CryptAuth and returns the deserialized response. """ conn = httplib.HTTPSConnection(self._google_apis_url) path = _REQUEST_PATH % function_path headers = { 'authorization': 'Bearer ' + self._access_token, 'Content-Type': 'application/json' } body = json.dumps(request_data) logger.info('Making request to %s with body:\n%s' % ( path, pprint.pformat(request_data))) conn.request('POST', path, body, headers) response = conn.getresponse() if response.status == 204: return {} if response.status != 200: logger.warning('Request to %s failed: %s' % (path, response.status)) return None return json.loads(response.read())
self._access_token = access_token self._google_apis_url = google_apis_url
identifier_body
Gruntfile.js
module.exports = function (grunt) { "use strict"; grunt.initConfig({ dirs: { css: 'app/css', js: 'app/js', sass: 'app/sass', }, compass: { dist: { options: { config: 'config.rb', } } }, concat: { options: { seperator: ';', }, dist: { src: ['<%= dirs.js %>/modules/*.js', '<%= dirs.js %>/src/*.js'], dest: '<%= dirs.js %>/app.js'
} }, uglify: { options: { // mangle: false, debug: true, }, target: { files: { '<%= dirs.js %>/app.min.js': ['<%= dirs.js %>/app.js'] } } }, watch: { css: { files: [ '<%= dirs.sass %>/*.scss', '<%= dirs.sass %>/modules/*.scss', '<%= dirs.sass %>/partials/*.scss' ], tasks: ['css'], options: { spawn: false, } }, js: { files: [ '<%= dirs.js %>/modules/*.js', '<%= dirs.js %>/src/*.js' ], tasks: ['js'], options: { spawn: false, } } } }); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['css', 'js']); grunt.registerTask('css', ['compass']); grunt.registerTask('js', ['concat', 'uglify']); };
random_line_split
OutputBindingCard.tsx
import i18next from 'i18next'; import { Link } from 'office-ui-fabric-react'; import React, { useContext } from 'react';
import { ReactComponent as OutputSvg } from '../../../../../../images/Common/output.svg'; import { ArmObj } from '../../../../../../models/arm-obj'; import { Binding, BindingDirection } from '../../../../../../models/functions/binding'; import { BindingInfo } from '../../../../../../models/functions/function-binding'; import { FunctionInfo } from '../../../../../../models/functions/function-info'; import PortalCommunicator from '../../../../../../portal-communicator'; import { PortalContext } from '../../../../../../PortalContext'; import { ThemeExtended } from '../../../../../../theme/SemanticColorsExtended'; import { ThemeContext } from '../../../../../../ThemeContext'; import { BindingFormBuilder } from '../../../common/BindingFormBuilder'; import { BindingEditorContext, BindingEditorContextInfo } from '../FunctionIntegrate'; import { getBindingDirection } from '../FunctionIntegrate.utils'; import BindingCard, { createNew, EditableBindingCardProps, editExisting, emptyList } from './BindingCard'; import { listStyle } from './BindingCard.styles'; const OutputBindingCard: React.SFC<EditableBindingCardProps> = props => { const { functionInfo, bindings, readOnly, loadBindingSettings } = props; const { t } = useTranslation(); const theme = useContext(ThemeContext); const portalCommunicator = useContext(PortalContext); const bindingEditorContext = useContext(BindingEditorContext) as BindingEditorContextInfo; const outputs = getOutputBindings(functionInfo.properties.config.bindings); const content = getContent( portalCommunicator, functionInfo, bindings, t, bindingEditorContext, theme, outputs, readOnly, loadBindingSettings ); return <BindingCard title={t('output')} Svg={OutputSvg} content={content} {...props} />; }; const getOutputBindings = (bindings: BindingInfo[]): BindingInfo[] => { const outputBindings = bindings.filter(binding => { return getBindingDirection(binding) === BindingDirection.out; }); return outputBindings ? outputBindings : []; }; const getContent = ( portalCommunicator: PortalCommunicator, functionInfo: ArmObj<FunctionInfo>, bindings: Binding[], t: i18next.TFunction, bindingEditorContext: BindingEditorContextInfo, theme: ThemeExtended, outputBindings: BindingInfo[], readOnly: boolean, loadBindingSettings: (bindingId: string, force: boolean) => Promise<void> ): JSX.Element => { const outputList: JSX.Element[] = outputBindings.map((item, i) => { const name = item.name ? `(${item.name})` : ''; const linkName = `${BindingFormBuilder.getBindingTypeName(item, bindings)} ${name}`; return ( <li key={i.toString()}> <Link onClick={() => { loadBindingSettings( bindings.find(binding => binding.type === item.type && binding.direction === BindingDirection.out)!.id, false ).then(() => { editExisting(portalCommunicator, t, functionInfo, item, bindingEditorContext, BindingDirection.out); }); }}> {linkName} </Link> </li> ); }); const completeOutputList = outputList.length > 0 ? outputList : emptyList(t('integrateNoOutputsDefined')); if (!readOnly) { completeOutputList.push( <li key={'newOutput'}> <Link onClick={() => { const inputs = bindings.filter(binding => binding.direction === BindingDirection.out); Promise.all(inputs.map(binding => loadBindingSettings(binding.id, false))).then(() => { createNew(portalCommunicator, t, functionInfo, bindingEditorContext, BindingDirection.out); }); }}> {t('integrateAddOutput')} </Link> </li> ); } return <ul className={listStyle(theme)}>{completeOutputList}</ul>; }; export default OutputBindingCard;
import { useTranslation } from 'react-i18next';
random_line_split
table_colgroup.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use app_units::Au; use context::LayoutContext; use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::Point2D; use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator, Overflow, SpecificFragmentInfo}; use layout_debug; use std::cmp::max; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::values::computed::LengthOrPercentageOrAuto; #[allow(unsafe_code)] unsafe impl ::flow::HasBaseFlow for TableColGroupFlow {} /// A table formatting context. #[repr(C)] pub struct TableColGroupFlow { /// Data common to all flows. pub base: BaseFlow, /// The associated fragment. pub fragment: Option<Fragment>, /// The table column fragments pub cols: Vec<Fragment>, /// The specified inline-sizes of table columns. (We use `LengthOrPercentageOrAuto` here in /// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred /// inline sizes.) pub inline_sizes: Vec<LengthOrPercentageOrAuto>, } impl TableColGroupFlow { pub fn from_fragments(fragment: Fragment, fragments: Vec<Fragment>) -> TableColGroupFlow { let writing_mode = fragment.style().writing_mode; TableColGroupFlow { base: BaseFlow::new(Some(fragment.style()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Some(fragment), cols: fragments, inline_sizes: vec!(), } } } impl Flow for TableColGroupFlow { fn class(&self) -> FlowClass { FlowClass::TableColGroup } fn as_mut_table_colgroup(&mut self) -> &mut TableColGroupFlow { self } fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("table_colgroup::bubble_inline_sizes {:x}", self.base.debug_id()); for fragment in &self.cols { // Retrieve the specified value from the appropriate CSS property. let inline_size = fragment.style().content_inline_size(); let span = match fragment.specific { SpecificFragmentInfo::TableColumn(col_fragment) => max(col_fragment.span, 1), _ => panic!("non-table-column fragment inside table column?!"), }; for _ in 0..span { self.inline_sizes.push(inline_size) } } } /// Table column inline-sizes are assigned in the table flow and propagated to table row flows /// and/or rowgroup flows. Therefore, table colgroup flows do not need to assign inline-sizes. fn assign_inline_sizes(&mut self, _: &LayoutContext) { } /// Table columns do not have block-size. fn assign_block_size(&mut self, _: &LayoutContext) { } fn update_late_computed_inline_position_if_necessary(&mut self, _: Au) {} fn update_late_computed_block_position_if_necessary(&mut self, _: Au) {} // Table columns are invisible. fn build_display_list(&mut self, _: &mut DisplayListBuildState) { } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.base.stacking_context_id = state.current_stacking_context_id; self.base.clipping_and_scrolling = Some(state.current_clipping_and_scrolling); } fn repair_style(&mut self, _: &::ServoArc<ComputedValues>) {} fn compute_overflow(&self) -> Overflow { Overflow::new() } fn generated_containing_block_size(&self, _: OpaqueFlow) -> LogicalSize<Au>
fn iterate_through_fragment_border_boxes(&self, _: &mut FragmentBorderBoxIterator, _: i32, _: &Point2D<Au>) {} fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {} } impl fmt::Debug for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { Some(ref rb) => write!(f, "TableColGroupFlow: {:?}", rb), None => write!(f, "TableColGroupFlow"), } } }
{ panic!("Table column groups can't be containing blocks!") }
identifier_body
table_colgroup.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use app_units::Au; use context::LayoutContext; use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::Point2D; use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator, Overflow, SpecificFragmentInfo}; use layout_debug; use std::cmp::max; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::values::computed::LengthOrPercentageOrAuto; #[allow(unsafe_code)] unsafe impl ::flow::HasBaseFlow for TableColGroupFlow {} /// A table formatting context. #[repr(C)] pub struct TableColGroupFlow { /// Data common to all flows. pub base: BaseFlow, /// The associated fragment. pub fragment: Option<Fragment>, /// The table column fragments pub cols: Vec<Fragment>, /// The specified inline-sizes of table columns. (We use `LengthOrPercentageOrAuto` here in /// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred /// inline sizes.) pub inline_sizes: Vec<LengthOrPercentageOrAuto>, } impl TableColGroupFlow { pub fn from_fragments(fragment: Fragment, fragments: Vec<Fragment>) -> TableColGroupFlow { let writing_mode = fragment.style().writing_mode; TableColGroupFlow { base: BaseFlow::new(Some(fragment.style()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Some(fragment), cols: fragments, inline_sizes: vec!(), } } } impl Flow for TableColGroupFlow { fn class(&self) -> FlowClass { FlowClass::TableColGroup } fn as_mut_table_colgroup(&mut self) -> &mut TableColGroupFlow { self } fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("table_colgroup::bubble_inline_sizes {:x}", self.base.debug_id()); for fragment in &self.cols { // Retrieve the specified value from the appropriate CSS property. let inline_size = fragment.style().content_inline_size(); let span = match fragment.specific { SpecificFragmentInfo::TableColumn(col_fragment) => max(col_fragment.span, 1), _ => panic!("non-table-column fragment inside table column?!"), }; for _ in 0..span { self.inline_sizes.push(inline_size) } } } /// Table column inline-sizes are assigned in the table flow and propagated to table row flows /// and/or rowgroup flows. Therefore, table colgroup flows do not need to assign inline-sizes. fn assign_inline_sizes(&mut self, _: &LayoutContext) { } /// Table columns do not have block-size. fn assign_block_size(&mut self, _: &LayoutContext) { } fn update_late_computed_inline_position_if_necessary(&mut self, _: Au) {} fn update_late_computed_block_position_if_necessary(&mut self, _: Au) {} // Table columns are invisible. fn build_display_list(&mut self, _: &mut DisplayListBuildState) { }
fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.base.stacking_context_id = state.current_stacking_context_id; self.base.clipping_and_scrolling = Some(state.current_clipping_and_scrolling); } fn repair_style(&mut self, _: &::ServoArc<ComputedValues>) {} fn compute_overflow(&self) -> Overflow { Overflow::new() } fn generated_containing_block_size(&self, _: OpaqueFlow) -> LogicalSize<Au> { panic!("Table column groups can't be containing blocks!") } fn iterate_through_fragment_border_boxes(&self, _: &mut FragmentBorderBoxIterator, _: i32, _: &Point2D<Au>) {} fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {} } impl fmt::Debug for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { Some(ref rb) => write!(f, "TableColGroupFlow: {:?}", rb), None => write!(f, "TableColGroupFlow"), } } }
random_line_split
table_colgroup.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use app_units::Au; use context::LayoutContext; use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::Point2D; use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator, Overflow, SpecificFragmentInfo}; use layout_debug; use std::cmp::max; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::values::computed::LengthOrPercentageOrAuto; #[allow(unsafe_code)] unsafe impl ::flow::HasBaseFlow for TableColGroupFlow {} /// A table formatting context. #[repr(C)] pub struct TableColGroupFlow { /// Data common to all flows. pub base: BaseFlow, /// The associated fragment. pub fragment: Option<Fragment>, /// The table column fragments pub cols: Vec<Fragment>, /// The specified inline-sizes of table columns. (We use `LengthOrPercentageOrAuto` here in /// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred /// inline sizes.) pub inline_sizes: Vec<LengthOrPercentageOrAuto>, } impl TableColGroupFlow { pub fn from_fragments(fragment: Fragment, fragments: Vec<Fragment>) -> TableColGroupFlow { let writing_mode = fragment.style().writing_mode; TableColGroupFlow { base: BaseFlow::new(Some(fragment.style()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Some(fragment), cols: fragments, inline_sizes: vec!(), } } } impl Flow for TableColGroupFlow { fn class(&self) -> FlowClass { FlowClass::TableColGroup } fn as_mut_table_colgroup(&mut self) -> &mut TableColGroupFlow { self } fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("table_colgroup::bubble_inline_sizes {:x}", self.base.debug_id()); for fragment in &self.cols { // Retrieve the specified value from the appropriate CSS property. let inline_size = fragment.style().content_inline_size(); let span = match fragment.specific { SpecificFragmentInfo::TableColumn(col_fragment) => max(col_fragment.span, 1), _ => panic!("non-table-column fragment inside table column?!"), }; for _ in 0..span { self.inline_sizes.push(inline_size) } } } /// Table column inline-sizes are assigned in the table flow and propagated to table row flows /// and/or rowgroup flows. Therefore, table colgroup flows do not need to assign inline-sizes. fn assign_inline_sizes(&mut self, _: &LayoutContext) { } /// Table columns do not have block-size. fn assign_block_size(&mut self, _: &LayoutContext) { } fn update_late_computed_inline_position_if_necessary(&mut self, _: Au) {} fn update_late_computed_block_position_if_necessary(&mut self, _: Au) {} // Table columns are invisible. fn build_display_list(&mut self, _: &mut DisplayListBuildState) { } fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) { self.base.stacking_context_id = state.current_stacking_context_id; self.base.clipping_and_scrolling = Some(state.current_clipping_and_scrolling); } fn
(&mut self, _: &::ServoArc<ComputedValues>) {} fn compute_overflow(&self) -> Overflow { Overflow::new() } fn generated_containing_block_size(&self, _: OpaqueFlow) -> LogicalSize<Au> { panic!("Table column groups can't be containing blocks!") } fn iterate_through_fragment_border_boxes(&self, _: &mut FragmentBorderBoxIterator, _: i32, _: &Point2D<Au>) {} fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {} } impl fmt::Debug for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { Some(ref rb) => write!(f, "TableColGroupFlow: {:?}", rb), None => write!(f, "TableColGroupFlow"), } } }
repair_style
identifier_name
detect_outlier.py
import numpy as np import sys sys.path.append("../Pipeline/Audio/Pipeline/") from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing import AudioPipe.speaker.recognition as SR # Speaker Recognition Module import scipy.io.wavfile as wav import commands, os import json import argparse import warnings from scipy import stats def outlier_detect(audio_dir, spk_name): spk_dir = os.path.join(audio_dir,spk_name) list_fn = os.path.join(spk_dir,"clip_list.txt") clip_ls = from_jsonfile(list_fn) audio_merge = merge_clips(spk_dir, clip_ls) # Training a model based on the merged audio Model = SR.GMMRec() Model.enroll_file(spk_name, audio_merge) Model.train() # Score each utterance in the training set llhd_ls = [] new_ls = [] stat_fn = os.path.join(audio_dir,"stats.json") if os.path.exists(stat_fn) and os.path.getsize(stat_fn) > 0: stat_dict = from_jsonfile(stat_fn) else: stat_dict = {} if spk_name not in stat_dict: stat_dict[spk_name]={} for clip in clip_ls: audio_test = os.path.join(spk_dir,clip["name"]) #commands.getstatusoutput("ffmpeg -i "+audio_test+" -vn -f wav -ab 16k "+audio_test) try: llhd = Model.predict(Model.get_mfcc(audio_test))[1] except ValueError: print clip["name"] continue llhd_ls.append(llhd) clip["llhd"] = llhd new_ls.append(clip) z_score = stats.zscore(llhd_ls) for i in xrange(len(llhd_ls)): new_ls[i]["zscore"] = z_score[i] with open(list_fn, "w") as fh: fh.write(to_json(new_ls, indent=2)) stat_dict[spk_name]["clip_num"]=len(clip_ls) stat_dict[spk_name]["zpos_num"]=sum(z_score>0) stat_dict[spk_name]["total_duration"]=sum([get_sec(clp["duration"]) for clp in new_ls]) stat_dict[spk_name]["clean_duration"]=sum([get_sec(clp["duration"]) for clp in new_ls if clp["zscore"]>-0.00001]) with open(stat_fn, "w") as fh: fh.write(to_json(stat_dict, indent=2)) os.remove(audio_merge) return llhd_ls def merge_clips(spk_dir, clip_ls): # Write the list of clips into a file for merging training data
def from_jsonfile(filename): with open(filename) as fh: return json.load(fh) def get_sec(time_str): h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + float(s) def to_json(result, **kwargs): '''Return a JSON representation of the aligned transcript''' options = { 'sort_keys': True, 'indent': 4, 'separators': (',', ': '), } options.update(kwargs) return json.dumps(result, **options) parser = argparse.ArgumentParser( description='Detect outliers in a training dataset of one speaker.') parser.add_argument( '-i', '--input', dest='input_dir', type=str, help='directory of audio clips') parser.add_argument( '-s', '--spk', dest='spk_name', type=str, help='the name of the speaker') args = parser.parse_args() audio_dir = args.input_dir spk_name = args.spk_name with warnings.catch_warnings(): warnings.simplefilter("ignore") outlier_detect(audio_dir, spk_name)
temp_fl = os.path.join(spk_dir,"temp.txt") count = 0 with open(temp_fl, "w") as fh: for clip in clip_ls: if count>100: break fh.write("file "+clip["name"]+"\n") count+=1 # Merge all the data into one audio audio_merge = os.path.join(spk_dir,"merged_gross.wav") commands.getstatusoutput("ffmpeg -f concat -i "+temp_fl.replace(" ", "\ ")+" -c copy -y "+audio_merge) os.remove(temp_fl) return audio_merge
identifier_body
detect_outlier.py
import numpy as np import sys sys.path.append("../Pipeline/Audio/Pipeline/") from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing import AudioPipe.speaker.recognition as SR # Speaker Recognition Module import scipy.io.wavfile as wav import commands, os import json import argparse import warnings from scipy import stats def outlier_detect(audio_dir, spk_name): spk_dir = os.path.join(audio_dir,spk_name) list_fn = os.path.join(spk_dir,"clip_list.txt") clip_ls = from_jsonfile(list_fn) audio_merge = merge_clips(spk_dir, clip_ls) # Training a model based on the merged audio Model = SR.GMMRec() Model.enroll_file(spk_name, audio_merge) Model.train() # Score each utterance in the training set llhd_ls = [] new_ls = [] stat_fn = os.path.join(audio_dir,"stats.json")
if os.path.exists(stat_fn) and os.path.getsize(stat_fn) > 0: stat_dict = from_jsonfile(stat_fn) else: stat_dict = {} if spk_name not in stat_dict: stat_dict[spk_name]={} for clip in clip_ls: audio_test = os.path.join(spk_dir,clip["name"]) #commands.getstatusoutput("ffmpeg -i "+audio_test+" -vn -f wav -ab 16k "+audio_test) try: llhd = Model.predict(Model.get_mfcc(audio_test))[1] except ValueError: print clip["name"] continue llhd_ls.append(llhd) clip["llhd"] = llhd new_ls.append(clip) z_score = stats.zscore(llhd_ls) for i in xrange(len(llhd_ls)): new_ls[i]["zscore"] = z_score[i] with open(list_fn, "w") as fh: fh.write(to_json(new_ls, indent=2)) stat_dict[spk_name]["clip_num"]=len(clip_ls) stat_dict[spk_name]["zpos_num"]=sum(z_score>0) stat_dict[spk_name]["total_duration"]=sum([get_sec(clp["duration"]) for clp in new_ls]) stat_dict[spk_name]["clean_duration"]=sum([get_sec(clp["duration"]) for clp in new_ls if clp["zscore"]>-0.00001]) with open(stat_fn, "w") as fh: fh.write(to_json(stat_dict, indent=2)) os.remove(audio_merge) return llhd_ls def merge_clips(spk_dir, clip_ls): # Write the list of clips into a file for merging training data temp_fl = os.path.join(spk_dir,"temp.txt") count = 0 with open(temp_fl, "w") as fh: for clip in clip_ls: if count>100: break fh.write("file "+clip["name"]+"\n") count+=1 # Merge all the data into one audio audio_merge = os.path.join(spk_dir,"merged_gross.wav") commands.getstatusoutput("ffmpeg -f concat -i "+temp_fl.replace(" ", "\ ")+" -c copy -y "+audio_merge) os.remove(temp_fl) return audio_merge def from_jsonfile(filename): with open(filename) as fh: return json.load(fh) def get_sec(time_str): h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + float(s) def to_json(result, **kwargs): '''Return a JSON representation of the aligned transcript''' options = { 'sort_keys': True, 'indent': 4, 'separators': (',', ': '), } options.update(kwargs) return json.dumps(result, **options) parser = argparse.ArgumentParser( description='Detect outliers in a training dataset of one speaker.') parser.add_argument( '-i', '--input', dest='input_dir', type=str, help='directory of audio clips') parser.add_argument( '-s', '--spk', dest='spk_name', type=str, help='the name of the speaker') args = parser.parse_args() audio_dir = args.input_dir spk_name = args.spk_name with warnings.catch_warnings(): warnings.simplefilter("ignore") outlier_detect(audio_dir, spk_name)
random_line_split