text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add a comment for New.
package gtf import ( "html/template" "strings" ) var GtfFuncMap = template.FuncMap { "stringReplace": func(s1 string, s2 string) string { return strings.Replace(s2, s1, "", -1) }, "stringDefault": func(s1 string, s2 string) string { if len(s2) > 0 { return s2 } return s1 }, "stringLength": func(s string) int { return len(s) }, "stringLower": func(s string) string { return strings.ToLower(s) }, "stringTruncateChars": func(n int, s string) string { if n < 0 { return s } r := []rune(s) rLength := len(r) if n >= rLength { return s } if n > 3 && rLength > 3 { return string(r[:n-3]) + "..." } return string(r[:n]) }, } // gtf.New is a wrapper function of template.New(http://golang.org/pkg/text/template/#New). // It automatically adds the gtf functions to the template's function map // and returns template.Template(http://golang.org/pkg/text/template/#Template). func New(name string) *template.Template { return template.New(name).Funcs(GtfFuncMap) }
package gtf import ( "html/template" "strings" ) var GtfFuncMap = template.FuncMap { "stringReplace": func(s1 string, s2 string) string { return strings.Replace(s2, s1, "", -1) }, "stringDefault": func(s1 string, s2 string) string { if len(s2) > 0 { return s2 } return s1 }, "stringLength": func(s string) int { return len(s) }, "stringLower": func(s string) string { return strings.ToLower(s) }, "stringTruncateChars": func(n int, s string) string { if n < 0 { return s } r := []rune(s) rLength := len(r) if n >= rLength { return s } if n > 3 && rLength > 3 { return string(r[:n-3]) + "..." } return string(r[:n]) }, } func New(name string) *template.Template { return template.New(name).Funcs(GtfFuncMap) }
Fix JSLint error, use camelCase for functions
Gratipay.giving = {} Gratipay.giving.init = function() { Gratipay.giving.activateTab('active'); $('.giving #tab-nav a').on('click', Gratipay.giving.handleClick); } Gratipay.giving.handleClick = function(e) { e.preventDefault(); var $target = $(e.target); Gratipay.giving.activateTab($target.data('tab')); } Gratipay.giving.activateTab = function(tab) { $.each($('.giving #tab-nav a'), function(i, obj) { var $obj = $(obj); if ($obj.data('tab') == tab) { $obj.addClass('selected'); } else { $obj.removeClass('selected'); } }) $.each($('.giving .tab'), function(i, obj) { var $obj = $(obj); if ($obj.data('tab') == tab) { $obj.show(); } else { $obj.hide(); } }) }
Gratipay.giving = {} Gratipay.giving.init = function() { Gratipay.giving.activate_tab('active'); $('.giving #tab-nav a').on('click', Gratipay.giving.handle_click); } Gratipay.giving.handle_click = function(e) { e.preventDefault(); var $target = $(e.target); Gratipay.giving.activate_tab($target.data('tab')); } Gratipay.giving.activate_tab = function(tab) { $.each($('.giving #tab-nav a'), function(i, obj) { var $obj = $(obj); $obj.data('tab') == tab ? $obj.addClass('selected') : $obj.removeClass('selected'); }) $.each($('.giving .tab'), function(i, obj) { var $obj = $(obj); $obj.data('tab') == tab ? $obj.show() : $obj.hide(); }) }
Fix node_modules paths on Windows This change moves 'prefix' test to happen after the absolute path is resolved. Without it, the prefix tests never actually fire when starting with a relative path, and the resulting dirs all end up looking like [ '/C:..', '/C:...' ] instead of [ 'C:...', 'C:...' ]
var path = require('path'); module.exports = function (start, opts) { var modules = opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'] ; // ensure that `start` is an absolute path at this point, // resolving against the process' current working directory start = path.resolve(start); var prefix = '/'; if (/^([A-Za-z]:)/.test(start)) { prefix = ''; } else if (/^\\\\/.test(start)) { prefix = '\\\\'; } var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/; var parts = start.split(splitRe); var dirs = []; for (var i = parts.length - 1; i >= 0; i--) { if (modules.indexOf(parts[i]) !== -1) continue; dirs = dirs.concat(modules.map(function(module_dir) { return prefix + path.join( path.join.apply(path, parts.slice(0, i + 1)), module_dir ); })); } if (process.platform === 'win32'){ dirs[dirs.length-1] = dirs[dirs.length-1].replace(":", ":\\"); } return dirs.concat(opts.paths); }
var path = require('path'); module.exports = function (start, opts) { var modules = opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'] ; var prefix = '/'; if (/^([A-Za-z]:)/.test(start)) { prefix = ''; } else if (/^\\\\/.test(start)) { prefix = '\\\\'; } var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/; // ensure that `start` is an absolute path at this point, // resolving against the process' current working directory start = path.resolve(start); var parts = start.split(splitRe); var dirs = []; for (var i = parts.length - 1; i >= 0; i--) { if (modules.indexOf(parts[i]) !== -1) continue; dirs = dirs.concat(modules.map(function(module_dir) { return prefix + path.join( path.join.apply(path, parts.slice(0, i + 1)), module_dir ); })); } if (process.platform === 'win32'){ dirs[dirs.length-1] = dirs[dirs.length-1].replace(":", ":\\"); } return dirs.concat(opts.paths); }
Fix regex so that it even passes for App.jsx
var babel = require('babel-jest'), jsPath = /.*\/react\-seed\/src\/js(?:\/[a-z]+)?(?:\/__tests__)?\/[a-zA-Z]+(?:\-test)?\.jsx?$/, lessPath = /.*\/react\-seed\/src\/less\/[a-z]+\/[a-zA-Z]+\.less$/; module.exports = { process: function(src, filename) { var dummyLessModule = 'module.exports = {dummy: true};'; if (jsPath.test(filename)) { src = src.replace(/^.*require\(\s*'styles(?:\/\w+)?\/\w+\.less'\s*\);/g, ''); src = src.replace(/^\s*import\s+'styles(?:\/\w+)?\/\w+\.less'\s*;/g, ''); return babel.process(src, filename); } else if (lessPath.test(filename)) { return dummyLessModule; } else { return src; } } };
var babel = require('babel-jest'), jsPath = /.*\/react\-seed\/src\/js(?:\/[a-z]+)?(?:\/__tests__)?\/[a-zA-Z]+(?:\-test)?\.jsx?$/, lessPath = /.*\/react\-seed\/src\/less\/[a-z]+\/[a-zA-Z]+\.less$/; module.exports = { process: function(src, filename) { var dummyLessModule = 'module.exports = {dummy: true};'; if (jsPath.test(filename)) { src = src.replace(/^.*require\(\s*'styles\/\w+\/\w+\.less'\s*\);/g, ''); src = src.replace(/^\s*import\s+'styles\/\w+\/\w+\.less'\s*;/g, ''); return babel.process(src, filename); } else if (lessPath.test(filename)) { return dummyLessModule; } else { return src; } } };
Handle mkdir error when directory exists
var ls = require('ls'); var fs = require('fs'); exports.generate = function(dir) { if(dir === undefined || dir === null) { dir = __dirname; } fs.mkdir(dir, 0777, function(err) { if(err && err.code != 'EEXIST') { return console.error(err); } var decks = ls(__dirname + "/decks/*.js"); for(var i = 0, len = decks.length; i < len; i++) { var json = require(decks[i].full).generate(); var out = JSON.stringify(json, null, 2); var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", ""); fs.writeFile(dir + "/" + filename + ".json", out, function(err) { if(err) { return console.log(err); } console.log(filename + " was saved!"); }); } }); } if(module.parent == null) { exports.generate(); }
var ls = require('ls'); var fs = require('fs'); exports.generate = function(dir) { if(dir === undefined || dir === null) { dir = __dirname; } fs.mkdir(dir); var decks = ls(__dirname + "/decks/*.js"); for(var i = 0, len = decks.length; i < len; i++) { var json = require(decks[i].full).generate(); var out = JSON.stringify(json, null, 2); var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", ""); fs.writeFile(dir + "/" + filename + ".json", out, function(err) { if(err) { return console.log(err); } console.log(filename + " was saved!"); }); } } if(module.parent == null) { exports.generate(); }
Increase repo size to 20Mb
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import json import logging.config import os from time import tzset VERSION = (0, 3, 0) __version__ = ".".join([str(s) for s in VERSION]) __title__ = "platformio-api" __description__ = ("An API for PlatformIO") __url__ = "https://github.com/ivankravets/platformio-api" __author__ = "Ivan Kravets" __email__ = "me@ikravets.com" __license__ = "MIT License" __copyright__ = "Copyright (C) 2014-2015 Ivan Kravets" config = dict( SQLALCHEMY_DATABASE_URI=None, GITHUB_LOGIN=None, GITHUB_PASSWORD=None, DL_PIO_DIR=None, DL_PIO_URL=None, MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb LOGGING=dict(version=1) ) assert "PIOAPI_CONFIG_PATH" in os.environ with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f: config.update(json.load(f)) # configure logging for packages logging.basicConfig() logging.config.dictConfig(config['LOGGING']) # setup time zone to UTC globally os.environ['TZ'] = "+00:00" tzset()
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import json import logging.config import os from time import tzset VERSION = (0, 3, 0) __version__ = ".".join([str(s) for s in VERSION]) __title__ = "platformio-api" __description__ = ("An API for PlatformIO") __url__ = "https://github.com/ivankravets/platformio-api" __author__ = "Ivan Kravets" __email__ = "me@ikravets.com" __license__ = "MIT License" __copyright__ = "Copyright (C) 2014-2015 Ivan Kravets" config = dict( SQLALCHEMY_DATABASE_URI=None, GITHUB_LOGIN=None, GITHUB_PASSWORD=None, DL_PIO_DIR=None, DL_PIO_URL=None, MAX_DLFILE_SIZE=1024*1024*10, LOGGING=dict(version=1) ) assert "PIOAPI_CONFIG_PATH" in os.environ with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f: config.update(json.load(f)) # configure logging for packages logging.basicConfig() logging.config.dictConfig(config['LOGGING']) # setup time zone to UTC globally os.environ['TZ'] = "+00:00" tzset()
Update Postgres test connection string
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.models import Base @pytest.fixture(scope="function") async def engine(): engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test") @pytest.fixture(scope="function") async def dbsession(engine, loop): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=engine) yield session async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.models import Base @pytest.fixture(scope="function") async def engine(): engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test") @pytest.fixture(scope="function") async def dbsession(engine, loop): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=engine) yield session async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
Remove other landing pages service
(function () { 'use strict'; angular .module('fusionSeedApp.services.landingPage', []) .factory('LandingPageService', LandingPageService); function LandingPageService($log, Orwell, $window, ConfigService) { 'ngInject'; activate(); var service = { getLandingPagesFromData: getLandingPagesFromData }; return service; ////////////// /** * This activate() is to redirect the window the first landing-page * in case redirect flag in appConfig * is `true`. */ function activate() { var resultsObservable = Orwell.getObservable('queryResults'); resultsObservable.addObserver(function (data) { var landing_pages = service.getLandingPagesFromData(data); if (angular.isArray(landing_pages) && ConfigService.getLandingPageRedirect()) { $window.location.assign(landing_pages[0]); } }); } /** * Extracts landing pages from Fusion response data. */ function getLandingPagesFromData(data) { return _.get(data, 'fusion.landing-pages'); } } })();
(function () { 'use strict'; angular .module('fusionSeedApp.services.landingPage', []) .factory('LandingPageService', LandingPageService); function LandingPageService($log, Orwell, $window, ConfigService) { 'ngInject'; activate(); var service = { getLandingPagesFromData: getLandingPagesFromData }; return service; ////////////// /** * This activate() is to redirect the window the first landing-page * in case redirect flag in appConfig * is `true`. */ function activate() { var resultsObservable = Orwell.getObservable('queryResults'); resultsObservable.addObserver(function (data) { var landing_pages = service.getLandingPagesFromData(data); $log.debug('landing_pages', landing_pages); if (angular.isArray(landing_pages) && ConfigService.getLandingPageRedirect()) { $window.location.assign(landing_pages[0]); } }); } /** * Extracts landing pages from Fusion response data. */ function getLandingPagesFromData(data) { return _.get(data, 'fusion.landing-pages'); } } })();
Remove unneeded switchOff function from forgot view
/* * Module dependencies. */ var template = require('./forgot-form'); var t = require('t'); var FormView = require('form-view'); var page = require('page'); /** * Expose ForgotView. */ module.exports = ForgotView; /** * Forgot password view * * @return {ForgotView} `ForgotView` instance. * @api public */ function ForgotView() { if (!(this instanceof ForgotView)) { return new ForgotView(); }; FormView.call(this, template); } /** * Extend from `FormView` */ FormView(ForgotView); ForgotView.prototype.switchOn = function() { this.on('success', this.bound('onsuccess')); this.on('error', this.bound('onerror')); }; /** * Show success message */ ForgotView.prototype.onsuccess = function() { var form = this.find('form'); var explanation = this.find('p.explanation-message'); var success = this.find('p.success-message'); form.addClass('hide'); explanation.addClass('hide'); success.removeClass('hide'); } /** * Handle errors */ ForgotView.prototype.onerror = function(error) { if ('notvalidated' === error.status) page('/signup/resend-validation-email'); };
/* * Module dependencies. */ var template = require('./forgot-form'); var t = require('t'); var FormView = require('form-view'); var page = require('page'); /** * Expose ForgotView. */ module.exports = ForgotView; /** * Forgot password view * * @return {ForgotView} `ForgotView` instance. * @api public */ function ForgotView() { if (!(this instanceof ForgotView)) { return new ForgotView(); }; FormView.call(this, template); } /** * Extend from `FormView` */ FormView(ForgotView); ForgotView.prototype.switchOn = function() { this.on('success', this.bound('onsuccess')); this.on('error', this.bound('onerror')); }; ForgotView.prototype.switchoff = function() { this.off('success', this.bound('onsuccess')); this.off('error', this.bound('onerror')); }; /** * Show success message */ ForgotView.prototype.onsuccess = function() { var form = this.find('form'); var explanation = this.find('p.explanation-message'); var success = this.find('p.success-message'); form.addClass('hide'); explanation.addClass('hide'); success.removeClass('hide'); } /** * Handle errors */ ForgotView.prototype.onerror = function(error) { if ('notvalidated' === error.status) page('/signup/resend-validation-email'); };
Increment version number for release
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.5", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "GNU Lesser General Public License (LGPL), Version 3", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.4", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "GNU Lesser General Public License (LGPL), Version 3", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
Use Ember.set instead of model.set
import Ember from 'ember'; export default function loadAll(model, relationship, dest, options = {}) { var page = options.page || 1; var query = { 'page[size]': 10, page: page }; query = Ember.merge(query, options || {}); Ember.set(model, 'query-params', query); return model.query(relationship, query).then(results => { dest.pushObjects(results.toArray()); var total = results.meta.pagination.total; var pageSize = results.meta.pagination.per_page; var remaining = total - (page * pageSize); if (remaining > 0) { query.page = page + 1; query['page[size]'] = pageSize; return loadAll(model, relationship, dest, query); } }); }
import Ember from 'ember'; export default function loadAll(model, relationship, dest, options = {}) { var page = options.page || 1; var query = { 'page[size]': 10, page: page }; query = Ember.merge(query, options || {}); model.set('query-params', query); return model.query(relationship, query).then(results => { dest.pushObjects(results.toArray()); var total = results.meta.pagination.total; var pageSize = results.meta.pagination.per_page; var remaining = total - (page * pageSize); if (remaining > 0) { query.page = page + 1; query['page[size]'] = pageSize; return loadAll(model, relationship, dest, query); } }); }
Apply oneworld-fix patch before testing connectivity Summary: Making the runner apply the necessary oneworld fix patch before running the tests. This can't be a long term solution, but at least means not getting that breaking change landed doesn't stop our tests from running. Since that change is only necessary for the tests, maybe we'll get away with fixing the update process before having to land it. Reviewed By: priteshrnandgaonkar Differential Revision: D10852110 fbshipit-source-id: b53a6d0ae9cb51e62cafc0c0f2cfe359ee6aff46
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import Server from '../server.js'; import LogManager from '../fb-stubs/Logger'; import reducers from '../reducers/index.js'; import configureStore from 'redux-mock-store'; import path from 'path'; import os from 'os'; import fs from 'fs'; let server; const mockStore = configureStore([])(reducers(undefined, {type: 'INIT'})); beforeAll(() => { // create config directory, which is usually created by static/index.js const flipperDir = path.join(os.homedir(), '.flipper'); if (!fs.existsSync(flipperDir)) { fs.mkdirSync(flipperDir); } server = new Server(new LogManager(), mockStore); return server.init(); }); test( 'Device can connect successfully', done => { var testFinished = false; server.addListener('new-client', (client: Client) => { console.debug('new-client ' + new Date().toString()); setTimeout(() => { testFinished = true; done(); }, 5000); }); server.addListener('removed-client', (id: string) => { console.debug('removed-client ' + new Date().toString()); if (!testFinished) { done.fail('client disconnected too early'); } }); }, 20000, ); afterAll(() => { return server.close(); });
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import Server from '../server.js'; import LogManager from '../fb-stubs/Logger'; import reducers from '../reducers/index.js'; import configureStore from 'redux-mock-store'; import path from 'path'; import os from 'os'; import fs from 'fs'; let server; const mockStore = configureStore([])(reducers(undefined, {type: 'INIT'})); beforeAll(() => { // create config directory, which is usually created by static/index.js const flipperDir = path.join(os.homedir(), '.flipper'); if (!fs.existsSync(flipperDir)) { fs.mkdirSync(flipperDir); } server = new Server(new LogManager(), mockStore); return server.init(); }); test.skip( 'Device can connect successfully', done => { var testFinished = false; server.addListener('new-client', (client: Client) => { console.debug('new-client ' + new Date().toString()); setTimeout(() => { testFinished = true; done(); }, 5000); }); server.addListener('removed-client', (id: string) => { console.debug('removed-client ' + new Date().toString()); if (!testFinished) { done.fail('client disconnected too early'); } }); }, 20000, ); afterAll(() => { return server.close(); });
Fix test case being unable to fail
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, **kwargs): sleep = kwargs.pop('sleep', DEFAULT_SLEEP) expected_return = kwargs.pop('expected_return', None) call = kwargs.pop('call', True) def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, **kwargs): sleep = kwargs.pop('sleep', DEFAULT_SLEEP) expected_return = kwargs.pop('expected_return', None) call = kwargs.pop('call', True) def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) else: raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
Add index.json to content fetch path to be able to omit url rewriting
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { init } from './redux/page'; import Page from './components/Page'; class FrontendApp extends Component { componentWillMount() { const path = window.location.pathname; const options = { mode: 'no-cors' }; fetch(`/api${path}/index.json`, options) .then(res => res.json()) .then(json => this.props.initPage(json)) .catch(err => console.error(`Unable to parse content for "${path}".`, err)) } render() { const { children:blocks = [] } = this.props.page; return ( <Page blocks={blocks} /> ) } } FrontendApp.propTypes = { page: PropTypes.object, init: PropTypes.func, }; export default connect( (state) => ({ page: state.page, }), { initPage: init } )(FrontendApp);
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { init } from './redux/page'; import Page from './components/Page'; class FrontendApp extends Component { componentWillMount() { const path = window.location.pathname; const options = { mode: 'no-cors' }; fetch(`/api${path}`, options) .then(res => res.json()) .then(json => this.props.initPage(json)) .catch(err => console.error(`Unable to parse content for "${path}".`, err)) } render() { const { children:blocks = [] } = this.props.page; return ( <Page blocks={blocks} /> ) } } FrontendApp.propTypes = { page: PropTypes.object, init: PropTypes.func, }; export default connect( (state) => ({ page: state.page, }), { initPage: init } )(FrontendApp);
Fix content type bug (415 error from server). - The server doesn't recognize the POST as type application/json, but adding an empty JSON object {} solves that.
'use strict'; angular.module('confRegistrationWebApp') .factory('currentRegistrationInterceptor', function ($q, $injector) { return { 'responseError': function (rejection) { var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/; if (rejection.status === 404 && regExp.test(rejection.config.url)) { var url = rejection.config.url.split('/'); if (_.isEmpty(_.last(url))) { url.pop(); } url.pop(); return $injector.get('$http').post(url.join('/'), {}); } return $q.reject(rejection); } }; });
'use strict'; angular.module('confRegistrationWebApp') .factory('currentRegistrationInterceptor', function ($q, $injector) { return { 'responseError': function (rejection) { var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/; if (rejection.status === 404 && regExp.test(rejection.config.url)) { var url = rejection.config.url.split('/'); if (_.isEmpty(_.last(url))) { url.pop(); } url.pop(); return $injector.get('$http').post(url.join('/')); } return $q.reject(rejection); } }; });
Remove superfluous class from importer
import os import imp modules = {} def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future names = os.listdir(path) for name in names: if not name.endswith(".py"): continue print("Importing module {0}".format(name)) name = name.split('.')[0] try: new_module = imp.load_source(name, path) modules[name] = new_module except ImportError as e: print("Error importing module {0} from directory {1}".format(name,os.getcwd())) print(e) continue print("Success") load_modules()
import os class loader: modules = {}; def __init__(self): self.load_modules(); def load_modules(self, path="./modules/"): # Consider adding recursive sorting at some point in the future names = os.listdir(path); pwd = os.getcwd(); os.chdir(path); for name in names: print("Importing module {0}".format(name)); name = name.split('.')[0]; try: new_module = __import__(name); self.modules[name] = new_module; except ImportError: print("Error importing module {0}".format(name)); continue; print("Success"); os.chdir(pwd);
Reduce the displayed channels to top 12
import axios from 'axios'; // get top twitch channels export const GET_CHANNELS = 'GET_CHANNELS'; export function getChannels() { const request = axios.get('https://api.twitch.tv/kraken/streams?api_version=3&limit=12'); return { type: GET_CHANNELS, payload: request, }; } // set the currently active channel export const SET_CHANNEL = 'SET_CHANNEL'; export function setChannel(channel) { const request = axios.post('api/channels/subscribe', channel); return { type: SET_CHANNEL, payload: request, }; } // set the currently active channel to null export const UNSET_CHANNEL = 'UNSET_CHANNEL'; export function unsetChannel() { return { type: UNSET_CHANNEL, payload: null, }; } export const GET_TONE = 'GET_TONE'; export function getTone(data) { const request = axios.put('api/watson/tone', data); return { type: GET_TONE, payload: request, }; } export const UNSET_TONE = 'UNSET_TONE'; export function unsetTone() { return { type: UNSET_TONE, payload: null, }; }
import axios from 'axios'; // get top twitch channels export const GET_CHANNELS = 'GET_CHANNELS'; export function getChannels() { const request = axios.get('https://api.twitch.tv/kraken/streams?api_version=3&limit=25'); return { type: GET_CHANNELS, payload: request, }; } // set the currently active channel export const SET_CHANNEL = 'SET_CHANNEL'; export function setChannel(channel) { const request = axios.post('api/channels/subscribe', channel); return { type: SET_CHANNEL, payload: request, }; } // set the currently active channel to null export const UNSET_CHANNEL = 'UNSET_CHANNEL'; export function unsetChannel() { return { type: UNSET_CHANNEL, payload: null, }; } export const GET_TONE = 'GET_TONE'; export function getTone(data) { const request = axios.put('api/watson/tone', data); return { type: GET_TONE, payload: request, }; } export const UNSET_TONE = 'UNSET_TONE'; export function unsetTone() { return { type: UNSET_TONE, payload: null, }; }
Make sure method call return type is passed by ref
<?php namespace Psalm\Plugin\Hook; use PhpParser\Node\Expr; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\StaticCall; use Psalm\Codebase; use Psalm\Context; use Psalm\FileManipulation; use Psalm\StatementsSource; use Psalm\Type\Union; interface AfterMethodCallAnalysisInterface { /** * @param MethodCall|StaticCall $expr * @param FileManipulation[] $file_replacements * * @return void */ public static function afterMethodCallAnalysis( Expr $expr, string $method_id, string $appearing_method_id, string $declaring_method_id, Context $context, StatementsSource $statements_source, Codebase $codebase, array &$file_replacements = [], Union &$return_type_candidate = null ); }
<?php namespace Psalm\Plugin\Hook; use PhpParser\Node\Expr; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\StaticCall; use Psalm\Codebase; use Psalm\Context; use Psalm\FileManipulation; use Psalm\StatementsSource; use Psalm\Type\Union; interface AfterMethodCallAnalysisInterface { /** * @param MethodCall|StaticCall $expr * @param FileManipulation[] $file_replacements * * @return void */ public static function afterMethodCallAnalysis( Expr $expr, string $method_id, string $appearing_method_id, string $declaring_method_id, Context $context, StatementsSource $statements_source, Codebase $codebase, array &$file_replacements = [], Union $return_type_candidate = null ); }
Fix theme colors & drawable on Android 8 Oreo
package org.mtransit.android.commons; import org.mtransit.android.commons.api.SupportFactory; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.TypedValue; public final class ThemeUtils { public static int resolveColorAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return SupportFactory.get().getColor(context.getResources(), tv.resourceId, context.getTheme()); } public static float resolveDimensionAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return context.getResources().getDimension(tv.resourceId); } public static Drawable resolveDrawableAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return SupportFactory.get().getResourcesDrawable(context.getResources(), tv.resourceId, context.getTheme()); } private static TypedValue resolveAttribute(Context context, int attrId) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(attrId, tv, true); return tv; } public static Drawable obtainStyledDrawable(Context themedContext, int attrId) { int[] attrs = new int[] { attrId }; TypedArray ta = themedContext.obtainStyledAttributes(attrs); Drawable drawableFromTheme = ta.getDrawable(0); ta.recycle(); return drawableFromTheme; } }
package org.mtransit.android.commons; import org.mtransit.android.commons.api.SupportFactory; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.TypedValue; public final class ThemeUtils { public static int resolveColorAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return SupportFactory.get().getColor(context.getResources(), tv.resourceId, null); } public static float resolveDimensionAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return context.getResources().getDimension(tv.resourceId); } public static Drawable resolveDrawableAttribute(Context context, int attrId) { TypedValue tv = resolveAttribute(context, attrId); return SupportFactory.get().getResourcesDrawable(context.getResources(), tv.resourceId, null); } private static TypedValue resolveAttribute(Context context, int attrId) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(attrId, tv, true); return tv; } public static Drawable obtainStyledDrawable(Context themedContext, int attrId) { int[] attrs = new int[] { attrId }; TypedArray ta = themedContext.obtainStyledAttributes(attrs); Drawable drawableFromTheme = ta.getDrawable(0); ta.recycle(); return drawableFromTheme; } }
Use correct vue library for SSR
var path = require('path') var utils = require('./utils') var webpack = require('webpack') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') baseWebpackConfig.plugins = [] delete baseWebpackConfig.resolve.alias['vue$'] var webpackConfig = merge(baseWebpackConfig, { entry: './webpack/server.js', module: { loaders: utils.styleLoaders({ sourceMap: false, extract: false }) }, target: 'node', output: { path: path.resolve(__dirname, '../../renderer'), libraryTarget: 'commonjs2', filename: 'bundle.server.js' }, vue: { loaders: utils.cssLoaders({ sourceMap: false, extract: false }) }, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': '"production"' }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin(), ] }) module.exports = webpackConfig
var path = require('path') var utils = require('./utils') var webpack = require('webpack') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') baseWebpackConfig.plugins = [] var webpackConfig = merge(baseWebpackConfig, { entry: './webpack/server.js', module: { loaders: utils.styleLoaders({ sourceMap: false, extract: false }) }, target: 'node', output: { path: path.resolve(__dirname, '../../renderer'), libraryTarget: 'commonjs2', filename: 'bundle.server.js' }, vue: { loaders: utils.cssLoaders({ sourceMap: false, extract: false }) }, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': '"production"' }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin(), ] }) module.exports = webpackConfig
Make use of MarkdownLanguageConfig constants
package flow.netbeans.markdown.highlighter; import flow.netbeans.markdown.csl.MarkdownLanguageConfig; import java.util.Collection; import java.util.EnumSet; import org.netbeans.spi.lexer.LanguageHierarchy; import org.netbeans.spi.lexer.Lexer; import org.netbeans.spi.lexer.LexerRestartInfo; public class MarkdownLanguageHierarchy extends LanguageHierarchy<MarkdownTokenId> { @Override protected synchronized Collection<MarkdownTokenId> createTokenIds () { return EnumSet.allOf (MarkdownTokenId.class); } @Override protected Lexer<MarkdownTokenId> createLexer (LexerRestartInfo<MarkdownTokenId> info) { return new MarkdownLexer(info); } @Override protected String mimeType () { return MarkdownLanguageConfig.MIME_TYPE; } }
package flow.netbeans.markdown.highlighter; import java.util.Collection; import java.util.EnumSet; import org.netbeans.spi.lexer.LanguageHierarchy; import org.netbeans.spi.lexer.Lexer; import org.netbeans.spi.lexer.LexerRestartInfo; public class MarkdownLanguageHierarchy extends LanguageHierarchy<MarkdownTokenId> { @Override protected synchronized Collection<MarkdownTokenId> createTokenIds () { return EnumSet.allOf (MarkdownTokenId.class); } @Override protected Lexer<MarkdownTokenId> createLexer (LexerRestartInfo<MarkdownTokenId> info) { return new MarkdownLexer(info); } @Override protected String mimeType () { return "text/x-markdown"; } }
Tweak padding on summary text
(function() { window.shared || (window.shared = {}); var dom = window.shared.ReactHelpers.dom; var createEl = window.shared.ReactHelpers.createEl; var merge = window.shared.ReactHelpers.merge; var PropTypes = window.shared.PropTypes; var styles = { caption: { marginRight: 5 }, value: { fontWeight: 'bold' }, sparklineContainer: { paddingLeft: 15, paddingRight: 15 }, textContainer: { paddingBottom: 5 } }; var AcademicSummary = window.shared.AcademicSummary = React.createClass({ displayName: 'AcademicSummary', propTypes: { caption: React.PropTypes.string.isRequired, value: PropTypes.nullable(React.PropTypes.number.isRequired), sparkline: React.PropTypes.element.isRequired }, render: function() { return dom.div({ className: 'AcademicSummary' }, dom.div({ style: styles.textContainer }, dom.span({ style: styles.caption }, this.props.caption + ':'), dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value) ), dom.div({ style: styles.sparklineContainer }, this.props.sparkline) ); } }); })();
(function() { window.shared || (window.shared = {}); var dom = window.shared.ReactHelpers.dom; var createEl = window.shared.ReactHelpers.createEl; var merge = window.shared.ReactHelpers.merge; var PropTypes = window.shared.PropTypes; var styles = { caption: { marginRight: 5 }, value: { fontWeight: 'bold' }, sparklineContainer: { paddingLeft: 15, paddingRight: 15 } }; var AcademicSummary = window.shared.AcademicSummary = React.createClass({ displayName: 'AcademicSummary', propTypes: { caption: React.PropTypes.string.isRequired, value: PropTypes.nullable(React.PropTypes.number.isRequired), sparkline: React.PropTypes.element.isRequired }, render: function() { return dom.div({ className: 'AcademicSummary' }, dom.div({}, dom.span({ style: styles.caption }, this.props.caption + ':'), dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value) ), dom.div({ style: styles.sparklineContainer }, this.props.sparkline) ); } }); })();
Add debugging println to show content of spreadsheet on the console.
package main import ( "encoding/json" "fmt" "io/ioutil" "github.com/pilu/traffic" "github.com/tealeg/xlsx" ) type ExcelData struct { DocumentName string Sheets [][][]string } func excelResponse(w traffic.ResponseWriter, r *traffic.Request) { file, handler, err := r.FormFile("file") if err != nil { fmt.Println(err) } data, err := ioutil.ReadAll(file) if err != nil { fmt.Println(err) } fmt.Print("Filename: ") fmt.Println(handler.Filename) xlFile, err := xlsx.OpenBinary(data) if err != nil { fmt.Println(err) } excelData := ExcelData{DocumentName: handler.Filename} excelData.Sheets, err = xlFile.ToSlice() if err != nil { fmt.Println(err) } fmt.Println(excelData) enc := json.NewEncoder(w) enc.Encode(excelData) } func APIHandler(w traffic.ResponseWriter, r *traffic.Request) { params := r.URL.Query() call := params.Get("call") if call == "conversion" { excelResponse(w, r); } }
package main import ( "encoding/json" "fmt" "io/ioutil" "github.com/pilu/traffic" "github.com/tealeg/xlsx" ) type ExcelData struct { DocumentName string Sheets [][][]string } func excelResponse(w traffic.ResponseWriter, r *traffic.Request) { file, handler, err := r.FormFile("file") if err != nil { fmt.Println(err) } data, err := ioutil.ReadAll(file) if err != nil { fmt.Println(err) } fmt.Print("Filename: ") fmt.Println(handler.Filename) xlFile, err := xlsx.OpenBinary(data) if err != nil { fmt.Println(err) } excelData := ExcelData{DocumentName: handler.Filename} excelData.Sheets, err = xlFile.ToSlice() if err != nil { fmt.Println(err) } enc := json.NewEncoder(w) enc.Encode(excelData) } func APIHandler(w traffic.ResponseWriter, r *traffic.Request) { params := r.URL.Query() call := params.Get("call") if call == "conversion" { excelResponse(w, r); } }
Rename 'URL' to 'link' to match with .link property
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Script for displaying pretty RSS feeds # from sys import argv import feedparser # Data for parsing data = feedparser.parse(argv[1]) # Display core feed properties print "\n\033[1mFeed title:\033[0m", data.feed.title if "description" in data.feed: if len(data.feed.description) > 59: data.feed.description = data.feed.description[:59] + "..." print "\033[1mFeed description:\033[0m", data.feed.description print "\033[1mFeed link:\033[0m", data.feed.link # Display core items properties print "\n\033[1mFeed entries:\033[0m\n" for item in data.entries: print " \033[1mEntry title:\033[0m", item.title if "description" in item: if len(item.description) > 54: item.description = item.description[:54] + "..." print " \033[1mEntry description:\033[0m", item.description print " \033[1mEntry link:\033[0m", item.link, "\n"
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Script for displaying pretty RSS feeds # from sys import argv import feedparser # Data for parsing data = feedparser.parse(argv[1]) # Display core feed properties print "\n\033[1mFeed title:\033[0m", data.feed.title if "description" in data.feed: if len(data.feed.description) > 59: data.feed.description = data.feed.description[:59] + "..." print "\033[1mFeed description:\033[0m", data.feed.description print "\033[1mFeed URL:\033[0m", data.feed.link # Display core items properties print "\n\033[1mFeed entries:\033[0m\n" for item in data.entries: print " \033[1mEntry title:\033[0m", item.title if "description" in item: if len(item.description) > 54: item.description = item.description[:54] + "..." print " \033[1mEntry description:\033[0m", item.description print " \033[1mEntry URL:\033[0m", item.link, "\n"
Update id of list element container
(function($) { $().ready(function() { var ANIMATION_SPEED = 250; $('body').addClass('js'); // DMs on the Settings page $('#user_enable_dms').click(function(event) { $('#dm-priority-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_dms:checked').length == 1) $('#dm-priority-container').show(); // Mentions on the Settings page $('#user_enable_mentions').click(function(event) { $('#mention-priority-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_mentions:checked').length == 1) $('#mention-priority-container').show(); // Lists on the Settings page $('#user_enable_list').click(function(event) { $('#list-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_list:checked').length == 1) $('#list-container').show(); }); })(jQuery);
(function($) { $().ready(function() { var ANIMATION_SPEED = 250; $('body').addClass('js'); // DMs on the Settings page $('#user_enable_dms').click(function(event) { $('#dm-priority-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_dms:checked').length == 1) $('#dm-priority-container').show(); // Mentions on the Settings page $('#user_enable_mentions').click(function(event) { $('#mention-priority-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_mentions:checked').length == 1) $('#mention-priority-container').show(); // Lists on the Settings page $('#user_enable_list').click(function(event) { $('#list-priority-container').slideToggle(ANIMATION_SPEED); }); if ($('#user_enable_list:checked').length == 1) $('#list-priority-container').show(); }); })(jQuery);
Fix crash when URL is provided.
import argparse, json, os.path import jinja2, requests def main(): parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", default="swagger.json", help="path to or URL of the Swagger JSON file (default: swagger.json)", metavar="SWAGGER_LOCATION" ) parser.add_argument( "-o", "--output", default="swagger.md", help="path to the output Markdown file (default: swagger.md)", metavar="OUTPUT" ) parser.add_argument( "-t", "--template", default=os.path.join(os.path.dirname(__file__), "swagger.md.j2"), help="Jinja2 template used for conversion", metavar="TEMPLATE" ) args = parser.parse_args() try: swagger_data = json.load(open(args.input, encoding="utf8")) except (FileNotFoundError, OSError): swagger_data = requests.get(args.input).json() template = jinja2.Template(open(args.template, encoding="utf8").read()) with open(args.output, "w", encoding="utf8") as output: output.write(template.render(swagger_data=swagger_data))
import argparse, json, os.path import jinja2, requests def main(): parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", default="swagger.json", help="path to or URL of the Swagger JSON file (default: swagger.json)", metavar="SWAGGER_LOCATION" ) parser.add_argument( "-o", "--output", default="swagger.md", help="path to the output Markdown file (default: swagger.md)", metavar="OUTPUT" ) parser.add_argument( "-t", "--template", default=os.path.join(os.path.dirname(__file__), "swagger.md.j2"), help="Jinja2 template used for conversion", metavar="TEMPLATE" ) args = parser.parse_args() try: swagger_data = json.load(open(args.input, encoding="utf8")) except FileNotFoundError: swagger_data = requests.get(args.input).json() template = jinja2.Template(open(args.template, encoding="utf8").read()) with open(args.output, "w", encoding="utf8") as output: output.write(template.render(swagger_data=swagger_data))
Update keyword and asset_url fields to accept arrays. Resolves #16
'use strict'; exports.up = function(knex, Promise) { return knex.schema. createTable('paths', function (t) { t.increments('id'); t.text('curator').notNullable(); t.text('curator_org'); t.specificType('collaborators', 'text[]'); t.text('name').notNullable(); t.text('description'); t.text('version').notNullable(); t.text('license'); t.text('image_url'); t.specificType('asset_urls', 'text[]'); t.specificType('keywords', 'text[]'); t.timestamp('created').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP')); }); }; exports.down = function(knex, Promise) { return knex.schema.dropTableIfExists('paths'); };
'use strict'; exports.up = function(knex, Promise) { return knex.schema. createTable('paths', function (t) { t.increments('id'); t.text('curator').notNullable(); t.text('curator_org'); t.specificType('collaborators', 'text[]'); t.text('name').notNullable(); t.text('description'); t.text('version').notNullable(); t.text('license'); t.text('image_url'); t.text('asset_urls'); t.text('keywords'); t.timestamp('created').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP')); }); }; exports.down = function(knex, Promise) { return knex.schema.dropTableIfExists('paths'); };
Add missing import and explanation of failure
import numpy as np import sys try: import statsmodels.api as sm except ImportError: print "Example requires statsmodels" sys.exit(0) from pymc import * # Generate data size = 50 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size) # Add outliers x = np.append(x, [.1, .15, .2]) y = np.append(y, [8, 6, 9]) data_outlier = dict(x=x, y=y) with Model() as model: family = glm.families.T(link=glm.links.Identity, priors={'nu': 1.5, 'lam': ('sigma', Uniform.dist(0, 20))}) glm.glm('y ~ x', data_outlier, family=family) def run(n=2000): if n == "short": n = 50 import matplotlib.pyplot as plt with model: trace = sample(n, Slice(model.vars)) plt.plot(x, y, 'x') glm.plot_posterior_predictive(trace) plt.show() if __name__ == '__main__': run()
import numpy as np try: import statsmodels.api as sm except ImportError: sys.exit(0) from pymc import * # Generate data size = 50 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size) # Add outliers x = np.append(x, [.1, .15, .2]) y = np.append(y, [8, 6, 9]) data_outlier = dict(x=x, y=y) with Model() as model: family = glm.families.T(link=glm.links.Identity, priors={'nu': 1.5, 'lam': ('sigma', Uniform.dist(0, 20))}) glm.glm('y ~ x', data_outlier, family=family) def run(n=2000): if n == "short": n = 50 import matplotlib.pyplot as plt with model: trace = sample(n, Slice(model.vars)) plt.plot(x, y, 'x') glm.plot_posterior_predictive(trace) plt.show() if __name__ == '__main__': run()
Convert binary string to UTF-8
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
Update the PyPI version to 0.2.19.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.19', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.18', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Improve comments in vtkjs example
// Fetch the dataset from the server $.ajax({url: 'capitals.json'}).done(function (capitals) { // Create a map object with reasonable center and zoom level var map = geo.map({ node: '#map', center: {x: 0, y: 0}, zoom: 2.5, clampBoundsX: false, clampBoundsY: false, clampZoom: false, discreteZoom: false }); // Add the map tile layer map.createLayer('osm', { zIndex: 0, minLevel: 4, keepLower: true, wrapX: false, wrapY: false }); // Create a vtk point feature layer var vtkLayer = map.createLayer('feature', { renderer: 'vtkjs' }); vtkLayer.createFeature('point', { selectionAPI: true, style: { radius: 100, // sphere radius (~0.1km) fillColor: 'red', fillOpacity: Math.random } }) // Bind the dataset to the vtk layer .data(capitals) .position(function (d) { return {x: d.longitude, y: d.latitude}; // position accessor }) .draw(); });
$.ajax({url: 'capitals.json'}).done(function (capitals) { // Create a map object with reasonable center and zoom level var map = geo.map({ node: '#map', center: {x: 0, y: 0}, zoom: 2.5, clampBoundsX: false, clampBoundsY: false, clampZoom: false, discreteZoom: false }); // Add the tile layer with the specified parameters map.createLayer('osm', { zIndex: 0, minLevel: 4, keepLower: true, wrapX: false, wrapY: false }); // Create a vtk point feature layer var vtkLayer = map.createLayer('feature', { renderer: 'vtkjs' }); vtkLayer.createFeature('point', { selectionAPI: true, style: { radius: 100, // sphere radius (~0.1km) fillColor: 'red', fillOpacity: Math.random } }) .data(capitals) // bind data .position(function (d) { return {x: d.longitude, y: d.latitude}; // position accessor }) .draw(); });
Fix extension to work with latest state changes Refs flarum/core#2150.
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionListState from 'flarum/states/DiscussionListState'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = this.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionListState.prototype, 'requestParams', function(params) { if (this.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionList from 'flarum/components/DiscussionList'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = this.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionList.prototype, 'requestParams', function(params) { if (this.props.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
Add missing cred-alert-worker-ng build test Signed-off-by: Kalai Wei <920bf42fdcab8ffc364d94066818a17cd391003a@pivotal.io>
package main_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "testing" ) func TestBinaries(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Binaries Suite") } var _ = AfterSuite(func() { gexec.CleanupBuildArtifacts() }) var _ = Describe("Binaries", func() { It("builds cred-alert-worker-ng", func() { _, err := gexec.Build("cred-alert/cmd/cred-alert-worker-ng") Expect(err).NotTo(HaveOccurred()) }) It("builds cred-alert-ingestor", func() { _, err := gexec.Build("cred-alert/cmd/cred-alert-ingestor") Expect(err).NotTo(HaveOccurred()) }) It("builds cred-alert-worker", func() { _, err := gexec.Build("cred-alert/cmd/cred-alert-worker") Expect(err).NotTo(HaveOccurred()) }) It("builds stats-monitor", func() { _, err := gexec.Build("cred-alert/cmd/stats-monitor") Expect(err).NotTo(HaveOccurred()) }) })
package main_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "testing" ) func TestBinaries(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Binaries Suite") } var _ = AfterSuite(func() { gexec.CleanupBuildArtifacts() }) var _ = Describe("Binaries", func() { It("builds cred-alert-ingestor", func() { _, err := gexec.Build("cred-alert/cmd/cred-alert-ingestor") Expect(err).NotTo(HaveOccurred()) }) It("builds cred-alert-worker", func() { _, err := gexec.Build("cred-alert/cmd/cred-alert-worker") Expect(err).NotTo(HaveOccurred()) }) It("builds stats-monitor", func() { _, err := gexec.Build("cred-alert/cmd/stats-monitor") Expect(err).NotTo(HaveOccurred()) }) })
Add example code and tidy up other parts of file
/* Author: TMW - (Author Name Here) */ // Create a closure to maintain scope of the '$' and TMW ;(function (TMW, $) { $(function() { // Any globals go here in CAPS (but avoid if possible) // follow a singleton pattern // (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript) TMW.Config.init(); });// END DOC READY /* Optional triggers // WINDOW.LOAD $(window).load(function() { }); // WINDOW.RESIZE $(window).resize(function() { }); */ TMW.Config = { variableX : '', // please don't keep me - only for example syntax! init : function () { console.debug('Kickoff is running'); } }; // Example module /* TMW.Ui = { init : function() { TMW.Ui.modal(); }, modal : function() { } }; */ })(window.TMW = window.TMW || {}, jQuery);
/* Author: TMW - (Author Name Here) */ // Create a closure to maintain scope of the '$' and TMW (function (TMW, $) { $(function() { // Any globals go here in CAPS (but avoid if possible) // follow a singleton pattern // (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript) TMW.SiteSetup.init(); });// END DOC READY /* optional triggers // WINDOW.LOAD $(window).load(function() { }); // WINDOW.RESIZE $(window).resize(function() { }); */ TMW.SiteSetup = { variableX : '', // please don't keep me - only for example syntax! init : function () { console.debug('Kickoff is running'); } }; })(window.TMW = window.TMW || {}, jQuery);
Mark as compatible for python 2.7, 3.3 and 3.4 Add `classifiers` parameter to `setup` function call in `setup.py` file.
# -*- coding: utf-8 -*- from distutils.core import setup readme_file = open('README.rst') setup( name='django-db-file-storage', version='0.3.1', author='Victor Oliveira da Silva', author_email='victor_o_silva@hotmail.com', packages=['db_file_storage'], url='https://github.com/victor-o-silva/db_file_storage', download_url='https://github.com/victor-o-silva/db_file_storage' '/tarball/0.3.1', license='GNU GPL v3', description="Custom FILE_STORAGE for Django. Saves files " "in your database instead of your file system.", long_description=readme_file.read(), install_requires=[ "Django", ], classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], ) readme_file.close()
# -*- coding: utf-8 -*- from distutils.core import setup readme_file = open('README.rst') setup( name='django-db-file-storage', version='0.3.1', author='Victor Oliveira da Silva', author_email='victor_o_silva@hotmail.com', packages=['db_file_storage'], url='https://github.com/victor-o-silva/db_file_storage', download_url='https://github.com/victor-o-silva/db_file_storage' '/tarball/0.3.1', license='GNU GPL v3', description="Custom FILE_STORAGE for Django. Saves files " "in your database instead of your file system.", long_description=readme_file.read(), install_requires=[ "Django", ], ) readme_file.close()
Refactor to better inject values into path items
import os import subprocess import sys import signal import itertools def _build_env(target): """ Prepend target and .pth references in target to PYTHONPATH """ env = dict(os.environ) suffix = env.get('PYTHONPATH') prefix = target, items = itertools.chain( prefix, (suffix,) if suffix else (), ) joined = os.pathsep.join(items) env['PYTHONPATH'] = joined return env def with_path(target, params): """ Launch Python with target on the path and params """ def null_handler(signum, frame): pass signal.signal(signal.SIGINT, null_handler) cmd = [sys.executable] + params subprocess.Popen(cmd, env=_build_env(target)).wait() def with_path_overlay(target, params): """ Overlay Python with target on the path and params """ cmd = [sys.executable] + params os.execve(sys.executable, cmd, _build_env(target))
import os import subprocess import sys import signal def _build_env(target): """ Prepend target to PYTHONPATH """ env = dict(os.environ) suffix = env.get('PYTHONPATH', '') prefix = target joined = os.pathsep.join([prefix, suffix]).rstrip(os.pathsep) env['PYTHONPATH'] = joined return env def with_path(target, params): """ Launch Python with target on the path and params """ def null_handler(signum, frame): pass signal.signal(signal.SIGINT, null_handler) cmd = [sys.executable] + params subprocess.Popen(cmd, env=_build_env(target)).wait() def with_path_overlay(target, params): """ Overlay Python with target on the path and params """ cmd = [sys.executable] + params os.execve(sys.executable, cmd, _build_env(target))
Fix page /pipe 's error.
// server.js /**IMPORT**/ var express = require('express'); var url = require('url'); var inject_piper = require('./inject-piper.js'); /** SET **/ var app = express(); /**FUNCTION**/ function sendViewMiddleware(req, res, next) { //send .html res.sendHtml = function(html) { return res.sendFile(__dirname + "/" + html); } next(); } app.use(sendViewMiddleware); /**GET**/ app.get('/', function (req, res) { //主页 console.log("[SERVER][GET] /"); res.sendHtml('index.html'); }); app.get('/pipe', function (req, res) { //pipe console.log("[SERVER][GET] /pipe"); var params = url.parse(req.url,true).query; if (params.length>0){ console.log(params); var href = params['href'] inject_piper.pipe(href,function(html){ res.send(html); }); }else{ res.sendHtml('index.html'); } }); /**启动服务器**/ var server = app.listen(10000, function () { var host = server.address().address var port = server.address().port console.log("Sever Start @ http://%s:%s", host, port) }); //于指定端口启动服务器
// server.js /**IMPORT**/ var express = require('express'); var url = require('url'); var inject_pipe = require('./inject-pipe.js'); /** SET **/ var app = express(); /**FUNCTION**/ function sendViewMiddleware(req, res, next) { //send .html res.sendHtml = function(html) { return res.sendFile(__dirname + "/" + html); } next(); } app.use(sendViewMiddleware); /**GET**/ app.get('/', function (req, res) { //主页 console.log("[SERVER][GET] /"); res.sendHtml('index.html'); }); app.get('/pipe', function (req, res) { //pipe console.log("[SERVER][GET] /pipe"); var params = url.parse(req.url,true).query; console.log(params); var href = params['href'] inject_pipe.pipe(href,function(html){ res.send(html); }); }); /**启动服务器**/ var server = app.listen(10000, function () { var host = server.address().address var port = server.address().port console.log("Sever Start @ http://%s:%s", host, port) }); //于指定端口启动服务器
Adjust logging and fix module documentation
"""Remove the profiles. Copyright (c) 2015 Francesco Montesano MIT Licence """ import shutil import dodocs.logger as dlog import dodocs.utils as dutils def remove(args): """Remove profile(s) Parameters ---------- args : namespace parsed command line arguments """ log = dlog.getLogger() for name in args.name: dlog.set_profile(name) profile_dir = dutils.profile_dir(name) if not profile_dir.exists(): log.warn("Profile does not exist") continue log.debug("Removing profile") try: if profile_dir.is_symlink(): realpath = profile_dir.resolve() profile_dir.unlink() shutil.rmtree(str(realpath)) else: shutil.rmtree(str(profile_dir)) except FileNotFoundError: log.error("The removal of profile failed", exc_info=True) log.info("profile removed")
"""Create the profile. Copyright (c) 2015 Francesco Montesano MIT Licence """ import shutil import dodocs.logger as dlog import dodocs.utils as dutils def remove(args): """Remove profile(s) Parameters ---------- args : namespace parsed command line arguments """ log = dlog.getLogger() for name in args.name: dlog.set_profile(name) log.debug("Removing profile") profile_dir = dutils.profile_dir(name) if not profile_dir.exists(): log.warn("Profile does not exist") continue try: if profile_dir.is_symlink(): realpath = profile_dir.resolve() profile_dir.unlink() shutil.rmtree(str(realpath)) else: shutil.rmtree(str(profile_dir)) except FileNotFoundError: log.error("The removal of profile failed", exc_info=True) log.info("profile removed")
Fix test group for NotFoundException
<?php namespace Veles\Tests\Routing\Exceptions; use Veles\Routing\Exceptions\NotFoundException; /** * Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52. * @group route */ class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase { /** * @var NotFoundException */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new NotFoundException; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } public function testConstruct() { $result = $this->object->getCode(); $msg = 'NotFoundException::__construct() wrong behavior!'; $this->assertSame(0, $result, $msg); } }
<?php namespace Veles\Tests\Routing\Exceptions; use Veles\Routing\Exceptions\NotFoundException; /** * Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52. * @group Dev */ class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase { /** * @var NotFoundException */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new NotFoundException; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } public function testConstruct() { $result = $this->object->getCode(); $msg = 'NotFoundException::__construct() wrong behavior!'; $this->assertSame(0, $result, $msg); } }
Allow repr to show java.lang.Iterables.
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/[\\\"]/.test(s)) return quote(s); else return s; } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } else if (x instanceof java.lang.Iterable) { var elems = []; var i = x.iterator(); while (i.hasNext()) elems.push(repr(i.next())); return x["class"] + ":[ " + elems.join(", ") + " ]"; } else if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/[\\\"]/.test(s)) return quote(s); else return s; } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
Update level checks to allow a verbosity level of 0 or greater
# # License: MIT (doc/LICENSE) # Author: Todd Gaunt from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: quit() if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") elif level == 0: return elif level >= 1: nmsg=PROGRAM_NAME + "warning: " + msg print(nmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") elif level == 0: return elif level >= 1: nmsg = PROGRAM_NAME + msg print(nmsg) # End of File
# # License: MIT (doc/LICENSE) # Author: Todd Gaunt # # File: imgfetch/fourchan.py # This file contains the logging functions for writing to stdout stderr etc... from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: errmsg=PROGRAM_NAME + "error: internal error" if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) if level >= 1 or level < 0: quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") if level >= 0: warnmsg=PROGRAM_NAME + "warning: " + msg print(warnmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") if level == 0: return elif level >= 1: outmsg = PROGRAM_NAME + msg print(outmsg) # End of File
Remove unused init() add render() method
var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm'); /** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { }; ContactsController.remove = function(id) { console.log('Controller Remove'); //ContactModel.remove(id); //ContactView.remove(id); }; ContactsController.render = function(id, contact) { var contactView = new ContactView(id, contact); }; ContactsController.prototype = { setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; module.exports = ContactsController;
var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm'); /** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { this.init(); }; ContactsController.remove = function(id) { console.log('Controller Remove'); //ContactModel.remove(id); //ContactView.remove(id); }; ContactsController.prototype = { init: function() { console.log('new controller'); }, setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; module.exports = ContactsController;
Fix for touchend event for iOS.
/** * Flotr Event Adapter */ Flotr.EventAdapter = { observe: function(object, name, callback) { bean.add(object, name, callback); return this; }, fire: function(object, name, args) { bean.fire(object, name, args); if (typeof(Prototype) != 'undefined') Event.fire(object, name, args); // @TODO Someone who uses mootools, add mootools adapter for existing applciations. return this; }, stopObserving: function(object, name, callback) { bean.remove(object, name, callback); return this; }, eventPointer: function(e) { if (!_.isUndefined(e.touches) && e.touches.length > 0) { return {x: e.touches[0].pageX, y: e.touches[0].pageY}; } else if (!_.isUndefined(e.changedTouches) && e.changedTouches.length > 0) { return {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY}; } else if (Flotr.isIE && Flotr.isIE < 9) { return {x: e.clientX + document.body.scrollLeft, y: e.clientY + document.body.scrollTop}; } else { return {x: e.pageX, y: e.pageY}; } } };
/** * Flotr Event Adapter */ Flotr.EventAdapter = { observe: function(object, name, callback) { bean.add(object, name, callback); return this; }, fire: function(object, name, args) { bean.fire(object, name, args); if (typeof(Prototype) != 'undefined') Event.fire(object, name, args); // @TODO Someone who uses mootools, add mootools adapter for existing applciations. return this; }, stopObserving: function(object, name, callback) { bean.remove(object, name, callback); return this; }, eventPointer: function(e) { if (!_.isUndefined(e.touches) && e.touches.length > 0) { return {x: e.touches[0].pageX, y: e.touches[0].pageY}; } else if (Flotr.isIE && Flotr.isIE < 9) { return {x: e.clientX + document.body.scrollLeft, y: e.clientY + document.body.scrollTop}; } else { return {x: e.pageX, y: e.pageY}; } } };
Update mongoDB address by env.
var express = require('express'), app = express(); var scores = require('./server/routes/scores'); var users = require('./server/routes/users'); var chats = require('./server/routes/chats'); var rooms = require('./server/routes/rooms'); var paints = require('./server/routes/pictures'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); mongoose.connect(process.env.MONGODB || 'mongodb://localhost/rollingpaint'); app.use(express.static('www')); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use('/scores', scores); app.use('/users', users); app.use('/chats', chats); app.use('/rooms', rooms); app.use('/pictures', paints); // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); // API Routes // app.get('/blah', routeHandler); app.set('port', process.env.PORT || 80); app.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
var express = require('express'), app = express(); var scores = require('./server/routes/scores'); var users = require('./server/routes/users'); var chats = require('./server/routes/chats'); var rooms = require('./server/routes/rooms'); var paints = require('./server/routes/pictures'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/rollingpaint'); app.use(express.static('www')); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use('/scores', scores); app.use('/users', users); app.use('/chats', chats); app.use('/rooms', rooms); app.use('/pictures', paints); // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); // API Routes // app.get('/blah', routeHandler); app.set('port', process.env.PORT || 80); app.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
Update generator to derive from frost-component
/** * Component definition for the <%= dasherizedModuleName %> component */ import {PropTypes} from 'ember-prop-types' import computed, {readOnly} from 'ember-computed-decorators' import {Component} from 'ember-frost-core' import layout from '<%= templatePath %>' export default Component.extend({ // == Dependencies ========================================================== // == Keyword Properties ==================================================== layout, // == PropTypes ============================================================= /** * Properties for this component. Options are expected to be (potentially) * passed in to the component. State properties are *not* expected to be * passed in/overwritten. */ propTypes: { // options // state }, /** @returns {Object} the default property values when not provided by consumer */ getDefaultProps () { return { // options // state } }, // == Computed Properties =================================================== @readOnly @computed('css') /** * A pretty silly computed property just as an example of one * it appends '-' to the css base * @param {String} css - the base css class for this component (the component name) * @returns {String} a css prefix suitable for use within the template */ cssPrefix (css) { return `${css}-` }, // == Functions ============================================================= // == DOM Events ============================================================ // == Lifecycle Hooks ======================================================= // == Actions =============================================================== actions: { } })
/** * Component definition for the <%= dasherizedModuleName %> component */ import Ember from 'ember' const {Component} = Ember import PropTypesMixin, {PropTypes} from 'ember-prop-types' import computed, {readOnly} from 'ember-computed-decorators' import layout from '<%= templatePath %>' export default Component.extend(PropTypesMixin, { // == Dependencies ========================================================== // == Keyword Properties ==================================================== layout, // == PropTypes ============================================================= /** * Properties for this component. Options are expected to be (potentially) * passed in to the component. State properties are *not* expected to be * passed in/overwritten. */ propTypes: { // options hook: PropTypes.string.isRequired, // state // keywords layout: PropTypes.any }, /** @returns {Object} the default property values when not provided by consumer */ getDefaultProps () { return { // options // state } }, // == Computed Properties =================================================== @readOnly @computed('hook') /** * A pretty silly computed property just as an example of one * it appends '-' to the hook * @param {String} hook - the hook for this component * @returns {String} a hook prefix suitable for use within the template */ hookPrefix (hook) { return `${hook}-` }, // == Functions ============================================================= // == DOM Events ============================================================ // == Lifecycle Hooks ======================================================= // == Actions =============================================================== actions: { } })
Change buttons on main page
@extends('layouts.app') @section('content') @include('includes.sideNav') <section class="home"> <div class="home--logo"> @include('includes.trio-logo') </div> <div> <p class="center-block text-center home--info"> Trios is a simple exercise to test your English skills.<br> You should put in a single word that fits all three sentences.<br> Have fun! </p> <a href="{{ url('/solve') }}" class="btn btn-big btn-success btn--home text-uppercase">Play</a> <a href="{{ url('/login') }}" class="btn btn-big btn--home btn--login text-uppercase">Login</a> </div> </section> @endsection
@extends('layouts.app') @section('content') @include('includes.sideNav') <section class="home"> <div class="home--logo"> @include('includes.trio-logo') </div> <div> <p class="center-block text-center home--info"> Trios is a simple exercise to test your English skills.<br> You should put in a single word that fits all three sentences.<br> Have fun! </p> <a href="{{ url('/solve') }}" class="btn-big btn-success btn--home text-uppercase">Play</a> <a href="{{ url('/login') }}" class="btn-big btn--home btn--login text-uppercase">Login</a> </div> </section> @endsection
Enable core text widget now that its usable
<?php namespace App; /** * Unregister all default widgets. */ add_action('widgets_init', function () { $widgets = [ 'WP_Widget_Pages', 'WP_Widget_Calendar', 'WP_Widget_Archives', 'WP_Widget_Links', 'WP_Widget_Meta', // 'WP_Widget_Search', // 'WP_Widget_Text', 'WP_Widget_Categories', // 'WP_Widget_Recent_Posts', 'WP_Widget_Recent_Comments', 'WP_Widget_RSS', 'WP_Widget_Tag_Cloud', // 'WP_Nav_Menu_Widget', ]; foreach ($widgets as $widget) { unregister_widget($widget); } });
<?php namespace App; /** * Unregister all default widgets. */ add_action('widgets_init', function () { $widgets = [ 'WP_Widget_Pages', 'WP_Widget_Calendar', 'WP_Widget_Archives', 'WP_Widget_Links', 'WP_Widget_Meta', // 'WP_Widget_Search', 'WP_Widget_Text', 'WP_Widget_Categories', // 'WP_Widget_Recent_Posts', 'WP_Widget_Recent_Comments', 'WP_Widget_RSS', 'WP_Widget_Tag_Cloud', // 'WP_Nav_Menu_Widget', ]; foreach ($widgets as $widget) { unregister_widget($widget); } });
Fix data handler name type
const fs = require('fs'); const path = require('path'); module.exports = function(options, fieldname, filename) { const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/'); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } let tempFilePath = path.join(dir, 'tmp' + Date.now()); let writeStream = fs.createWriteStream(tempFilePath); let fileSize = 0; // eslint-disable-line return { dataHandler: function(data) { writeStream.write(data); fileSize += data.length; if (options.debug) { return console.log( // eslint-disable-line `Uploaded ${data.length} bytes for `, fieldname, filename ); } }, getFilePath: function(){ return tempFilePath; }, getFileSize: function(){ return fileSize; }, cleanup: function(){ writeStream.end(); fs.unlink(tempFilePath, function(err) { if (err) throw err; }); }, complete: function(){ writeStream.end(); } }; };
const fs = require('fs'); const path = require('path'); module.exports = function(options, fieldname, filename) { const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/'); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } let tempFilePath = path.join(dir, 'tmp' + Date.now()); let writeStream = fs.createWriteStream(tempFilePath); let fileSize = 0; // eslint-disable-line return { handler: function(data) { writeStream.write(data); fileSize += data.length; if (options.debug) { return console.log( // eslint-disable-line `Uploaded ${data.length} bytes for `, fieldname, filename ); } }, getFilePath: function(){ return tempFilePath; }, getFileSize: function(){ return fileSize; }, cleanup: function(){ writeStream.end(); fs.unlink(tempFilePath, function(err) { if (err) throw err; }); }, complete: function(){ writeStream.end(); } }; };
Add CustomizeBrowserOptions method to Metric base class BUG=271177 Review URL: https://chromiumcodereview.appspot.com/22938004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217198 0039d316-1c4b-4281-b951-d872f2087c98
# 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. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def CustomizeBrowserOptions(self, options): """Add browser options that are required by this metric. Some metrics do not have any special browser options that need to be added, and they do not need to override this method; by default, no browser options are added. To add options here, call options.AppendExtraBrowserArg(arg). """ pass def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
# 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. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
Remove commonSvc dependency to prevent circular dependency
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = []; function sessionService() { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = ['commonService']; function sessionService(commonService) { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
Use unminified for development env
var path = require('path'); module.exports = { name: 'Ember CLI Data Factory Guy', blueprintsPath: function() { return path.join(__dirname, 'blueprints'); }, included: function(app) { this._super.included(app); if (app.tests) { // ember-data must be imported before ember-data-factory-guy. var options = { exports: { 'ember-data': [ 'default' ] } }; this.app.import({ development: app.bowerDirectory + '/ember-data/ember-data.js', production: app.bowerDirectory + '/ember-data/ember-data.prod.js' }, options); app.import({ development: app.bowerDirectory + '/ember-data-factory-guy/dist/ember-data-factory-guy.js', production: app.bowerDirectory + '/ember-data-factory-guy/dist/ember-data-factory-guy.min.js' }); } } };
var path = require('path'); module.exports = { name: 'Ember CLI Data Factory Guy', blueprintsPath: function() { return path.join(__dirname, 'blueprints'); }, included: function(app) { this._super.included(app); if (app.tests) { // ember-data must be imported before ember-data-factory-guy. var options = { exports: { 'ember-data': [ 'default' ] } }; this.app.import({ development: app.bowerDirectory + '/ember-data/ember-data.js', production: app.bowerDirectory + '/ember-data/ember-data.prod.js' }, options); app.import(app.bowerDirectory + '/ember-data-factory-guy/dist/ember-data-factory-guy.min.js'); } } };
Fix ctypes call test for windows
import os import ctypes from numba import * @autojit(backend='ast', nopython=True) def call_ctypes_func(func, value): return func(value) def test_ctypes_calls(): # Test puts for no segfault libc = ctypes.CDLL(ctypes.util.find_library('c')) puts = libc.puts puts.argtypes = [ctypes.c_char_p] call_ctypes_func(puts, "Hello World!") # Test ceil result libm = ctypes.CDLL(ctypes.util.find_library('m')) ceil = libm.ceil ceil.argtypes = [ctypes.c_double] ceil.restype = ctypes.c_double assert call_ctypes_func(ceil, 10.1) == 11.0 def test_str_return(): try: import errno except ImportError: return libc = ctypes.CDLL(ctypes.util.find_library('c')) strerror = libc.strerror strerror.argtypes = [ctypes.c_int] strerror.restype = ctypes.c_char_p expected = os.strerror(errno.EACCES) got = call_ctypes_func(strerror, errno.EACCES) assert expected == got if __name__ == "__main__": test_ctypes_calls() # test_str_return()
import os import ctypes from numba import * @autojit(backend='ast', nopython=True) def call_ctypes_func(func, value): return func(value) def test_ctypes_calls(): libc = ctypes.CDLL(ctypes.util.find_library('c')) puts = libc.puts puts.argtypes = [ctypes.c_char_p] assert call_ctypes_func(puts, "Hello World!") libm = ctypes.CDLL(ctypes.util.find_library('m')) ceil = libm.ceil ceil.argtypes = [ctypes.c_double] ceil.restype = ctypes.c_double assert call_ctypes_func(ceil, 10.1) == 11.0 def test_str_return(): try: import errno except ImportError: return libc = ctypes.CDLL(ctypes.util.find_library('c')) strerror = libc.strerror strerror.argtypes = [ctypes.c_int] strerror.restype = ctypes.c_char_p expected = os.strerror(errno.EACCES) got = call_ctypes_func(strerror, errno.EACCES) assert expected == got if __name__ == "__main__": test_ctypes_calls() # test_str_return()
Create the snippet, then the draft.
import Ember from 'ember'; export default Ember.Route.extend({ actions: { submit: function () { var self = this, content = this.controller.get('firstSnippet'), snippet = this.store.createRecord('snippet', { content: content, }); snippet.save().then(function () { var draft = self.store.createRecord('draft', { firstLine: content.slice(0, 30), contributionStatus: 'cooldown', canAdmin: true, snippetCount: 1, lastSnippet: snippet, }); return draft.save(); }).then(function () { return self.transitionTo('index'); }); } } });
import Ember from 'ember'; export default Ember.Route.extend({ actions: { submit: function () { var content = this.controller.get('firstSnippet'); var snippet = this.store.createRecord('snippet', { content: content, }); snippet.save().then(function () { var draft = this.store.createRecord('draft', { firstLine: snippet.slice(0, 30), contributionStatus: 'cooldown', canAdmin: true, snippetCount: 1, lastSnippet: snippet, }); return draft.save(); }).then(function () { this.transitionTo('index'); }); } } });
Fix broken test.. was testing the old way of validation of the reconsent command.
package edu.northwestern.bioinformatics.studycalendar.web.schedule; import edu.northwestern.bioinformatics.studycalendar.service.StudyService; import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.NowFactory; import static org.easymock.EasyMock.expect; import org.springframework.validation.Errors; import org.springframework.validation.BindException; import java.util.Calendar; public class ScheduleReconsentCommandTest extends StudyCalendarTestCase { private ScheduleReconsentCommand command; private StudyService studyService; private NowFactory nowFactory; protected void setUp() throws Exception { super.setUp(); studyService = registerMockFor(StudyService.class); nowFactory = registerMockFor(NowFactory.class); command = new ScheduleReconsentCommand(studyService, nowFactory); } public void testValidate() throws Exception { BindException errors = new BindException(command, "startDate"); command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3)); expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)); replayMocks(); command.validate(errors); verifyMocks(); assertEquals("There should be one error: ", 1, errors.getAllErrors().size()); } }
package edu.northwestern.bioinformatics.studycalendar.web.schedule; import edu.northwestern.bioinformatics.studycalendar.service.StudyService; import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.NowFactory; import static org.easymock.EasyMock.expect; import java.util.Calendar; public class ScheduleReconsentCommandTest extends StudyCalendarTestCase { private ScheduleReconsentCommand command; private StudyService studyService; private NowFactory nowFactory; protected void setUp() throws Exception { super.setUp(); studyService = registerMockFor(StudyService.class); nowFactory = registerMockFor(NowFactory.class); command = new ScheduleReconsentCommand(studyService, nowFactory); } public void testValidate() throws Exception { command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3)); expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)).times(2); replayMocks(); command.validate(null); verifyMocks(); assertSameDay("Expected Date different than actual", DateTools.createDate(2007, Calendar.AUGUST, 3), command.getStartDate()); } }
Fix param order of assertEquals (expected, actual) in test for Finder\Glob
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Tests; use Symfony\Component\Finder\Glob; class GlobTest extends \PHPUnit_Framework_TestCase { public function testGlobToRegexDelimiters() { $this->assertEquals('#^\.[^/]*$#', Glob::toRegex('.*')); $this->assertEquals('^\.[^/]*$', Glob::toRegex('.*', true, true, '')); $this->assertEquals('/^\.[^/]*$/', Glob::toRegex('.*', true, true, '/')); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Tests; use Symfony\Component\Finder\Glob; class GlobTest extends \PHPUnit_Framework_TestCase { public function testGlobToRegexDelimiters() { $this->assertEquals(Glob::toRegex('.*'), '#^\.[^/]*$#'); $this->assertEquals(Glob::toRegex('.*', true, true, ''), '^\.[^/]*$'); $this->assertEquals(Glob::toRegex('.*', true, true, '/'), '/^\.[^/]*$/'); } }
Make sure to not leave hanging children processes if the parent is killed
# encoding: utf-8 ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing import signal # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.processes = [] def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) p = multiprocessing.Process(target=netapi[fun]) p.start() self.processes.append(p) # make sure to kill the subprocesses if the parent is killed signal.signal(signal.SIGTERM, self.kill_children) def kill_children(self, *args): ''' Kill all of the children ''' for p in self.processes: p.terminate() p.join()
# encoding: utf-8 ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts def run(self): ''' Load and start all available api modules ''' netapi = salt.loader.netapi(self.opts) for fun in netapi: if fun.endswith('.start'): logger.info("Starting '{0}' api module".format(fun)) multiprocessing.Process(target=netapi[fun]).start()
Trim even if there's no latest doc
var README_MAXLEN = 64 * 1024 module.exports = readmeTrim function readmeTrim(doc) { var changed = false var readme = doc.readme || '' var readmeFilename = doc.readmeFilename || '' if (doc['dist-tags'] && doc['dist-tags'].latest) { var latest = doc.versions[doc['dist-tags'].latest] if (latest && latest.readme) { readme = latest.readme readmeFilename = latest.readmeFilename || '' } } for (var v in doc.versions) { // If we still don't have one, just take the first one. if (doc.versions[v].readme && !readme) readme = doc.versions[v].readme if (doc.versions[v].readmeFilename && !readmeFilename) readmeFilename = doc.versions[v].readmeFilename if (doc.versions[v].readme) changed = true delete doc.versions[v].readme delete doc.versions[v].readmeFilename } if (readme && readme.length > README_MAXLEN) { changed = true readme = readme.slice(0, README_MAXLEN) } doc.readme = readme doc.readmeFilename = readmeFilename return changed }
var README_MAXLEN = 64 * 1024 module.exports = readmeTrim function readmeTrim(doc) { var changed = false var readme = doc.readme || '' var readmeFilename = doc.readmeFilename || '' if (doc['dist-tags'] && doc['dist-tags'].latest) { var latest = doc.versions[doc['dist-tags'].latest] if (latest && latest.readme) { readme = latest.readme readmeFilename = latest.readmeFilename || '' } for (var v in doc.versions) { // If we still don't have one, just take the first one. if (doc.versions[v].readme && !readme) readme = doc.versions[v].readme if (doc.versions[v].readmeFilename && !readmeFilename) readmeFilename = doc.versions[v].readmeFilename if (doc.versions[v].readme) changed = true delete doc.versions[v].readme delete doc.versions[v].readmeFilename } } if (readme && readme.length > README_MAXLEN) { changed = true readme = readme.slice(0, README_MAXLEN) } doc.readme = readme doc.readmeFilename = readmeFilename return changed }
Set default coordinate to -90, 0(antarctica) since mysql refuses to index coordinates if there exists empty or null value.
<?php class Db_model extends CI_Model { function __construct() { // Call the Model constructor parent::__construct(); } function insert_record($record) { /* * convert coordinate string to mysql geospacial fucntion call */ $coord_string = $record['coordinates']; unset($record['coordinates']); // convert string to function call, if string is null or not well formatted // set as null $coord = NULL; if ($coord_string != NULL and $coord_string != '') { $coord_array = explode(", ", $coord_string); if (sizeof($coord == 2)) { // make sure we have two coordinates $coord = NULL; } } if ($coord == NULL) { // set to antarctica $coord_array = array(-90, 0); } $coord = "GeomFromText('POINT(" . implode(' ', $coord_array) . ")')"; // insert in to db $this->db->set($record); if ($coord) $this->db->set('coordinate', $coord, FALSE); $this->db->insert('point'); } }
<?php class Db_model extends CI_Model { function __construct() { // Call the Model constructor parent::__construct(); } function insert_record($record) { /* * convert coordinate string to mysql geospacial fucntion call */ $coord_string = $record['coordinates']; unset($record['coordinates']); // convert string to function call, if string is null or not well formatted // set as null $coord = NULL; if ($coord_string != NULL and $coord_string != '') { $coord_array = explode(", ", $coord_string); if (sizeof($coord == 2)) { // make sure we have two coordinates $coord = "GeomFromText('POINT(" . implode(' ', $coord_array) . ")')"; } else { $coord = NULL; } } // insert in to db $this->db->set($record); if ($coord) $this->db->set('coordinate', $coord, FALSE); $this->db->insert('point'); } }
Remove hack in mdbd fs.host.fqdn driver.
package main import ( "encoding/json" "errors" "github.com/Symantec/Dominator/lib/mdb" "io" "log" ) func loadDsHostFqdn(reader io.Reader, datacentre string, logger *log.Logger) ( *mdb.Mdb, error) { type machineType struct { Fqdn string } type dataCentreType map[string]machineType type inMdbType map[string]dataCentreType var inMdb inMdbType var outMdb mdb.Mdb decoder := json.NewDecoder(reader) if err := decoder.Decode(&inMdb); err != nil { return nil, errors.New("Error decoding: " + err.Error()) } for dsName, dataCentre := range inMdb { if datacentre != "" && dsName != datacentre { continue } for _, inMachine := range dataCentre { var outMachine mdb.Machine if inMachine.Fqdn != "" { outMachine.Hostname = inMachine.Fqdn outMdb.Machines = append(outMdb.Machines, outMachine) } } } return &outMdb, nil }
package main import ( "encoding/json" "errors" "github.com/Symantec/Dominator/lib/mdb" "io" "log" ) func loadDsHostFqdn(reader io.Reader, datacentre string, logger *log.Logger) ( *mdb.Mdb, error) { type machineType struct { Fqdn string } type dataCentreType map[string]machineType type inMdbType map[string]dataCentreType var inMdb inMdbType var outMdb mdb.Mdb decoder := json.NewDecoder(reader) if err := decoder.Decode(&inMdb); err != nil { return nil, errors.New("Error decoding: " + err.Error()) } for dsName, dataCentre := range inMdb { if datacentre != "" && dsName != datacentre { continue } for machineName, inMachine := range dataCentre { var outMachine mdb.Machine if inMachine.Fqdn == "" { outMachine.Hostname = machineName + "." + dsName } else { outMachine.Hostname = inMachine.Fqdn } outMdb.Machines = append(outMdb.Machines, outMachine) } } return &outMdb, nil }
Add location and expense strings to pastTrip model
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, locationString: String, expenseString: String, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
Add jest module mapper for tests directory
module.exports = { verbose: true, bail: true, collectCoverage: true, coverageDirectory: 'coverage', restoreMocks: true, moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], transform: { '^.+\\.vue$': 'vue-jest', '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '^.+\\.jsx?$': 'babel-jest' }, moduleNameMapper: { '^@/tests/(.*)$': '<rootDir>/tests/$1', '^@/(.*)$': '<rootDir>/src/$1' }, snapshotSerializers: ['jest-serializer-vue'], testMatch: [ '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)' ], testURL: 'http://localhost/' };
module.exports = { verbose: true, bail: true, collectCoverage: true, coverageDirectory: 'coverage', restoreMocks: true, moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], transform: { '^.+\\.vue$': 'vue-jest', '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '^.+\\.jsx?$': 'babel-jest' }, moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' }, snapshotSerializers: ['jest-serializer-vue'], testMatch: [ '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)' ], testURL: 'http://localhost/' };
Remove ominous TESTING_LOGIN config comment
# TODO @Sumukh Better Secret Management System class TestConfig(object): DEBUG = True SECRET_KEY = 'Testing*ok*server*' RESTFUL_JSON = {'indent': 4} TESTING_LOGIN = True class DevConfig(TestConfig): ENV = 'dev' DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:@localhost:5432/okdev' CACHE_TYPE = 'simple' ASSETS_DEBUG = True class TestConfig(TestConfig): ENV = 'test' DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:@localhost:5432/okdev' SQLALCHEMY_ECHO = True CACHE_TYPE = 'simple' WTF_CSRF_ENABLED = False class Config: SECRET_KEY = 'samplekey' class ProdConfig(Config): # TODO Move to secret file ENV = 'prod' SQLALCHEMY_DATABASE_URI = 'postgresql://user:@localhost:5432/okprod' CACHE_TYPE = 'simple'
# TODO @Sumukh Better Secret Management System class TestConfig(object): DEBUG = True SECRET_KEY = 'Testing*ok*server*' RESTFUL_JSON = {'indent': 4} TESTING_LOGIN = True # Do NOT turn on for prod class DevConfig(TestConfig): ENV = 'dev' DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:@localhost:5432/okdev' CACHE_TYPE = 'simple' ASSETS_DEBUG = True class TestConfig(TestConfig): ENV = 'test' DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:@localhost:5432/okdev' SQLALCHEMY_ECHO = True CACHE_TYPE = 'simple' WTF_CSRF_ENABLED = False class Config: SECRET_KEY = 'samplekey' class ProdConfig(Config): # TODO Move to secret file ENV = 'prod' SQLALCHEMY_DATABASE_URI = 'postgresql://user:@localhost:5432/okprod' CACHE_TYPE = 'simple'
Remove a debug logging call
function setupBoolPreference(name) { document.getElementById(name).checked = Preferences[name].value; document.getElementById(name).addEventListener("change", function(e) { Preferences[name].value = e.target.checked; }); } function setupNumberPreference(name) { document.getElementById(name).value = Preferences[name].value; document.getElementById(name).addEventListener("change", function(e) { Preferences[name].value = e.target.value; }); } for(var name in Preferences) { if(Preferences[name].type == "bool") { setupBoolPreference(name); } else { setupNumberPreference(name); } } if(!navigator.vibrate) { document.getElementById("vibration").setAttribute("disabled", true); } var strbundle = new StringBundle(document.getElementById("strings")); document.querySelector("[data-l10n-id='settings_highscores_clear']").addEventListener("click", function() { if(window.confirm(strbundle.getString("highscores_confirm_clear"))) { Highscores.clear(); removeDynamicItems(); noresults.classList.remove("hidden"); } }); document.getElementById("header").addEventListener("action", function() { window.location = "index.html"; }, false);
function setupBoolPreference(name) { document.getElementById(name).checked = Preferences[name].value; document.getElementById(name).addEventListener("change", function(e) { Preferences[name].value = e.target.checked; }); } function setupNumberPreference(name) { document.getElementById(name).value = Preferences[name].value; document.getElementById(name).addEventListener("change", function(e) { console.log("ping"); Preferences[name].value = e.target.value; }); } for(var name in Preferences) { if(Preferences[name].type == "bool") { setupBoolPreference(name); } else { setupNumberPreference(name); } } if(!navigator.vibrate) { document.getElementById("vibration").setAttribute("disabled", true); } var strbundle = new StringBundle(document.getElementById("strings")); document.querySelector("[data-l10n-id='settings_highscores_clear']").addEventListener("click", function() { if(window.confirm(strbundle.getString("highscores_confirm_clear"))) { Highscores.clear(); removeDynamicItems(); noresults.classList.remove("hidden"); } }); document.getElementById("header").addEventListener("action", function() { window.location = "index.html"; }, false);
Add another test case to increase coverage
package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } @Test public void unknownTermsReturnNull() { assertThat(subject.getTermName("IPRFOOBAR"), is(nullValue())); } }
package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } }
Index only latest by default.
import logging from django.core.management.base import BaseCommand from django.conf import settings from projects import tasks from projects.models import ImportedFile from builds.models import Version log = logging.getLogger(__name__) class Command(BaseCommand): help = '''\ Delete and re-create ImportedFile objects for all latest Versions, such that they can be added to the search index. This is accomplished by walking the filesystem for each project. ''' def handle(self, *args, **kwargs): ''' Build/index all versions or a single project's version ''' # Delete all existing as a cleanup for any deleted projects. ImportedFile.objects.all().delete() if getattr(settings, 'INDEX_ONLY_LATEST', True): queryset = Version.objects.filter(slug='latst') else: queryset = Version.objects.public() for v in queryset: log.info("Building files for %s" % v) try: tasks.fileify(v) except Exception: log.error('Build failed for %s' % v, exc_info=True)
import logging from django.core.management.base import BaseCommand from django.conf import settings from projects import tasks from projects.models import ImportedFile from builds.models import Version log = logging.getLogger(__name__) class Command(BaseCommand): help = '''\ Delete and re-create ImportedFile objects for all latest Versions, such that they can be added to the search index. This is accomplished by walking the filesystem for each project. ''' def handle(self, *args, **kwargs): ''' Build/index all versions or a single project's version ''' # Delete all existing as a cleanup for any deleted projects. ImportedFile.objects.all().delete() if getattr(settings, 'INDEX_ONLY_LATEST', False): queryset = Version.objects.filter(slug='latst') else: queryset = Version.objects.public() for v in queryset: log.info("Building files for %s" % v) try: tasks.fileify(v) except Exception: log.error('Build failed for %s' % v, exc_info=True)
Fix test broken due to delete_record change
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, record.type, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
Comment out a test case
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('UTF-8') sys.path.append('..') from analyzer import rss_parser #entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/us', language='en') #entries = rss_parser.parse(feed_link='http://www.engadget.com/rss.xml', language='en') #entries = rss_parser.parse(feed_link='http://rss.cnn.com/rss/edition_sport.rss', language='en') #entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/sports', language='en') entries = rss_parser.parse(feed_link='http://rss.detik.com/index.php/sport', feed_id="5264f7cb0ff6cb1898609028", language='in', categories={"ID::Olahraga" : "1"}) print len(entries) print entries[0]
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('UTF-8') sys.path.append('..') from analyzer import rss_parser #entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/us', language='en') #entries = rss_parser.parse(feed_link='http://www.engadget.com/rss.xml', language='en') #entries = rss_parser.parse(feed_link='http://rss.cnn.com/rss/edition_sport.rss', language='en') entries = rss_parser.parse(feed_link='http://news.yahoo.com/rss/sports', language='en') entries = rss_parser.parse(feed_link='http://rss.detik.com/index.php/sport', feed_id="5264f7cb0ff6cb1898609028", language='in', categories={"ID::Olahraga" : "1"}) print len(entries) print entries[0]
Add a comment about what happens for expired/non-existent uids
/* 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/. */ // helper functions for views with a profile image. Meant to be mixed into views. 'use strict'; define([ 'lib/session' ], function (Session) { return { // user must be authenticated and verified to see Settings pages mustVerify: true, initialize: function () { var self = this; var uid = self.relier.get('uid'); // A uid param is set by RPs linking directly to the settings // page for a particular account. // We set the current account to the one with `uid` if // it exists in our list of cached accounts. If it doesn't, // clear the current account. // The `mustVerify` flag will ensure that the account is valid. if (! self.user.getAccountByUid(uid).isEmpty()) { // The account with uid exists; set it to our current account. self.user.setSignedInAccountByUid(uid); } else if (uid) { // session is expired or user does not exist. Force the user // to sign in. Session.clear(); self.user.clearSignedInAccount(); } } }; });
/* 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/. */ // helper functions for views with a profile image. Meant to be mixed into views. 'use strict'; define([ 'lib/session' ], function (Session) { return { // user must be authenticated and verified to see Settings pages mustVerify: true, initialize: function () { var self = this; var uid = self.relier.get('uid'); // A uid param is set by RPs linking directly to the settings // page for a particular account. // We set the current account to the one with `uid` if // it exists in our list of cached accounts. If it doesn't, // clear the current account. // The `mustVerify` flag will ensure that the account is valid. if (! self.user.getAccountByUid(uid).isEmpty()) { // The account with uid exists; set it to our current account. self.user.setSignedInAccountByUid(uid); } else if (uid) { Session.clear(); self.user.clearSignedInAccount(); } } }; });
Set status button in serial no
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), function() { cur_frm.set_value("status", "Available"); cur_frm.save(); }); });
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available); }); cur_frm.cscript.set_status_as_available = function() { cur_frm.set_value("status", "Available"); cur_frm.save() }
Add better notes of when things aren't working.
var ChunkTypes = require('./ChunkTypes'); var DataRequestType = require('./io/DataRequestType'); var Promise = require('bluebird'); var Ranges = require('./utils/Ranges'); var _ = require('lodash'); var fetchDataRedirect = require('./fetchDataRedirect'); var regeneratorRuntime = require('regenerator/runtime'); var sendRequest = require('./io/sendRequest'); var fetchData = Promise.coroutine(function*(cache, apiKey, lists) { var listNames = lists.map((list) => list.name); var listChunkRanges = yield Promise.map(listNames, function(listName) { return Promise.props({ add: cache.getChunkIDs(listName, ChunkTypes.ADD), sub: cache.getChunkIDs(listName, ChunkTypes.SUB) }).then((results) => _.mapValues(results, Ranges.getRangesForNumbers)); }).then((results) => _.zipObject(listNames, results)); var listChunks = yield sendRequest(DataRequestType, { apiKey: apiKey, lists: listChunkRanges }); // TODO: support pleasereset. yield Promise.each(listChunks.lists, Promise.coroutine(function*(list) { // TODO: support list chunk expiration. yield Promise.each(list.urls, function(url) { return fetchDataRedirect(cache, list.name, url); }); })); return listChunks.delay; }); module.exports = fetchData;
var ChunkTypes = require('./ChunkTypes'); var DataRequestType = require('./io/DataRequestType'); var Promise = require('bluebird'); var Ranges = require('./utils/Ranges'); var _ = require('lodash'); var fetchDataRedirect = require('./fetchDataRedirect'); var regeneratorRuntime = require('regenerator/runtime'); var sendRequest = require('./io/sendRequest'); var fetchData = Promise.coroutine(function*(cache, apiKey, lists) { var listNames = lists.map((list) => list.name); var listChunkRanges = yield Promise.map(listNames, function(listName) { return Promise.props({ add: cache.getChunkIDs(listName, ChunkTypes.ADD), sub: cache.getChunkIDs(listName, ChunkTypes.SUB) }).then((results) => _.mapValues(results, Ranges.getRangesForNumbers)); }).then((results) => _.zipObject(listNames, results)); var listChunks = yield sendRequest(DataRequestType, { apiKey: apiKey, lists: listChunkRanges }); if (listChunks.isReset) { throw new Error('Reset not implemented'); } yield Promise.each(listChunks.lists, function(list) { return Promise.each(list.urls, function(url) { return fetchDataRedirect(cache, list.name, url); }); }); return listChunks.delay; }); module.exports = fetchData;
Rename js_lib to js_library in docs/comments/etc... to clean up lingering references to js_lib. CL automatically created by: replace_string --pcre '\b([^\":/\n])js_lib\b' '\1js_library' ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=248271419
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. // All Rights Reserved. /** * @fileoverview Aliases `goog.editor.PluginImpl`. * * This is done to create a target for `goog.editor.PluginImpl` that also pulls * in `goog.editor.Field` without creating a cycle. Doing so allows downstream * targets to depend only on `goog.editor.Plugin` without js_library complaining * about unfullfilled forward declarations. */ goog.provide('goog.editor.Plugin'); /** @suppress {extraRequire} This is the whole point. */ goog.require('goog.editor.Field'); goog.require('goog.editor.PluginImpl'); /** * @constructor * @extends {goog.editor.PluginImpl} */ goog.editor.Plugin = goog.editor.PluginImpl;
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. // All Rights Reserved. /** * @fileoverview Aliases `goog.editor.PluginImpl`. * * This is done to create a target for `goog.editor.PluginImpl` that also pulls * in `goog.editor.Field` without creating a cycle. Doing so allows downstream * targets to depend only on `goog.editor.Plugin` without js_lib complaining * about unfullfilled forward declarations. */ goog.provide('goog.editor.Plugin'); /** @suppress {extraRequire} This is the whole point. */ goog.require('goog.editor.Field'); goog.require('goog.editor.PluginImpl'); /** * @constructor * @extends {goog.editor.PluginImpl} */ goog.editor.Plugin = goog.editor.PluginImpl;
Use hljs.listLanguages for auto-detection tests
'use strict'; var fs = require('fs'); var hljs = require('../build'); var path = require('path'); var utility = require('./utility'); function testAutoDetection(language) { it('should be detected as ' + language, function() { var languagePath = utility.buildPath('detect', language), examples = fs.readdirSync(languagePath); examples.forEach(function(example) { var filename = path.join(languagePath, example), content = fs.readFileSync(filename, 'utf-8'), expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs', function() { describe('.highlightAuto', function() { var languages = hljs.listLanguages(); languages.forEach(testAutoDetection); }); });
'use strict'; var fs = require('fs'); var hljs = require('../build'); var path = require('path'); var utility = require('./utility'); function testAutoDetection(language) { it('should be detected as ' + language, function() { var languagePath = utility.buildPath('detect', language), examples = fs.readdirSync(languagePath); examples.forEach(function(example) { var filename = path.join(languagePath, example), content = fs.readFileSync(filename, 'utf-8'), expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs', function() { describe('.highlightAuto', function() { var languages = utility.languagesList(); languages.forEach(testAutoDetection); }); });
Set user password for all sanitized users to '123'.
#!/usr/bin/python # Setup import paths, since we are using Django models import sys, os sys.path.append('/var/www/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production' # Imports from django.core import serializers if len(sys.argv) != 4: print "Usage: %s format input-file output-file" % sys.argv[0] exit(1) if sys.argv[1] not in ('json', 'xml'): print "Invalid format '%s'! Valid formats are: json xml" % sys.argv[1] exit(1) def object_transformator(): # Read all objects one by one for holder in serializers.deserialize(sys.argv[1], open(sys.argv[2], 'r')): name = holder.object.__class__.__name__ object = holder.object # Some objects need to be sanitized if name == 'Node': object.notes = '' elif name == 'UserAccount': object.vpn_password = 'XXX' object.phone = '5551234' elif name == 'User': object.password = '$1$1qL5F...$ZPQdHpHMsvNQGI4rIbAG70' elif name == 'Profile': object.root_pass = 'XXX' elif name == 'StatsSolar': continue yield holder.object # Write transformed objects out out = open(sys.argv[3], 'w') serializers.serialize(sys.argv[1], object_transformator(), stream = out) out.close()
#!/usr/bin/python # Setup import paths, since we are using Django models import sys, os sys.path.append('/var/www/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production' # Imports from django.core import serializers if len(sys.argv) != 4: print "Usage: %s format input-file output-file" % sys.argv[0] exit(1) if sys.argv[1] not in ('json', 'xml'): print "Invalid format '%s'! Valid formats are: json xml" % sys.argv[1] exit(1) def object_transformator(): # Read all objects one by one for holder in serializers.deserialize(sys.argv[1], open(sys.argv[2], 'r')): name = holder.object.__class__.__name__ object = holder.object # Some objects need to be sanitized if name == 'Node': object.notes = '' elif name == 'UserAccount': object.vpn_password = 'XXX' object.phone = '5551234' elif name == 'User': object.password = 'XXX' elif name == 'Profile': object.root_pass = 'XXX' elif name == 'StatsSolar': continue yield holder.object # Write transformed objects out out = open(sys.argv[3], 'w') serializers.serialize(sys.argv[1], object_transformator(), stream = out) out.close()
Move all navigation code into try block This prevents navigation forward when the validation failed. Before the user didn't have the chance to correct what was wrong and where immediately taken on the next page.
import { take, put, select, call } from 'redux-saga/effects'; import { NAVIGATE_TO_NEXT_SECTION, setErrors, load } from '../actions'; import * as selectors from '../selectors'; import { push } from '../../common/actions/router'; import { validateNode, HTTPError } from '../../common/helpers/api'; // Navigate to next section based on current section export default function* navigateToNextSection() { while (true) { yield take(NAVIGATE_TO_NEXT_SECTION); const node = yield select(selectors.node); const activeSection = yield select(selectors.activeSection); const { nodeAttrs } = activeSection; yield put(load(true)); const attrs = yield call([ nodeAttrs, nodeAttrs.toJS ]); try { yield call(validateNode, node, attrs); const sections = yield select(selectors.sections); const nextIndex = sections.indexOf(activeSection) + 1; const nextSection = sections.get(nextIndex); yield put(push.newNodeSectionPath(nextSection, node.serialize())); } catch (error) { if (yield call(HTTPError.is, error, 422)) { const { errors } = error; // Abort navigation and show errors. yield put(setErrors(errors)); } else { throw error; } } finally { yield put(load(false)); } } }
import { take, put, select, call } from 'redux-saga/effects'; import { NAVIGATE_TO_NEXT_SECTION, setErrors, load } from '../actions'; import * as selectors from '../selectors'; import { push } from '../../common/actions/router'; import { validateNode, HTTPError } from '../../common/helpers/api'; // Navigate to next section based on current section export default function* navigateToNextSection() { while (true) { yield take(NAVIGATE_TO_NEXT_SECTION); const node = yield select(selectors.node); const activeSection = yield select(selectors.activeSection); const { nodeAttrs } = activeSection; yield put(load(true)); const attrs = yield call([ nodeAttrs, nodeAttrs.toJS ]); try { yield call(validateNode, node, attrs); } catch (error) { if (yield call(HTTPError.is, error, 422)) { const { errors } = error; // Abort navigation and show errors. yield put(setErrors(errors)); } else { throw error; } } finally { yield put(load(false)); } const sections = yield select(selectors.sections); const nextIndex = sections.indexOf(activeSection) + 1; const nextSection = sections.get(nextIndex); yield put(push.newNodeSectionPath(nextSection, node.serialize())); } }
Add missing source map comment when debug is true Without this comment, source maps won't resolve properly.
import { transformFile } from 'babel-core' import { debug } from '../util/stdio' import { default as es2015 } from 'babel-preset-es2015' import { default as amd } from 'babel-plugin-transform-es2015-modules-amd' export default function configure(pkg, opts) { return (name, file, done) => { transformFile(file , { moduleIds: true , moduleRoot: `${pkg.name}/${opts.lib}` , sourceRoot: opts.src , presets: [es2015] , plugins: [amd] , babelrc: true , sourceMaps: !!opts.debug , sourceFileName: file , sourceMapTarget: file } , (error, result) => { if (error) { done(error) } else { let output = { files: { [`${name}.js`]: result.code } } if (opts.debug) { output.files[`${name}.js`] += `\n//# sourceMappingURL=${name}.js.map` output.files[`${name}.js.map`] = JSON.stringify(result.map) } done(null, output) } } ) } }
import { transformFile } from 'babel-core' import { debug } from '../util/stdio' import { default as es2015 } from 'babel-preset-es2015' import { default as amd } from 'babel-plugin-transform-es2015-modules-amd' export default function configure(pkg, opts) { return (name, file, done) => { transformFile(file , { moduleIds: true , moduleRoot: `${pkg.name}/${opts.lib}` , sourceRoot: opts.src , presets: [es2015] , plugins: [amd] , babelrc: true , sourceMaps: !!opts.debug , sourceFileName: file , sourceMapTarget: file } , (error, result) => { if (error) { done(error) } else { let output = { files: { [`${name}.js`]: result.code } } if (opts.debug) { output.files[`${name}.js.map`] = JSON.stringify(result.map) } done(null, output) } } ) } }
Establish session in default handler.
/** * Password authentication handler. * * This component provides an HTTP handler that authenticates a username and * password. The credentials are submitted via an HTML form. */ exports = module.exports = function(parse, csrfProtection, authenticate, ceremony) { function establishSession(req, res, next) { req.login(req.user, function(err) { if (err) { return next(err); } return next(); }); } return [ parse('application/x-www-form-urlencoded'), ceremony( csrfProtection(), authenticate('www-password', { session: false }), [ establishSession ] ) ]; /* return [ parse('application/x-www-form-urlencoded'), ceremony('login/password', csrfProtection(), authenticate('password'), { through: 'login' }) ]; */ }; exports['@require'] = [ 'http://i.bixbyjs.org/http/middleware/parse', 'http://i.bixbyjs.org/http/middleware/csrfProtection', 'http://i.bixbyjs.org/http/middleware/authenticate', 'http://i.bixbyjs.org/http/middleware/ceremony' ];
/** * Password authentication handler. * * This component provides an HTTP handler that authenticates a username and * password. The credentials are submitted via an HTML form. */ exports = module.exports = function(parse, csrfProtection, authenticate, ceremony) { function establishSession(req, res, next) { req.login(req.user, function(err) { if (err) { return next(err); } return next(); }); } return [ parse('application/x-www-form-urlencoded'), ceremony( csrfProtection(), authenticate('www-password', { session: false }), establishSession ) ]; /* return [ parse('application/x-www-form-urlencoded'), ceremony('login/password', csrfProtection(), authenticate('password'), { through: 'login' }) ]; */ }; exports['@require'] = [ 'http://i.bixbyjs.org/http/middleware/parse', 'http://i.bixbyjs.org/http/middleware/csrfProtection', 'http://i.bixbyjs.org/http/middleware/authenticate', 'http://i.bixbyjs.org/http/middleware/ceremony' ];
Add ability to change input color
// @flow import React, { type ElementRef } from 'react'; import AutosizeInput from 'react-input-autosize'; import { colors, spacing } from '../theme'; import { Div } from '../primitives'; import type { PropsWithStyles } from '../types'; export type InputProps = PropsWithStyles & { cx: string => string | void, /** Reference to the internal element */ innerRef: (ElementRef<*>) => void, /** Set whether the input should be visible. Does not affect input size. */ isHidden: boolean, /** Whether the input is disabled */ isDisabled?: boolean, }; export const css = ({ isDisabled }: InputProps) => ({ margin: spacing.baseUnit / 2, paddingBottom: spacing.baseUnit / 2, paddingTop: spacing.baseUnit / 2, visibility: isDisabled ? 'hidden' : 'visible', color: colors.text, }); const inputStyle = isHidden => ({ background: 0, border: 0, fontSize: 'inherit', opacity: isHidden ? 0 : 1, outline: 0, padding: 0, color: 'inherit', }); const Input = ({ cx, getStyles, innerRef, isHidden, isDisabled, ...props }: InputProps) => ( <Div css={getStyles('input', props)}> <AutosizeInput className={cx('input')} inputRef={innerRef} inputStyle={inputStyle(isHidden)} disabled={isDisabled} {...props} /> </Div> ); export default Input;
// @flow import React, { type ElementRef } from 'react'; import AutosizeInput from 'react-input-autosize'; import { spacing } from '../theme'; import { Div } from '../primitives'; import type { PropsWithStyles } from '../types'; export type InputProps = PropsWithStyles & { cx: string => string | void, /** Reference to the internal element */ innerRef: (ElementRef<*>) => void, /** Set whether the input should be visible. Does not affect input size. */ isHidden: boolean, /** Whether the input is disabled */ isDisabled?: boolean, }; export const css = ({ isDisabled }: InputProps) => ({ margin: spacing.baseUnit / 2, paddingBottom: spacing.baseUnit / 2, paddingTop: spacing.baseUnit / 2, visibility: isDisabled ? 'hidden' : 'visible', }); const inputStyle = isHidden => ({ background: 0, border: 0, fontSize: 'inherit', opacity: isHidden ? 0 : 1, outline: 0, padding: 0, }); const Input = ({ cx, getStyles, innerRef, isHidden, isDisabled, ...props }: InputProps) => ( <Div css={getStyles('input', props)}> <AutosizeInput className={cx('input')} inputRef={innerRef} inputStyle={inputStyle(isHidden)} disabled={isDisabled} {...props} /> </Div> ); export default Input;
Remove delete from stop to avoid errors
const RtmpServer = require('rtmp-server'); const rtmpToHLS = require('./rtmpToHLS'); const { streamKey } = require('../config.json'); const { deleteVideos, log } = require('./utils'); function server(socket) { const rtmpServer = new RtmpServer(); rtmpServer.listen(1935); rtmpServer.on('error', (err) => { log('RTMP server error:', 'yellow'); log(err, 'yellow'); }); rtmpServer.on('client', (client) => { client.on('connect', () => log(`CONNECT ${client.app}`, 'blue')); client.on('play', () => log('PLAY ', 'blue')); client.on('publish', ({ streamName }) => { if (streamKey !== streamName) { log('Publishing error: Wrong stream key', 'red'); return; } deleteVideos(); rtmpToHLS(); socket.broadcast.emit('restart', {}); socket.broadcast.emit('published', {}); log('PUBLISH', 'blue'); }); client.on('stop', () => { socket.broadcast.emit('restart', {}); socket.broadcast.emit('disconeted', {}); log('DISCONNECTED', 'red'); }); }); } module.exports = server;
const RtmpServer = require('rtmp-server'); const rtmpToHLS = require('./rtmpToHLS'); const { streamKey } = require('../config.json'); const { deleteVideos, log } = require('./utils'); function server(socket) { const rtmpServer = new RtmpServer(); rtmpServer.listen(1935); rtmpServer.on('error', (err) => { log('RTMP server error:', 'yellow'); log(err, 'yellow'); }); rtmpServer.on('client', (client) => { client.on('connect', () => log(`CONNECT ${client.app}`, 'blue')); client.on('play', () => log('PLAY ', 'blue')); client.on('publish', ({ streamName }) => { if (streamKey !== streamName) { log('Publishing error: Wrong stream key', 'red'); return; } deleteVideos(); rtmpToHLS(); socket.broadcast.emit('restart', {}); socket.broadcast.emit('published', {}); log('PUBLISH', 'blue'); }); client.on('stop', () => { setTimeout(() => { deleteVideos(); }, 2000); socket.broadcast.emit('restart', {}); socket.broadcast.emit('disconeted', {}); log('DISCONNECTED', 'red'); }); }); } module.exports = server;
Modify exception handling to local config names
# Default settings import ConfigParser import os import pyaudio PROG = 'soundmeter' USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG) USER_LOGFILE = os.path.join(USER_DIR, 'log') USER_CONFIG = os.path.join(USER_DIR, 'config') USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh') config = ConfigParser.ConfigParser() config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG) items = {} if config.has_section(PROG): items = dict(config.items(PROG)) for name in items: try: if name in ['frames_per_buffer', 'format', 'channels', 'rate']: items[name] = int(items[name]) elif name in ['audio_segment_length']: items[name] = float(items[name]) else: raise Exception('Unknown name "%s" in config' % name) except ValueError: raise Exception('Invalid value to "%s" in config' % name) FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048 FORMAT = items.get('format') or pyaudio.paInt16 CHANNELS = items.get('channels') or 2 RATE = items.get('rate') or 44100 AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
# Default settings import ConfigParser import os import pyaudio PROG = 'soundmeter' USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG) USER_LOGFILE = os.path.join(USER_DIR, 'log') USER_CONFIG = os.path.join(USER_DIR, 'config') USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh') config = ConfigParser.ConfigParser() config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG) items = {} if config.has_section(PROG): items = dict(config.items(PROG)) for name in items: try: if name in ['frames_per_buffer', 'format', 'channels', 'rate']: items[name] = int(items[name]) if name in ['audio_segment_length']: items[name] = float(items[name]) except: items[name] = None FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048 FORMAT = items.get('format') or pyaudio.paInt16 CHANNELS = items.get('channels') or 2 RATE = items.get('rate') or 44100 AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
Add timeout to dead links script
from operator import itemgetter from itertools import chain import os import yaml import requests yaml.load_all directory = "_companies" flat = chain.from_iterable def link_status_company(filename): (name, _) = filename.rsplit(".", 1); print("==== {name} ====".format(name=name)) docs = filter(None, yaml.load_all(open(os.path.join(directory, filename)))) positions = flat(map(itemgetter("positions"), filter(lambda doc: "positions" in doc, docs))) def link_status_position(position): title = position["title"] url = position["url"] print("{title} [ {url} ]".format(title=title, url=url)) try: response = requests.get(url, timeout=10) status_code_description = requests.status_codes._codes.get(response.status_code, '-') print("{} {} {}".format(response.status_code, status_code_description, response.history)) except Exception as e: print(e) print() list(map(link_status_position, positions)) list(map(link_status_company, sorted(os.listdir(directory))))
from operator import itemgetter from itertools import chain import os import yaml import requests yaml.load_all directory = "_companies" flat = chain.from_iterable def link_status_company(filename): (name, _) = filename.rsplit(".", 1); print("==== {name} ====".format(name=name)) docs = filter(None, yaml.load_all(open(os.path.join(directory, filename)))) positions = flat(map(itemgetter("positions"), filter(lambda doc: "positions" in doc, docs))) def link_status_position(position): title = position["title"] url = position["url"] print("{title} [ {url} ]".format(title=title, url=url)) response = requests.get(url) status_code_description = requests.status_codes._codes.get(response.status_code, '-') print("{} {} {}".format(response.status_code, status_code_description, response.history)) print() list(map(link_status_position, positions)) list(map(link_status_company, sorted(os.listdir(directory))))
Fix incorrect login url for sign in form on frontpage
<form name="loginform" action="<?php echo wp_login_url(home_url());?>" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
Disable the Inspector panel patch (needs to be fixed on the platform)
/* See license.txt for terms of usage */ "use strict"; module.metadata = { "stability": "experimental" }; const { Cu, Ci } = require("chrome"); const { Trace, TraceError } = require("../core/trace.js").get(module.id); const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const { MarkupView } = devtools["require"]("devtools/markupview/markup-view"); // Patching MarkupView // xxxHonza: Bug 1036949 - New API: MarkupView customization let originalTemplate = MarkupView.prototype.template; MarkupView.prototype.template = function(aName, aDest, aOptions) { let node = originalTemplate.apply(this, arguments); // Needs to be fixed on the platform //this._inspector.emit("markupview-render", node, aName, aDest, aOptions); return node; } function shutdown() { MarkupView.prototype.template = originalTemplate; } // Exports from this module exports.shutdown = shutdown;
/* See license.txt for terms of usage */ "use strict"; module.metadata = { "stability": "experimental" }; const { Cu, Ci } = require("chrome"); const { Trace, TraceError } = require("../core/trace.js").get(module.id); const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const { MarkupView } = devtools["require"]("devtools/markupview/markup-view"); // Patching MarkupView // xxxHonza: Bug 1036949 - New API: MarkupView customization let originalTemplate = MarkupView.prototype.template; MarkupView.prototype.template = function(aName, aDest, aOptions) { let node = originalTemplate.apply(this, arguments); this._inspector.emit("markupview-render", node, aName, aDest, aOptions); return node; } function shutdown() { MarkupView.prototype.template = originalTemplate; } // Exports from this module exports.shutdown = shutdown;
Use real model as basis for mock.
<?php if ( ! defined('BASEPATH')) exit('Invalid file request.'); /** * OmniLog module tests. * * @author Stephen Lewis <stephen@experienceinternet.co.uk> * @copyright Experience Internet * @package Omnilog */ require_once dirname(__FILE__) .'/../mcp.omnilog.php'; require_once dirname(__FILE__) .'/../models/omnilog_model.php'; class Test_omnilog extends Testee_unit_test_case { private $_model; private $_subject; /* -------------------------------------------------------------- * PUBLIC METHODS * ------------------------------------------------------------ */ /** * Constructor. * * @access public * @return void */ public function setUp() { parent::setUp(); Mock::generate('Omnilog_model', get_class($this) .'_mock_model'); $this->_ee->omnilog_model = $this->_get_mock('model'); $this->_model = $this->_ee->omnilog_model; $this->_subject = new Omnilog(); } } /* End of file : test.mod_omnilog.php */ /* File location : third_party/omnilog/tests/test.mod_omnilog.php */
<?php if ( ! defined('BASEPATH')) exit('Invalid file request.'); /** * OmniLog module tests. * * @author Stephen Lewis <stephen@experienceinternet.co.uk> * @copyright Experience Internet * @package Omnilog */ require_once dirname(__FILE__) .'/../mcp.omnilog.php'; require_once dirname(__FILE__) .'/../models/omnilog_model.php'; class Test_omnilog extends Testee_unit_test_case { private $_model; private $_subject; /* -------------------------------------------------------------- * PUBLIC METHODS * ------------------------------------------------------------ */ /** * Constructor. * * @access public * @return void */ public function setUp() { parent::setUp(); Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model'); $this->_ee->omnilog_model = $this->_get_mock('model'); $this->_model = $this->_ee->omnilog_model; $this->_subject = new Omnilog(); } } /* End of file : test.mod_omnilog.php */ /* File location : third_party/omnilog/tests/test.mod_omnilog.php */
Make Client, Service importable from pyservice
""" Copyright (c) 2014, Joseph Cross. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from pyservice.client import Client from pyservice.service import Service __all__ = ["Client", "Service"]
""" Copyright (c) 2014, Joseph Cross. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """
Fix updates of package data
<?php namespace Outlandish\Wpackagist\Storage; use Doctrine\ORM\EntityManagerInterface; use Outlandish\Wpackagist\Entity\PackageData; final class Database extends Provider { /** @var EntityManagerInterface */ private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function load(string $key): ?string { $data = $this->loadFromDb($key); if ($data) { return $data->getValue(); } return null; } public function save(string $key, string $json): bool { // Update or insert as needed. $data = $this->loadFromDb($key); if (!$data) { $data = new PackageData(); } $data->setKey($key); $data->setValue($json); $this->entityManager->persist($data); $this->entityManager->flush(); return true; } protected function loadFromDb(string $key): ?PackageData { return $this->entityManager->getRepository(PackageData::class)->findOneBy(['key' => $key]); } }
<?php namespace Outlandish\Wpackagist\Storage; use Doctrine\ORM\EntityManagerInterface; use Outlandish\Wpackagist\Entity\PackageData; final class Database extends Provider { /** @var EntityManagerInterface */ private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function load(string $key): ?string { $data = $this->entityManager->getRepository(PackageData::class)->findOneBy(['key' => $key]); if ($data) { return $data->getValue(); } return null; } public function save(string $key, string $json): bool { $data = new PackageData(); $data->setKey($key); $data->setValue($json); $this->entityManager->persist($data); $this->entityManager->flush(); return true; } }
Make review feedback not a Markdown widget Review feedback wasn't supposed to be in markdown. Change the widget to a regular text area.
from django import forms from django.forms import Textarea from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": MarkEdit()} def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) self.fields["vote"] = forms.ChoiceField( widget=forms.RadioSelect(), choices=VOTES.CHOICES ) class ReviewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ["text"] widgets = {"text": MarkEdit()} class SpeakerCommentForm(forms.ModelForm): class Meta: model = ProposalMessage fields = ["message"] widgets = {"message": Textarea(attrs={'class': 'fullwidth-textarea'})} class BulkPresentationForm(forms.Form): talk_ids = forms.CharField( max_length=500, help_text="Provide a comma seperated list of talk ids to accept." )
from django import forms from markedit.widgets import MarkEdit from symposion.reviews.models import Review, Comment, ProposalMessage, VOTES class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ["vote", "comment"] widgets = {"comment": MarkEdit()} def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) self.fields["vote"] = forms.ChoiceField( widget=forms.RadioSelect(), choices=VOTES.CHOICES ) class ReviewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ["text"] widgets = {"text": MarkEdit()} class SpeakerCommentForm(forms.ModelForm): class Meta: model = ProposalMessage fields = ["message"] widgets = {"message": MarkEdit()} class BulkPresentationForm(forms.Form): talk_ids = forms.CharField( max_length=500, help_text="Provide a comma seperated list of talk ids to accept." )
Rename the method for getting the compiler.
package com.haskforce.jps.model; import com.intellij.openapi.util.SystemInfo; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsElementFactory; import org.jetbrains.jps.model.JpsElementTypeWithDefaultProperties; import org.jetbrains.jps.model.library.sdk.JpsSdkType; import java.io.File; public class JpsHaskellSdkType extends JpsSdkType<JpsDummyElement> implements JpsElementTypeWithDefaultProperties<JpsDummyElement> { public static final JpsHaskellSdkType INSTANCE = new JpsHaskellSdkType(); @NotNull public static File getExecutable(@NotNull final String path, @NotNull final String command) { return new File(path, SystemInfo.isWindows ? command + ".exe" : command); } @NotNull public static File getGhcExecutable(@NotNull final String sdkHome) { return getExecutable(new File(sdkHome, "bin").getAbsolutePath(), "ghc"); } @NotNull @Override public JpsDummyElement createDefaultProperties() { return JpsElementFactory.getInstance().createDummyElement(); } }
package com.haskforce.jps.model; import com.intellij.openapi.util.SystemInfo; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsElementFactory; import org.jetbrains.jps.model.JpsElementTypeWithDefaultProperties; import org.jetbrains.jps.model.library.sdk.JpsSdkType; import java.io.File; public class JpsHaskellSdkType extends JpsSdkType<JpsDummyElement> implements JpsElementTypeWithDefaultProperties<JpsDummyElement> { public static final JpsHaskellSdkType INSTANCE = new JpsHaskellSdkType(); @NotNull public static File getExecutable(@NotNull final String path, @NotNull final String command) { return new File(path, SystemInfo.isWindows ? command + ".exe" : command); } @NotNull public static File getByteCodeCompilerExecutable(@NotNull final String sdkHome) { return getExecutable(new File(sdkHome, "bin").getAbsolutePath(), "ghc"); } @NotNull @Override public JpsDummyElement createDefaultProperties() { return JpsElementFactory.getInstance().createDummyElement(); } }
Check that the non-plugin events are not caught by the plugin
var Plugin = require('vigour-native/lib/bridge/Plugin') var plugin describe('plugin', function () { it('should be requireable', function () { plugin = require('../../') expect(plugin).instanceOf(Plugin) expect(plugin.key).to.equal('plugin') }) describe('native events', function () { it('should forward the `ready` event', function () { var spy = sinon.spy() plugin.on('ready', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.ready(null, 'message 1', plugin.key) window.vigour.native.bridge.ready(null, 'message 2') expect(spy).calledOnce }) it('should forward native `error` events', function () { var spy = sinon.spy() plugin.on('error', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.error('message 1', plugin.key) window.vigour.native.bridge.error('message 2') expect(spy).calledOnce }) it('should forward pushed messages', function () { var spy = sinon.spy() plugin.on('receive', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.receive(null, 'message 1', plugin.key) window.vigour.native.bridge.receive(null, 'message 2') expect(spy).calledOnce }) }) })
var Plugin = require('vigour-native/lib/bridge/Plugin') var plugin describe('plugin', function () { it('should be requireable', function () { plugin = require('../../') expect(plugin).instanceOf(Plugin) expect(plugin.key).to.equal('plugin') }) describe('native events', function () { it('should forward the `ready` event', function () { var spy = sinon.spy() plugin.on('ready', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.ready(null, 'message', plugin.key) expect(spy).calledOnce }) it('should forward native `error` events', function () { var spy = sinon.spy() plugin.on('error', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.error('message 1', plugin.key) window.vigour.native.bridge.error('message 2') expect(spy).calledOnce }) it('should forward pushed messages', function () { var spy = sinon.spy() plugin.on('receive', spy) // Let's fake a ready event for this plugin window.vigour.native.bridge.receive(null, 'message', plugin.key) expect(spy).calledOnce }) }) })
Fix for using the extension from inside an iframe
// FORKED FROM https://github.com/muaz-khan/WebRTC-Experiment/tree/master/Chrome-Extensions/desktopCapture // this background script is used to invoke desktopCapture API to capture screen-MediaStream. var session = ['screen', 'window']; chrome.runtime.onConnect.addListener(function (port) { // this one is called for each message from "content-script.js" port.onMessage.addListener(function (message) { if(message === 'get-sourceId') { // Tab for which the stream will be created (passed to // chrome.desktopCapture.chooseDesktopMedia). var tab = port.sender.tab; // If the streamId is requested from frame with different url than // its parent according to the documentation ( // https://developer.chrome.com/extensions/desktopCapture ) - // "The stream can only be used by frames in the given tab whose // security origin matches tab.url." That's why we need to change // the url to the url of the frame (the frame is the sender). // Related ticket: // https://bugs.chromium.org/p/chromium/issues/detail?id=425344 tab.url = port.sender.url; chrome.desktopCapture.chooseDesktopMedia(session, tab, onAccessApproved); } }); // "sourceId" will be empty if permission is denied. function onAccessApproved(sourceId) { // if "cancel" button is clicked if(!sourceId || !sourceId.length) { return port.postMessage('PermissionDeniedError'); } port.postMessage({ sourceId: sourceId }); } });
// FORKED FROM https://github.com/muaz-khan/WebRTC-Experiment/tree/master/Chrome-Extensions/desktopCapture // this background script is used to invoke desktopCapture API to capture screen-MediaStream. var session = ['screen', 'window']; chrome.runtime.onConnect.addListener(function (port) { // this one is called for each message from "content-script.js" port.onMessage.addListener(function (message) { if(message === 'get-sourceId') { chrome.desktopCapture.chooseDesktopMedia(session, port.sender.tab, onAccessApproved); } }); // "sourceId" will be empty if permission is denied. function onAccessApproved(sourceId) { // if "cancel" button is clicked if(!sourceId || !sourceId.length) { return port.postMessage('PermissionDeniedError'); } port.postMessage({ sourceId: sourceId }); } });
Remove need for static pages
# OSU SPS Website Build Script import os def loadFile( src, prefx ): out = "" for line in open( src, 'r' ): out += prefx + line return out def outputFile( name, content ): file = open( name, 'w' ) file.write( content ) file.close() out_folder = "output/" src_folder = "src/" includes_folder = src_folder + "includes/" header = loadFile( includes_folder + "header.html", "" ) header = header.replace( "[STYLE]", loadFile( includes_folder + "style.css", "\t" ) ) header = header.replace( "[SCRIPT]", loadFile( includes_folder + "script.js", "\t" ) ) footer = loadFile( includes_folder + "footer.html", "" ) names = set() for name in os.listdir( src_folder ): names.add( name ) names.remove( includes_folder[ len( src_folder ) : -1 ] ) for name in names: raw = loadFile( src_folder + name, "" ) raw = header + raw + footer outputFile( out_folder + name, raw )
# OSU SPS Website Build Script def loadFile( src, prefx ): out = "" for line in open( src, 'r' ): out += prefx + line return out def outputFile( name, content ): file = open( name, 'w' ) file.write( content ) file.close() out_folder = "output/" src_folder = "src/" includes_folder = src_folder + "includes/" header = loadFile( includes_folder + "header.html", "" ) header = header.replace( "[STYLE]", loadFile( includes_folder + "style.css", "\t" ) ) header = header.replace( "[SCRIPT]", loadFile( includes_folder + "script.js", "\t" ) ) footer = loadFile( includes_folder + "footer.html", "" ) names = [ "index.html" ] for name in names: raw = loadFile( src_folder + name, "" ) raw = header + raw + footer outputFile( out_folder + name, raw )
Add missing option to tryCreatePlayer
//= require asciinema-player function tryCreatePlayer(parentNode, asciicast, options) { function createPlayer() { asciinema_player.core.CreatePlayer( parentNode, asciicast.url, { width: asciicast.width, height: asciicast.height, snapshot: asciicast.snapshot, speed: options.speed, autoPlay: options.autoPlay, loop: options.loop, preload: options.preload, startAt: options.startAt, fontSize: options.fontSize, theme: options.theme, title: options.title, author: options.author, authorURL: options.authorURL, authorImgURL: options.authorImgURL } ); } function fetch() { $.get('/api/asciicasts/' + asciicast.id + '.json', function(data) { asciicast = data; checkReadiness(); }); } function checkReadiness() { if (asciicast.url) { $('.processing-info').remove(); createPlayer(); } else { $('.processing-info').show(); setTimeout(fetch, 2000); } } checkReadiness(); }
//= require asciinema-player function tryCreatePlayer(parentNode, asciicast, options) { function createPlayer() { asciinema_player.core.CreatePlayer( parentNode, asciicast.url, { width: asciicast.width, height: asciicast.height, snapshot: asciicast.snapshot, speed: options.speed, autoPlay: options.autoPlay, loop: options.loop, startAt: options.startAt, fontSize: options.fontSize, theme: options.theme, title: options.title, author: options.author, authorURL: options.authorURL, authorImgURL: options.authorImgURL } ); } function fetch() { $.get('/api/asciicasts/' + asciicast.id + '.json', function(data) { asciicast = data; checkReadiness(); }); } function checkReadiness() { if (asciicast.url) { $('.processing-info').remove(); createPlayer(); } else { $('.processing-info').show(); setTimeout(fetch, 2000); } } checkReadiness(); }
Use where in and cast to array. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Model\Scopes; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Eloquent\Builder; class UserWithRoleScope implements Scope { /** * The selected role. * * @var string|array */ protected $role; /** * Construct the scope. * * @param string|array $role */ public function __construct($role) { $this->role = $role; } /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * * @return void */ public function apply(Builder $builder, Model $model) { if (empty($this->role)) { return; } $builder->whereHas('roles', function ($query) { $query->whereIn('name', (array) $this->role); }); } }
<?php namespace Orchestra\Model\Scopes; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Eloquent\Builder; class UserWithRoleScope implements Scope { /** * The selected role. * * @var string */ protected $role; /** * Construct the scope. * * @param string $role */ public function __construct($role) { $this->role = $role; } /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * * @return void */ public function apply(Builder $builder, Model $model) { if (empty($this->role)) { return; } $builder->whereHas('roles', function ($query) { $query->where('name', '=', $this->role); }); } }
2.5.1: Fix reset GridItem color for SPA preview
from PyQt5.QtGui import QFont from cadnano.gui.views.styles import BLUE_STROKE, GRAY_STROKE, THE_FONT # Slice Sizing SLICE_HELIX_RADIUS = 15. SLICE_HELIX_STROKE_WIDTH = 0.5 SLICE_HELIX_MOD_HILIGHT_WIDTH = 1 EMPTY_HELIX_STROKE_WIDTH = 0.25 # Z values # bottom ZSLICEHELIX = 40 ZSELECTION = 50 ZDESELECTOR = 60 ZWEDGEGIZMO = 100 ZPXIGROUP = 150 ZPARTITEM = 200 # top # Part appearance SLICE_FILL = "#f6f6f6" DEFAULT_PEN_WIDTH = 0 # cosmetic DEFAULT_ALPHA = 2 SELECTED_COLOR = '#5a8bff' SELECTED_PEN_WIDTH = 2 SELECTED_ALPHA = 0 SLICE_NUM_FONT = QFont(THE_FONT, 10, QFont.Bold) USE_TEXT_COLOR = "#ffffff" SLICE_TEXT_COLOR = "#000000" ACTIVE_STROKE = '#cccc00' ACTIVE_GRID_DOT_COLOR = '#0000ff' DEFAULT_GRID_DOT_COLOR = '#0000ff' VHI_HINT_ACTIVE_STROKE = BLUE_STROKE VHI_HINT_INACTIVE_STROKE = '#cccccc'
from PyQt5.QtGui import QFont from cadnano.gui.views.styles import BLUE_STROKE, GRAY_STROKE, THE_FONT # Slice Sizing SLICE_HELIX_RADIUS = 15. SLICE_HELIX_STROKE_WIDTH = 0.5 SLICE_HELIX_MOD_HILIGHT_WIDTH = 1 EMPTY_HELIX_STROKE_WIDTH = 0.25 # Z values # bottom ZSLICEHELIX = 40 ZSELECTION = 50 ZDESELECTOR = 60 ZWEDGEGIZMO = 100 ZPXIGROUP = 150 ZPARTITEM = 200 # top # Part appearance SLICE_FILL = "#ffffff" DEFAULT_PEN_WIDTH = 0 # cosmetic DEFAULT_ALPHA = 2 SELECTED_COLOR = '#5a8bff' SELECTED_PEN_WIDTH = 2 SELECTED_ALPHA = 0 SLICE_NUM_FONT = QFont(THE_FONT, 10, QFont.Bold) USE_TEXT_COLOR = "#ffffff" SLICE_TEXT_COLOR = "#000000" ACTIVE_STROKE = '#cccc00' ACTIVE_GRID_DOT_COLOR = '#0000ff' DEFAULT_GRID_DOT_COLOR = '#0000ff' VHI_HINT_ACTIVE_STROKE = BLUE_STROKE VHI_HINT_INACTIVE_STROKE = '#cccccc'
Add alias for the Guard contract to auth.driver
<?php namespace MyBB\Auth; use Illuminate\Auth\AuthServiceProvider as LaravelAuth; use MyBB\Auth\Hashing\phpass\PasswordHash; /** * This class is only used to register our own subclass of the AuthManager instead of Laravel's default one */ class AuthServiceProvider extends LaravelAuth { /** * Register the service provider. * * @return void */ public function register() { parent::register(); // Bind our Password Hashing method as singleton $this->app->singleton('MyBB\Auth\Hashing\phpass\PasswordHash', function($app) { // Make sure the class gets properly initialized $phpass = new PasswordHash(8, true); $phpass->PasswordHash(8, true); return $phpass; }); } /** * Register the authenticator services. * * @return void */ protected function registerAuthenticator() { $this->app->singleton('auth', function ($app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->singleton('auth.driver', function ($app) { return $app['auth']->driver(); }); $this->app->alias('auth.driver', 'MyBB\Auth\Contracts\Guard'); } }
<?php namespace MyBB\Auth; use Illuminate\Auth\AuthServiceProvider as LaravelAuth; use MyBB\Auth\Hashing\phpass\PasswordHash; /** * This class is only used to register our own subclass of the AuthManager instead of Laravel's default one */ class AuthServiceProvider extends LaravelAuth { /** * Register the service provider. * * @return void */ public function register() { parent::register(); // Bind our Password Hashing method as singleton $this->app->singleton('MyBB\Auth\Hashing\phpass\PasswordHash', function($app) { // Make sure the class gets properly initialized $phpass = new PasswordHash(8, true); $phpass->PasswordHash(8, true); return $phpass; }); } /** * Register the authenticator services. * * @return void */ protected function registerAuthenticator() { $this->app->singleton('auth', function ($app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->singleton('auth.driver', function ($app) { return $app['auth']->driver(); }); } }
Use star args to invoke apply_async
from __future__ import absolute_import import celery import os import os.path import sys # Add the project to the python path sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir)) # Configure the application only if it seemingly isnt already configured from django.conf import settings if not settings.configured: from sentry.runner import configure configure() from sentry.utils import metrics class Celery(celery.Celery): def on_configure(self): from raven.contrib.django.models import client from raven.contrib.celery import register_signal, register_logger_signal # register a custom filter to filter out duplicate logs register_logger_signal(client) # hook into the Celery error handler register_signal(client) app = Celery('sentry') OriginalTask = app.Task class SentryTask(OriginalTask): def apply_async(self, *args, **kwargs): key = 'jobs.delay' instance = self.name with metrics.timer(key, instance=instance): return OriginalTask.apply_async(self, *args, **kwargs) app.Task = SentryTask # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object(settings) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) if __name__ == '__main__': app.start()
from __future__ import absolute_import import celery import os import os.path import sys # Add the project to the python path sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir)) # Configure the application only if it seemingly isnt already configured from django.conf import settings if not settings.configured: from sentry.runner import configure configure() from sentry.utils import metrics class Celery(celery.Celery): def on_configure(self): from raven.contrib.django.models import client from raven.contrib.celery import register_signal, register_logger_signal # register a custom filter to filter out duplicate logs register_logger_signal(client) # hook into the Celery error handler register_signal(client) app = Celery('sentry') OriginalTask = app.Task class SentryTask(OriginalTask): def apply_async(self, args, kwargs): key = 'jobs.delay' instance = self.name with metrics.timer(key, instance=instance): return OriginalTask.apply_async(self, args, kwargs) app.Task = SentryTask # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object(settings) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) if __name__ == '__main__': app.start()
Use nltk to extract text from html data
# coding: utf-8 """ Script to download the raw data from http://www.rsssf.com/ The data was processed mostly by interactive sessions in ipython. Almost every file had it's own format, so there is no point in trying to automate it in a fully automatic script, but this downloading script may be useful for future dowloads. """ import nltk import requests YEAR_URL = 'http://www.rsssf.com/tablesa/arg%i.html' FILE_PATH = 'data/%i.txt' YEARS = range(90, 100) + range(2000, 2016) for year in YEARS: print 'Year:', year try: html = requests.get(YEAR_URL % year).content text = nltk.clean_html(html) with open(FILE_PATH % year, 'w') as data_file: data_file.write(text) print 'Wrote file with', len(text), 'chars' except: print 'ERROR!'
# coding: utf-8 """ Script to download the raw data from http://www.rsssf.com/ The data was processed mostly by interactive sessions in ipython. Almost every file had it's own format, so there is no point in trying to automate it in a fully automatic script, but this downloading script may be useful for future dowloads. """ import requests YEAR_URL = 'http://www.rsssf.com/tablesa/arg%i.html' FILE_PATH = 'data/%i.txt' YEARS = range(90, 100) + range(2000, 2016) for year in YEARS: print 'Year:', year try: data = requests.get(YEAR_URL % year).content with open(FILE_PATH % year, 'w') as data_file: data_file.write(data) print 'Wrote file with', len(data), 'chars' except: print 'ERROR!'
Change custom tag name [rev. matthew.gordon]
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.searchcomponents.core.search; import com.hp.autonomy.types.requests.Documents; import java.io.Serializable; import java.util.List; import java.util.Set; public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> { String HIGHLIGHT_START_TAG = "<HavenSearch-QueryText-Placeholder>"; String HIGHLIGHT_END_TAG = "</HavenSearch-QueryText-Placeholder>"; Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E; Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E; List<D> findSimilar(Set<S> indexes, String reference) throws E; }
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.searchcomponents.core.search; import com.hp.autonomy.types.requests.Documents; import java.io.Serializable; import java.util.List; import java.util.Set; public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> { String HIGHLIGHT_START_TAG = "<Find-IOD-QueryText-Placeholder>"; String HIGHLIGHT_END_TAG = "</Find-IOD-QueryText-Placeholder>"; Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E; Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E; List<D> findSimilar(Set<S> indexes, String reference) throws E; }
chore(pins): Update dict pin in prep for release - Update dict pin in prep for release
from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'psqlgraph', 'gdcdictionary', 'dictionaryutils>=2.0.0,<3.0.0', 'cdisutils', ], package_data={ "gdcdatamodel": [ "xml_mappings/*.yaml", ] }, dependency_links=[ 'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils', 'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph', 'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary', ], entry_points={ 'console_scripts': [ 'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main' ] }, )
from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'psqlgraph', 'gdcdictionary', 'dictionaryutils>=2.0.0,<3.0.0', 'cdisutils', ], package_data={ "gdcdatamodel": [ "xml_mappings/*.yaml", ] }, dependency_links=[ 'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils', 'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph', 'git+https://github.com/NCI-GDC/gdcdictionary.git@release/marvin#egg=gdcdictionary', ], entry_points={ 'console_scripts': [ 'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main' ] }, )
Revert a debugging change that slipped in. git-svn-id: 48f3d5eb0141859d8d7d81547b6bd7b3dde885f8@186 8655a95f-0638-0410-abc2-2f1ed958ef3d
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): cursor.execute(statement)
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): try: cursor.execute(statement) except: print statement print sql raise Exception(statement)
Change adminSettings/save to accept a list of settings instead of just one
package mil.dds.anet.resources; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.AdminSetting; import mil.dds.anet.database.AdminDao; import mil.dds.anet.graphql.GraphQLFetcher; import mil.dds.anet.graphql.IGraphQLResource; import mil.dds.anet.views.AbstractAnetBean; @Path("/api/admin") public class AdminResource implements IGraphQLResource { private AdminDao dao; public AdminResource(AnetObjectEngine engine) { this.dao = engine.getAdminDao(); } @GET @GraphQLFetcher @Path("/") public List<AdminSetting> getAll() { return dao.getAllSettings(); } @POST @Path("/save") @RolesAllowed("ADMINISTRATOR") public Response save(List<AdminSetting> settings) { for (AdminSetting setting : settings) { dao.saveSetting(setting); } return Response.ok().build(); } @Override public String getDescription() { return "Admin Resources";} @Override public Class<? extends AbstractAnetBean> getBeanClass() { return AdminSetting.class; } }
package mil.dds.anet.resources; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.AdminSetting; import mil.dds.anet.database.AdminDao; import mil.dds.anet.graphql.GraphQLFetcher; import mil.dds.anet.graphql.IGraphQLResource; import mil.dds.anet.views.AbstractAnetBean; @Path("/api/admin") public class AdminResource implements IGraphQLResource { private AdminDao dao; public AdminResource(AnetObjectEngine engine) { this.dao = engine.getAdminDao(); } @GET @GraphQLFetcher @Path("/") public List<AdminSetting> getAll() { return dao.getAllSettings(); } @POST @Path("/save") @RolesAllowed("ADMINISTRATOR") public Response save(AdminSetting setting) { dao.saveSetting(setting); return Response.ok().build(); } @Override public String getDescription() { return "Admin Resources";} @Override public Class<? extends AbstractAnetBean> getBeanClass() { return AdminSetting.class; } }