text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update yaml method to make CodeFactor happy
#!/usr/bin/env python # utility script to generate readme information based on CSV and datapackage # # pip install pandas # usage: # python readme_info.py datapackage import yaml import sys import pandas as pd def readme_info(df, dp_resource): print('1. Number of fields: %d\n' % len(df.columns)) print('2. Number of rows: {:,}\n'.format(len(df))) schema_fields = dp_resource['schema']['fields'] assert len(schema_fields) == len(df.columns) field_info = {field['name']: field for field in schema_fields} print('3. Field List:') for col in df.columns: print('%s : %s' % (col, field_info[col]['description'])) if __name__ == '__main__': if len(sys.argv) < 2: print('Please provide path to frictionless datapackage file') exit(0) with open(sys.argv[1]) as packageyaml: datapackage = yaml.safe_load(packageyaml) for resource_dict in datapackage['resources']: csvfile = resource_dict['path'] print('Inspecting %s...\n\n' % csvfile) df = pd.read_csv(csvfile) readme_info(df, resource_dict)
#!/usr/bin/env python # utility script to generate readme information based on CSV and datapackage # # pip install pandas # usage: # python readme_info.py datapackage import yaml import sys import pandas as pd def readme_info(df, dp_resource): print('1. Number of fields: %d\n' % len(df.columns)) print('2. Number of rows: {:,}\n'.format(len(df))) schema_fields = dp_resource['schema']['fields'] assert len(schema_fields) == len(df.columns) field_info = {field['name']: field for field in schema_fields} print('3. Field List:') for col in df.columns: print('%s : %s' % (col, field_info[col]['description'])) if __name__ == '__main__': if len(sys.argv) < 2: print('Please provide path to frictionless datapackage file') exit(0) with open(sys.argv[1]) as packageyaml: datapackage = yaml.load(packageyaml) for resource_dict in datapackage['resources']: csvfile = resource_dict['path'] print('Inspecting %s...\n\n' % csvfile) df = pd.read_csv(csvfile) readme_info(df, resource_dict)
Fix inaccurate docstring for dashboard issue count
from sqlalchemy import func from catwatch.blueprints.user.models import db, User from catwatch.blueprints.issue.models import Issue class Dashboard(object): @classmethod def group_and_count_users(cls): """ Perform a group by/count on all user types. :return: List of results """ count = func.count(User.role) return db.session.query(count, User.role).group_by(User.role).all() @classmethod def group_and_count_issues(cls): """ Perform a group by/count on all issue types. :return: List of results """ count = func.count(Issue.status) return db.session.query(count, Issue.status).group_by( Issue.status).all()
from sqlalchemy import func from catwatch.blueprints.user.models import db, User from catwatch.blueprints.issue.models import Issue class Dashboard(object): @classmethod def group_and_count_users(cls): """ Perform a group by/count on all user types. :return: List of results """ count = func.count(User.role) return db.session.query(count, User.role).group_by(User.role).all() @classmethod def group_and_count_issues(cls): """ Perform a group by/count on all user types. :return: List of results """ count = func.count(Issue.status) return db.session.query(count, Issue.status).group_by( Issue.status).all()
Add <yo-rc.json> to <configuring> priority
'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay( 'Welcome to the doozie ' + chalk.red('generator-sys-angular') + ' generator!' )); var prompts = [{ type: 'confirm', name: 'someOption', message: 'Would you like to enable this option?', default: true }]; this.prompt(prompts, function (props) { this.props = props; // To access props later use this.props.someOption; done(); }.bind(this)); }, configuring: function() { this.config.save(); }, writing: function () { this.fs.copy( this.templatePath('dummyfile.txt'), this.destinationPath('dummyfile.txt') ); } });
'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay( 'Welcome to the doozie ' + chalk.red('generator-sys-angular') + ' generator!' )); var prompts = [{ type: 'confirm', name: 'someOption', message: 'Would you like to enable this option?', default: true }]; this.prompt(prompts, function (props) { this.props = props; // To access props later use this.props.someOption; done(); }.bind(this)); }, writing: function () { this.fs.copy( this.templatePath('dummyfile.txt'), this.destinationPath('dummyfile.txt') ); } });
Fix TicketedEventType import to not flush search
<?php namespace App\Console\Commands\Import; use App\Models\Membership\TicketedEventType; class ImportTicketedEventTypesFull extends AbstractImportCommand { protected $signature = 'import:events-ticketed-types-full {--y|yes : Answer "yes" to all prompts}'; protected $description = "Import all ticketed event types data"; public function handle() { $this->api = env('EVENTS_DATA_SERVICE_URL'); if( !$this->reset() ) { return false; } $this->importTicketedEventTypes(); } protected function importTicketedEventTypes() { return $this->import( 'Membership', TicketedEventType::class, 'event-types' ); } protected function reset() { // We only need to clear a table, not flush a search index return $this->resetData( [], 'ticketed_event_types' ); } protected function save( $datum, $model, $transformer ) { // TODO: Determine if this is still necessary $datum->source = 'galaxy'; return parent::save( $datum, $model, $transformer ); } }
<?php namespace App\Console\Commands\Import; use App\Models\Membership\TicketedEventType; class ImportTicketedEventTypesFull extends AbstractImportCommand { protected $signature = 'import:events-ticketed-types-full {--y|yes : Answer "yes" to all prompts}'; protected $description = "Import all ticketed event types data"; public function handle() { $this->api = env('EVENTS_DATA_SERVICE_URL'); if( !$this->reset() ) { return false; } $this->importTicketedEventTypes(); } protected function importTicketedEventTypes() { return $this->import( 'Membership', TicketedEventType::class, 'event-types' ); } protected function reset() { return $this->resetData( TicketedEventType::class, 'ticketed_event_types' ); } protected function save( $datum, $model, $transformer ) { // TODO: Determine if this is still necessary $datum->source = 'galaxy'; return parent::save( $datum, $model, $transformer ); } }
Use develop for djsonb repository
#!/usr/bin/env python from setuptools import setup, find_packages tests_require = [] setup( name='ashlar', version='0.0.2', description='Define and validate schemas for metadata for geotemporal event records', author='Azavea, Inc.', author_email='info@azavea.com', keywords='gis jsonschema', packages=find_packages(exclude=['tests']), dependency_links=[ 'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.6' ], install_requires=[ 'Django ==1.8.6', 'djangorestframework >=3.1.1', 'djangorestframework-gis >=0.8.1', 'django-filter >=0.9.2', 'djsonb >=0.1.6', 'jsonschema >=2.4.0', 'psycopg2 >=2.6', 'django-extensions >=1.6.1', 'python-dateutil >=2.4.2', 'PyYAML >=3.11', 'pytz >=2015.7', 'requests >=2.8.1' ], extras_require={ 'dev': [], 'test': tests_require }, test_suite='tests', tests_require=tests_require, )
#!/usr/bin/env python from setuptools import setup, find_packages tests_require = [] setup( name='ashlar', version='0.0.2', description='Define and validate schemas for metadata for geotemporal event records', author='Azavea, Inc.', author_email='info@azavea.com', keywords='gis jsonschema', packages=find_packages(exclude=['tests']), dependency_links=[ 'https://github.com/azavea/djsonb/tarball/feature/pattern-search-OR#egg=djsonb-0.1.6' ], install_requires=[ 'Django ==1.8.6', 'djangorestframework >=3.1.1', 'djangorestframework-gis >=0.8.1', 'django-filter >=0.9.2', 'djsonb >=0.1.6', 'jsonschema >=2.4.0', 'psycopg2 >=2.6', 'django-extensions >=1.6.1', 'python-dateutil >=2.4.2', 'PyYAML >=3.11', 'pytz >=2015.7', 'requests >=2.8.1' ], extras_require={ 'dev': [], 'test': tests_require }, test_suite='tests', tests_require=tests_require, )
Revert "Attempt to fix provider injection" This reverts commit 436801481c2aab67a2b55521a32a476cd88687dc.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require js-routes //= require bootstrap-sprockets //= require bootstrap/popover //= require angular/angular //= require angular-resource/angular-resource //= require angular-route/angular-route //= require angular-ui-router //= require angular-rails-templates //= require_tree ./templates //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require js-routes //= require bootstrap-sprockets //= require bootstrap/popover //= require angular/angular.min //= require angular-resource/angular-resource.min //= require angular-route/angular-route.min //= require angular-ui-router //= require angular-rails-templates //= require_tree ./templates //= require_tree .
Remove spurious no cover pragma
import numpy as np from fastats.core.decorator import fs def value(x): return x @fs def single_pass(x): """ Performs a single iteration over the first dimension of `x`. Tests ----- >>> def square(x): ... return x * x >>> data = np.arange(10) >>> single_pass(data, value=square) array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) >>> import math >>> def calc(x): ... return 2 * math.log(x) >>> single_pass(data[1:], value=calc) array([0, 1, 2, 2, 3, 3, 3, 4, 4]) """ result = np.zeros_like(x) for i in range(x.shape[0]): result[i] = value(x[i]) return result if __name__ == '__main__': import pytest pytest.main([__file__])
import numpy as np from fastats.core.decorator import fs def value(x): # pragma: no cover return x @fs def single_pass(x): """ Performs a single iteration over the first dimension of `x`. Tests ----- >>> def square(x): ... return x * x >>> data = np.arange(10) >>> single_pass(data, value=square) array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) >>> import math >>> def calc(x): ... return 2 * math.log(x) >>> single_pass(data[1:], value=calc) array([0, 1, 2, 2, 3, 3, 3, 4, 4]) """ result = np.zeros_like(x) for i in range(x.shape[0]): result[i] = value(x[i]) return result if __name__ == '__main__': import pytest pytest.main([__file__])
Update crossfilter to gray/blue scheme Same as in https://vega.github.io/editor/#/examples/vega-lite/interactive_layered_crossfilter
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # gray background with selection background = base.encode( color=alt.value('#ddd') ).add_selection(brush) # blue highlights on the transformed data highlight = base.transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # blue background with selection background = base.add_selection(brush) # yellow highlights on the transformed data highlight = base.encode( color=alt.value('goldenrod') ).transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
Fix typo (exists -> exits)
package main import ( "flag" "fmt" "os" "time" _ "github.com/jackwilsdon/svnwatch/types" ) func fatalf(format interface{}, a ...interface{}) { fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...)) os.Exit(1) } func main() { configDir := flag.String("config", "/etc/svnwatch", "the configuration directory for svnwatch") interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exits after a single check)") flag.Parse() watcher, err := loadWatcher(*configDir) if *interval < 0 { fatalf("%s: invalid interval: %d", os.Args[0], *interval) } if err != nil { fatalf(err) } for { if err := watcher.update(); err != nil { fatalf(err) } if err := watcher.save(*configDir); err != nil { fatalf(err) } if *interval > 0 { time.Sleep(time.Duration(*interval) * time.Second) } else { break } } }
package main import ( "flag" "fmt" "os" "time" _ "github.com/jackwilsdon/svnwatch/types" ) func fatalf(format interface{}, a ...interface{}) { fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...)) os.Exit(1) } func main() { configDir := flag.String("config", "/etc/svnwatch", "the configuration directory for svnwatch") interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exists after a single check)") flag.Parse() watcher, err := loadWatcher(*configDir) if *interval < 0 { fatalf("%s: invalid interval: %d", os.Args[0], *interval) } if err != nil { fatalf(err) } for { if err := watcher.update(); err != nil { fatalf(err) } if err := watcher.save(*configDir); err != nil { fatalf(err) } if *interval > 0 { time.Sleep(time.Duration(*interval) * time.Second) } else { break } } }
Add a note about repushing app for env to take effect Signed-off-by: Damien Le Berrigaud <99e6b749acbfbe2a596df99e91d24d6e1fdbee00@pivotallabs.com>
package commands import ( "cf/api" "cf/configuration" term "cf/terminal" "github.com/codegangsta/cli" ) type SetEnv struct { ui term.UI appRepo api.ApplicationRepository } func NewSetEnv(ui term.UI, appRepo api.ApplicationRepository) (se SetEnv) { se.ui = ui se.appRepo = appRepo return } func (se SetEnv) Run(c *cli.Context) { appName := c.Args()[0] varName := c.Args()[1] varValue := c.Args()[2] config, err := configuration.Load() if err != nil { se.ui.Failed("Error loading configuration", err) return } app, err := se.appRepo.FindByName(config, appName) if err != nil { se.ui.Failed("App does not exist.", err) return } se.ui.Say("Updating env variable %s for app %s...", varName, appName) err = se.appRepo.SetEnv(config, app, varName, varValue) if err != nil { se.ui.Failed("Failed setting env", err) return } se.ui.Ok() se.ui.Say("TIP: Use 'cf push' to ensure your env variable changes take effect.") }
package commands import ( "cf/api" "cf/configuration" term "cf/terminal" "github.com/codegangsta/cli" ) type SetEnv struct { ui term.UI appRepo api.ApplicationRepository } func NewSetEnv(ui term.UI, appRepo api.ApplicationRepository) (se SetEnv) { se.ui = ui se.appRepo = appRepo return } func (se SetEnv) Run(c *cli.Context) { appName := c.Args()[0] varName := c.Args()[1] varValue := c.Args()[2] config, err := configuration.Load() if err != nil { se.ui.Failed("Error loading configuration", err) return } app, err := se.appRepo.FindByName(config, appName) if err != nil { se.ui.Failed("App does not exist.", err) return } se.ui.Say("Updating env variable %s for app %s...", varName, appName) err = se.appRepo.SetEnv(config, app, varName, varValue) if err != nil { se.ui.Failed("Failed setting env", err) return } se.ui.Ok() }
Switch to memcachier dev plan
import logging import os import json import TileStache if 'AWS_ACCESS_KEY_ID' in os.environ and \ 'AWS_SECRET_ACCESS_KEY' in os.environ: cache = { "name": "S3", "bucket": "telostats-tiles", "access": os.environ['AWS_ACCESS_KEY_ID'], "secret": os.environ['AWS_SECRET_ACCESS_KEY'] } else: cache = {"name": "Test"} cache = { 'name': 'Memcache', 'servers': [os.environ.get('MEMCACHIER_SERVERS')], 'username': os.environ.get('MEMCACHIER_USERNAME'), 'password': os.environ.get('MEMCACHIER_PASSWORD'), } config_dict = { "cache": cache, "layers": { "telaviv": { "provider": {"name": "mbtiles", "tileset": "Telostats.mbtiles"}, "projection": "spherical mercator" } } } config = TileStache.Config.buildConfiguration(config_dict, '.') application = TileStache.WSGITileServer(config=config, autoreload=False)
import logging import os import json import TileStache if 'AWS_ACCESS_KEY_ID' in os.environ and \ 'AWS_SECRET_ACCESS_KEY' in os.environ: cache = { "name": "S3", "bucket": "telostats-tiles", "access": os.environ['AWS_ACCESS_KEY_ID'], "secret": os.environ['AWS_SECRET_ACCESS_KEY'] } else: cache = {"name": "Test"} cache = { 'name': 'memcache', 'servers': [os.environ.get('MEMCACHE_SERVERS')], 'username': os.environ.get('MEMCACHE_USERNAME'), 'password': os.environ.get('MEMCACHE_PASSWORD'), } config_dict = { "cache": cache, "layers": { "telaviv": { "provider": {"name": "mbtiles", "tileset": "Telostats.mbtiles"}, "projection": "spherical mercator" } } } config = TileStache.Config.buildConfiguration(config_dict, '.') application = TileStache.WSGITileServer(config=config, autoreload=False)
chore(ci): Add console logs for deploy status
var fs = require("fs"); var path = require("path"); var ShopifyAPI = require("shopify-node-api"); var pageId = process.env.SHOPIFY_PAGE_ID; var Shopify = new ShopifyAPI({ shop: process.env.SHOPIFY_SHOP, shopify_api_key: process.env.SHOPIFY_API_KEY, access_token: process.env.SHOPIFY_API_PASSWORD }); var indexPagePath = path.join(__dirname, "..", "dist", "index.html"); fs.readFile(indexPagePath, "utf-8", function (err, data) { if (!err) { var put_data = { page: { body_html: data } }; console.log("Deploying Page Body: ", data); Shopify.put("/admin/pages/" + pageId + ".json", put_data, function (err, data, headers) { if (err) { console.error("Failed to Deploy during API call"); return 0; } else { console.log("Deploy Success"); return 1; } }); } else { console.error("Error reading file: ", err); } });
console.log("Deploying Application..."); var fs = require("fs"); var path = require("path"); var ShopifyAPI = require("shopify-node-api"); var pageId = process.env.SHOPIFY_PAGE_ID; var Shopify = new ShopifyAPI({ shop: process.env.SHOPIFY_SHOP, shopify_api_key: process.env.SHOPIFY_API_KEY, access_token: process.env.SHOPIFY_API_PASSWORD }); var indexPagePath = path.join(__dirname, "..", "dist", "index.html"); fs.readFile(indexPagePath, "utf-8", function (err, data) { if (!err) { var put_data = { page: { body_html: data } }; Shopify.put("/admin/pages/" + pageId + ".json", put_data, function (err, data, headers) { if (err) { console.error("Failed to Deploy during API call"); return 0; } else { console.log("Deploy Success"); return 1; } }); } });
Stop setting routing param in sfRequest
<?php /* * This file is part of the Access to Memory (AtoM) software. * * Access to Memory (AtoM) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Access to Memory (AtoM) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>. */ class QubitMeta extends sfFilter { public function execute($filterChain) { $context = $this->getContext(); $context->response->addMeta('title', sfConfig::get('app_siteTitle')); $context->response->addMeta('description', sfConfig::get('app_siteDescription')); $filterChain->execute(); } }
<?php /* * This file is part of the Access to Memory (AtoM) software. * * Access to Memory (AtoM) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Access to Memory (AtoM) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>. */ class QubitMeta extends sfFilter { public function execute($filterChain) { $context = $this->getContext(); $context->response->addMeta('title', sfConfig::get('app_siteTitle')); $context->response->addMeta('description', sfConfig::get('app_siteDescription')); foreach (array('actor_template', 'informationobject_template', 'repository_template') as $name) { if (isset($context->request[$name])) { $context->routing->setDefaultParameter($name, $context->request[$name]); } else { $context->routing->setDefaultParameter($name, sfConfig::get('app_default_template_'.substr($name, 0, -9))); } } $filterChain->execute(); } }
Use shallowEqual to prevent false-positive values
/* @flow */ import { shallowEqual } from 'recompose' import { objectEach } from 'fela-utils' import createTheme from './createTheme' export default function ThemeProviderFactory( BaseComponent: any, renderChildren: Function, statics?: Object ): any { class ThemeProvider extends BaseComponent { theme: Object constructor(props: Object, context: Object) { super(props, context) const previousTheme = !props.overwrite && this.context.theme this.theme = createTheme(props.theme, previousTheme) } componentWillReceiveProps(nextProps: Object): void { if (shallowEqual(this.props.theme, nextProps.theme) === false) { this.theme.update(nextProps.theme) } } shouldComponentUpdate(nextProps: Object): boolean { return shallowEqual(this.props.theme, nextProps.theme) === false } getChildContext(): Object { return { theme: this.theme } } render(): Object { return renderChildren(this.props.children) } } if (statics) { objectEach(statics, (value, key) => { ThemeProvider[key] = value }) } return ThemeProvider }
/* @flow */ import { shallowEqual } from 'recompose' import { objectEach } from 'fela-utils' import createTheme from './createTheme' export default function ThemeProviderFactory( BaseComponent: any, renderChildren: Function, statics?: Object ): any { class ThemeProvider extends BaseComponent { theme: Object constructor(props: Object, context: Object) { super(props, context) const previousTheme = !props.overwrite && this.context.theme this.theme = createTheme(props.theme, previousTheme) } componentWillReceiveProps(nextProps: Object): void { if (this.props.theme !== nextProps.theme) { this.theme.update(nextProps.theme) } } shouldComponentUpdate(nextProps: Object): boolean { return shallowEqual(this.props.theme, nextProps.theme) === false } getChildContext(): Object { return { theme: this.theme } } render(): Object { return renderChildren(this.props.children) } } if (statics) { objectEach(statics, (value, key) => { ThemeProvider[key] = value }) } return ThemeProvider }
Migrate deprecated jest testUrl to testEnvironmentOptions.url
// For a detailed explanation regarding each configuration property, visit: // https://jestjs.io/docs/en/configuration.html module.exports = { roots: ["<rootDir>/src/main/javascript"], collectCoverage: false, collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"], coverageDirectory: "<rootDir>/target/js-coverage", testEnvironment: "jsdom", testEnvironmentOptions: { url: "http://localhost" }, moduleNameMapper: { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/test/javascript/__mocks__/fileMock.js", "\\.(css|less)$": "<rootDir>/src/test/javascript/__mocks__/styleMock.js", }, };
// For a detailed explanation regarding each configuration property, visit: // https://jestjs.io/docs/en/configuration.html module.exports = { roots: ["<rootDir>/src/main/javascript"], collectCoverage: false, collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"], coverageDirectory: "<rootDir>/target/js-coverage", testURL: "http://localhost", testEnvironment: "jsdom", moduleNameMapper: { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/test/javascript/__mocks__/fileMock.js", "\\.(css|less)$": "<rootDir>/src/test/javascript/__mocks__/styleMock.js", }, };
Add model for storing words.
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_db_tables(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True) class WebsitesContent(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites_content" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=False) words = Column('words', ARRAY(String), nullable=False)
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_website_table(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True)
Remove metadata from special properties list Metadata was originally put on the special properties list, since we had plans to ask users to pass metadata in from the API object constructors. Now that this plan is largely abandoned, there is no need to heed to it. This commit will remove it from this set. Signed-off-by: Alex Clemmer <2e6147cbff6661bd424c256de746b4f230002dff@gmail.com>
package ksonnet import ( "log" "os" "os/exec" "strings" "github.com/ksonnet/ksonnet-lib/ksonnet-gen/kubespec" ) const constructorName = "new" var specialProperties = map[kubespec.PropertyName]kubespec.PropertyName{ "apiVersion": "apiVersion", "kind": "kind", } func isSpecialProperty(pn kubespec.PropertyName) bool { _, ok := specialProperties[pn] return ok } func getSHARevision(dir string) string { cwd, err := os.Getwd() if err != nil { log.Fatalf("Could get working directory:\n%v", err) } err = os.Chdir(dir) if err != nil { log.Fatalf("Could cd to directory of repository at '%s':\n%v", dir, err) } sha, err := exec.Command("sh", "-c", "git rev-parse HEAD").Output() if err != nil { log.Fatalf("Could not find SHA of HEAD:\n%v", err) } err = os.Chdir(cwd) if err != nil { log.Fatalf("Could cd back to current directory '%s':\n%v", cwd, err) } return strings.TrimSpace(string(sha)) }
package ksonnet import ( "log" "os" "os/exec" "strings" "github.com/ksonnet/ksonnet-lib/ksonnet-gen/kubespec" ) const constructorName = "new" var specialProperties = map[kubespec.PropertyName]kubespec.PropertyName{ "apiVersion": "apiVersion", "metadata": "metadata", "kind": "kind", } func isSpecialProperty(pn kubespec.PropertyName) bool { _, ok := specialProperties[pn] return ok } func getSHARevision(dir string) string { cwd, err := os.Getwd() if err != nil { log.Fatalf("Could get working directory:\n%v", err) } err = os.Chdir(dir) if err != nil { log.Fatalf("Could cd to directory of repository at '%s':\n%v", dir, err) } sha, err := exec.Command("sh", "-c", "git rev-parse HEAD").Output() if err != nil { log.Fatalf("Could not find SHA of HEAD:\n%v", err) } err = os.Chdir(cwd) if err != nil { log.Fatalf("Could cd back to current directory '%s':\n%v", cwd, err) } return strings.TrimSpace(string(sha)) }
Add Theresa May Jive bot
package co.uk.jiveelection.campaign; import co.uk.jiveelection.campaign.twit.TwitHelper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import twitter4j.TwitterException; import java.io.IOException; /** * Main entry point for the Jive Campaign application. Sets up a continuously running loop that * checks the latest tweet from the named candidate, translates it to jive, then tweets it as a * jivebot. */ @SpringBootApplication public class App { public static void main(String[] args) throws TwitterException, IOException, InterruptedException { SpringApplication.run(App.class, args); TwitHelper jivebotDavidCameron = new TwitHelper("David_Cameron", TwitConfig.DAVID_JIVERON_ACCESS_TOKEN, TwitConfig.DAVID_JIVERON_ACCESS_TOKEN_SECRET); TwitHelper jivebotEdMiliband = new TwitHelper("Ed_Miliband", TwitConfig.ED_JIVEABAND_ACCESS_TOKEN, TwitConfig.ED_JIVEABAND_ACCESS_TOKEN_SECRET); TwitHelper jivebotNickClegg = new TwitHelper("nick_clegg", TwitConfig.NICK_JIVEGG_ACCESS_TOKEN, TwitConfig.NICK_JIVEGG_ACCESS_TOKEN_SECRET); TwitHelper jivebotTheresaMay = new TwitHelper("theresa_may", TwitConfig.JIVERESA_MAY_ACCESS_TOKEN, TwitConfig.JIVERESA_MAY_ACCESS_TOKEN_SECRET); } }
package co.uk.jiveelection.campaign; import java.io.IOException; import org.springframework.boot.autoconfigure.SpringBootApplication; import twitter4j.TwitterException; import co.uk.jiveelection.campaign.twit.TwitHelper; /** * Main entry point for the Jive Campaign application. Sets up a continuously running loop that * checks the latest tweet from the named candidate, translates it to jive, then tweets it as a * jivebot. */ @SpringBootApplication public class App { public static void main(String[] args) throws TwitterException, IOException, InterruptedException { TwitHelper jivebotDavidCameron = new TwitHelper("David_Cameron", "David_Jiveron", TwitConfig.DAVID_JIVERON_ACCESS_TOKEN, TwitConfig.DAVID_JIVERON_ACCESS_TOKEN_SECRET); TwitHelper jivebotEdMiliband = new TwitHelper("Ed_Miliband", "Ed_Jiveaband", TwitConfig.ED_JIVEABAND_ACCESS_TOKEN, TwitConfig.ED_JIVEABAND_ACCESS_TOKEN_SECRET); TwitHelper jivebotNickClegg = new TwitHelper("nick_clegg", "nick_jivegg", TwitConfig.NICK_JIVEGG_ACCESS_TOKEN, TwitConfig.NICK_JIVEGG_ACCESS_TOKEN_SECRET); } }
Change admin attribute to sysadmin
from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Route(entity.Entity, db.Model): # TODO(samueldmq): recheck string lengths for below attributes # TODO(samueldmq): add an 'active' attribute attributes = ['id', 'name', 'url', 'method', 'sysadmin', 'bypass'] name = db.Column(db.String(20), nullable=False) url = db.Column(db.String(80), nullable=False) method = db.Column(db.String(10), nullable=False) sysadmin = db.Column(db.Boolean(), nullable=False) bypass = db.Column(db.Boolean(), nullable=False) __table_args__ = (UniqueConstraint('url', 'method', name='route_uk'),) def __init__(self, id, name, url, method, sysadmin=False, bypass=False): self.id = id self.name = name self.url = url self.method = method self.method = method self.bypass = bypass self.sysadmin = sysadmin
from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Route(entity.Entity, db.Model): # TODO(samueldmq): recheck string lengths for below attributes # TODO(samueldmq): add an 'active' attribute attributes = ['id', 'name', 'url', 'method', 'admin', 'bypass'] name = db.Column(db.String(20), nullable=False) url = db.Column(db.String(80), nullable=False) method = db.Column(db.String(10), nullable=False) admin = db.Column(db.Boolean(), nullable=False) bypass = db.Column(db.Boolean(), nullable=False) __table_args__ = (UniqueConstraint('url', 'method', name='route_uk'),) def __init__(self, id, name, url, method, admin=False, bypass=False): self.id = id self.name = name self.url = url self.method = method self.method = method self.bypass = bypass self.admin = admin
Add name regex test and mail validation
describe('Users', function() { describe('Creation', function () { context('When creating a new user', function() { var some_guy = jsf(mocks.user); it('Should have an id', function() { some_guy.should.have.property('userId'); some_guy.userId.should.be.ok(); some_guy.userId.should.be.String(); }); it('Should have a name', function() { some_guy.should.have.property('name'); some_guy.name.should.be.ok(); some_guy.name.should.be.String(); }); it('Shold have a email', function(){ some_guy.should.have.property('emailAddr'); some_guy.emailAddr.should.be.ok(); some_guy.emailAddr.should.be.String(); }); it('The name would be Facu, Robert, or Cesar.', function() { some_guy.name.should.match(/^Facu$|^Robert$|^Cesar$/); }); it('The email address should be from the expected domain', function(){ some_guy.emailAddr.should.containEql("altoros.com"); }); }); }); });
describe('Users', function() { describe('Creation', function () { context('When creating a new user', function() { var some_guy = jsf(mocks.user); it('Should have an id', function() { some_guy.should.have.property('userId'); some_guy.userId.should.be.ok(); some_guy.userId.should.be.String(); }); it('Should have a name', function() { some_guy.should.have.property('name'); some_guy.name.should.be.ok(); some_guy.name.should.be.String(); }); it('Shold have a email', function(){ some_guy.should.have.property('emailAddr'); some_guy.emailAddr.should.be.ok(); some_guy.emailAddr.should.be.String(); }); }); }); });
Fix ntee -h/--help not showing right name and version and showing cli's ones instead
#!/usr/bin/env node var cli = require('cli').enable('version').setApp('./package.json'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
#!/usr/bin/env node var cli = require('cli').enable('version'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
Remove check for translation files There is no reason why crash whole app when extension is not configured
<?php namespace GettextTranslator\DI; use Nette\DI\CompilerExtension; use Nette\DI\ContainerBuilder; if (!class_exists('Nette\DI\CompilerExtension')) { class_alias('Nette\Config\CompilerExtension', 'Nette\DI\CompilerExtension'); } class Extension extends CompilerExtension { /** @var array */ private $defaults = array( 'lang' => 'en', 'files' => array(), 'layout' => 'horizontal', 'height' => 450 ); public function loadConfiguration() { $config = $this->getConfig($this->defaults); $builder = $this->getContainerBuilder(); $translator = $builder->addDefinition($this->prefix('translator')); $translator->setClass('GettextTranslator\Gettext', array('@session', '@cacheStorage', '@httpResponse')); $translator->addSetup('setLang', array($config['lang'])); $translator->addSetup('setProductionMode', array($builder->expand('%productionMode%'))); foreach ($config['files'] AS $id => $file) { $translator->addSetup('addFile', array($file, $id)); } $translator->addSetup('GettextTranslator\Panel::register', array('@application', '@self', '@session', '@httpRequest', $config['layout'], $config['height'])); } }
<?php namespace GettextTranslator\DI; use Nette; if (!class_exists('Nette\DI\CompilerExtension')) { class_alias('Nette\Config\CompilerExtension', 'Nette\DI\CompilerExtension'); } class Extension extends Nette\DI\CompilerExtension { /** @var array */ private $defaults = array( 'lang' => 'en', 'files' => array(), 'layout' => 'horizontal', 'height' => 450 ); public function loadConfiguration() { $config = $this->getConfig($this->defaults); $builder = $this->getContainerBuilder(); $translator = $builder->addDefinition($this->prefix('translator')); $translator->setClass('GettextTranslator\Gettext', array('@session', '@cacheStorage', '@httpResponse')); $translator->addSetup('setLang', array($config['lang'])); $translator->addSetup('setProductionMode', array($builder->expand('%productionMode%'))); // at least one language file must be defined if (count($config['files']) === 0) { throw new InvalidConfigException('Language file(s) must be defined.'); } foreach ($config['files'] AS $id => $file) { $translator->addSetup('addFile', array($file, $id)); } $translator->addSetup('GettextTranslator\Panel::register', array('@application', '@self', '@session', '@httpRequest', $config['layout'], $config['height'])); } } class InvalidConfigException extends Nette\InvalidStateException { }
Fix small bug in templatetags
from django import template from ..models import Post, Section register = template.Library() @register.assignment_tag def latest_blog_posts(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(blog__scoper=scoper) return qs[:5] @register.assignment_tag def latest_blog_post(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(blog__scoper=scoper) return qs[0] @register.assignment_tag def latest_section_post(section, scoper=None): qs = Post.objects.published().filter(section__name=section).order_by("-published") if scoper: qs = qs.filter(blog__scoper=scoper) return qs[0] if qs.count() > 0 else None @register.assignment_tag def blog_sections(): return Section.objects.filter(enabled=True)
from django import template from ..models import Post, Section register = template.Library() @register.assignment_tag def latest_blog_posts(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(scoper=scoper) return qs[:5] @register.assignment_tag def latest_blog_post(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(scoper=scoper) return qs[0] @register.assignment_tag def latest_section_post(section, scoper=None): qs = Post.objects.published().filter(section__name=section).order_by("-published") if scoper: qs = qs.filter(scoper=scoper) return qs[0] if qs.count() > 0 else None @register.assignment_tag def blog_sections(): return Section.objects.filter(enabled=True)
Remove debugging print statement from changeMarginWidth
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0, QsciScintilla.NumberMargin) self.setUtf8(True) self.setIndentationsUseTabs(False) self.setTabWidth(4) self.setIndentationGuides(False) self.setAutoIndent(True) def changeMarginWidth(self): numLines = self.lines() self.setMarginWidth(0, "00" * len(str(numLines))) def updateFont(self, newFont): self.lexer().setFont(newFont)
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0, QsciScintilla.NumberMargin) self.setUtf8(True) self.setIndentationsUseTabs(False) self.setTabWidth(4) self.setIndentationGuides(False) self.setAutoIndent(True) def changeMarginWidth(self): numLines = self.lines() print(len(str(numLines))) self.setMarginWidth(0, "00" * len(str(numLines))) def updateFont(self, newFont): self.lexer().setFont(newFont)
Make entity repo compatible with parent
<?php namespace Knp\RadBundle\Doctrine; use Doctrine\ORM\EntityRepository as BaseEntityRepository; use Doctrine\ORM\QueryBuilder; abstract class EntityRepository extends BaseEntityRepository { public function __call($method, $arguments) { if (0 === strpos($method, 'find')) { if (method_exists($this, $builder = 'build'.substr($method, 4))) { $qb = call_user_func_array(array($this, $builder), $arguments); return $qb->getQuery()->getResult(); } } return parent::__call($method, $arguments); } protected function build() { return $this->createQueryBuilder($this->getAlias()); } protected function buildOne($id) { return $this->build()->where($this->getAlias().'.id = '.intval($id)); } protected function buildAll() { return $this->build(); } protected function getAlias() { $reflection = new \ReflectionObject($this); return strtolower( preg_replace(array('/Repository$/', '/[a-z0-9]/'), '', $reflection->getShortName()) ); } }
<?php namespace Knp\RadBundle\Doctrine; use Doctrine\ORM\EntityRepository as BaseEntityRepository; use Doctrine\ORM\QueryBuilder; abstract class EntityRepository extends BaseEntityRepository { public function __call($method, array $arguments = array()) { if (0 === strpos($method, 'find')) { if (method_exists($this, $builder = 'build'.substr($method, 4))) { $qb = call_user_func_array(array($this, $builder), $arguments); return $qb->getQuery()->getResult(); } } return parent::__call($method, $arguments); } protected function build() { return $this->createQueryBuilder($this->getAlias()); } protected function buildOne($id) { return $this->build()->where($this->getAlias().'.id = '.intval($id)); } protected function buildAll() { return $this->build(); } protected function getAlias() { $reflection = new \ReflectionObject($this); return strtolower( preg_replace(array('/Repository$/', '/[a-z0-9]/'), '', $reflection->getShortName()) ); } }
Fix DebugToolbar requirement in non-debug envs
import functools import os from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from flask_app.app import app from flask_app.models import db manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) _FROM_HERE = functools.partial(os.path.join, os.path.dirname(__file__)) @manager.command def testserver(): from flask.ext.debugtoolbar import DebugToolbarExtension app.config["DEBUG"] = True app.config["TESTING"] = True app.config["SECRET_KEY"] = "dummy secret key" DebugToolbarExtension(app) app.run(port=8000, extra_files=[ _FROM_HERE("flask_app", "app.yml") ]) if __name__ == '__main__': manager.run()
import functools import os from flask.ext.debugtoolbar import DebugToolbarExtension from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from flask_app.app import app from flask_app.models import db manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) _FROM_HERE = functools.partial(os.path.join, os.path.dirname(__file__)) @manager.command def testserver(): app.config["DEBUG"] = True app.config["TESTING"] = True app.config["SECRET_KEY"] = "dummy secret key" toolbar = DebugToolbarExtension(app) app.run(port=8000, extra_files=[ _FROM_HERE("flask_app", "app.yml") ]) if __name__ == '__main__': manager.run()
Enable generic tests on Windows The build line excluding windows was inadvertent.
package liner import ( "bytes" "strings" "testing" ) func TestHistory(t *testing.T) { input := `foo bar baz quux dingle` var s State num, err := s.ReadHistory(strings.NewReader(input)) if err != nil { t.Fatal("Unexpected error reading history", err) } if num != 5 { t.Fatal("Wrong number of history entries read") } var out bytes.Buffer num, err = s.WriteHistory(&out) if err != nil { t.Fatal("Unexpected error writing history", err) } if num != 5 { t.Fatal("Wrong number of history entries written") } if strings.TrimSpace(out.String()) != input { t.Fatal("Round-trip failure") } // Test reading with a trailing newline present var s2 State num, err = s2.ReadHistory(&out) if err != nil { t.Fatal("Unexpected error reading history the 2nd time", err) } if num != 5 { t.Fatal("Wrong number of history entries read the 2nd time") } }
// +build !windows package liner import ( "bytes" "strings" "testing" ) func TestHistory(t *testing.T) { input := `foo bar baz quux dingle` var s State num, err := s.ReadHistory(strings.NewReader(input)) if err != nil { t.Fatal("Unexpected error reading history", err) } if num != 5 { t.Fatal("Wrong number of history entries read") } var out bytes.Buffer num, err = s.WriteHistory(&out) if err != nil { t.Fatal("Unexpected error writing history", err) } if num != 5 { t.Fatal("Wrong number of history entries written") } if strings.TrimSpace(out.String()) != input { t.Fatal("Round-trip failure") } // Test reading with a trailing newline present var s2 State num, err = s2.ReadHistory(&out) if err != nil { t.Fatal("Unexpected error reading history the 2nd time", err) } if num != 5 { t.Fatal("Wrong number of history entries read the 2nd time") } }
Add test to ensure all the views have assigned an eventManager This test ensure that current eventManager bubbling logic performs correctly
var set = Em.set; var get = Em.get; module("Em.View extensions", { setup: function() { Em.Gestures.register('viewTestGesture',Em.Object.extend()); }, teardown: function() { Em.Gestures.unregister('viewTestGesture'); } }); test("should detect gesture", function() { var view = Em.View.create({ viewTestGestureStart: function() { }, viewTestGestureChange: function() { }, viewTestGestureEnd: function() { }, viewTestGestureCancel: function() { } }); var eventManager = get(view, 'eventManager'); ok(eventManager,'view has an eventManager'); var gestures = get(eventManager, 'gestures'); equal(gestures.length,1,'gesture exists'); }); test("should apply options", function() { var view = Em.View.create({ viewTestGestureOptions: { numberOfRequiredTouches: 4 }, viewTestGestureStart: function() { } }); var eventManager = get(view, 'eventManager'); ok(eventManager,'view has an eventManager'); var gestures = get(eventManager, 'gestures'); equal(gestures.length,1,'gesture exists'); equal(gestures[0].numberOfRequiredTouches,4, "should apply options hash"); }); test("A view without gestures have assigned a GestureManager at its eventManager property", function() { var view = Em.View.create({ }); var eventManager = get(view, 'eventManager'); ok(eventManager,'view has an eventManager'); var gestures = get(eventManager, 'gestures'); equal(gestures.length,0,' has not gestures'); });
var set = Em.set; var get = Em.get; module("Em.View extensions", { setup: function() { Em.Gestures.register('viewTestGesture',Em.Object.extend()); }, teardown: function() { Em.Gestures.unregister('viewTestGesture'); } }); test("should detect gesture", function() { var view = Em.View.create({ viewTestGestureStart: function() { }, viewTestGestureChange: function() { }, viewTestGestureEnd: function() { }, viewTestGestureCancel: function() { } }); var eventManager = get(view, 'eventManager'); ok(eventManager,'view has an eventManager'); var gestures = get(eventManager, 'gestures'); equal(gestures.length,1,'gesture exists'); }); test("should apply options", function() { var view = Em.View.create({ viewTestGestureOptions: { numberOfRequiredTouches: 4 }, viewTestGestureStart: function() { } }); var eventManager = get(view, 'eventManager'); ok(eventManager,'view has an eventManager'); var gestures = get(eventManager, 'gestures'); equal(gestures.length,1,'gesture exists'); equal(gestures[0].numberOfRequiredTouches,4, "should apply options hash"); });
Use deprecated method to ensure we don't break with older versions of jackson
package com.bugsnag.serialization; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.OutputStream; public class Serializer { private ObjectMapper mapper = new ObjectMapper(); /** * Constructor. */ @SuppressWarnings("deprecation") // Use deprecated method to ensure we don't break with older versions of jackson public Serializer() { mapper .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .setVisibilityChecker( mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); } /** * Write the object to the stream. * * @param stream the stream to write the object to. * @param object the object to write to the stream. * @throws SerializationException the object could not be serialized. */ public void writeToStream(OutputStream stream, Object object) throws SerializationException { try { mapper.writeValue(stream, object); } catch (IOException ex) { throw new SerializationException("Exception during serialization", ex); } } }
package com.bugsnag.serialization; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.OutputStream; public class Serializer { private ObjectMapper mapper = new ObjectMapper(); /** * Constructor. */ public Serializer() { mapper .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .setVisibility( mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); } /** * Write the object to the stream. * * @param stream the stream to write the object to. * @param object the object to write to the stream. * @throws SerializationException the object could not be serialized. */ public void writeToStream(OutputStream stream, Object object) throws SerializationException { try { mapper.writeValue(stream, object); } catch (IOException ex) { throw new SerializationException("Exception during serialization", ex); } } }
[AC-6976] Remove physical_address from factory, not sure why this helps
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from factory import ( DjangoModelFactory, Sequence, ) from accelerator.apps import AcceleratorConfig ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily') class ProgramFamilyFactory(DjangoModelFactory): class Meta: model = ProgramFamily name = Sequence(lambda n: "Program Family {0}".format(n)) short_description = 'A program family for testing' url_slug = Sequence(lambda n: "pf{0}".format(n)) email_domain = Sequence(lambda n: "pf{0}.accelerator.org".format(n)) phone_number = "617-555-1212" # physical_address = "Boston" is_open_for_startups = True is_open_for_experts = True use_site_tree_side_nav = False
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from factory import ( DjangoModelFactory, Sequence, ) from accelerator.apps import AcceleratorConfig ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily') class ProgramFamilyFactory(DjangoModelFactory): class Meta: model = ProgramFamily name = Sequence(lambda n: "Program Family {0}".format(n)) short_description = 'A program family for testing' url_slug = Sequence(lambda n: "pf{0}".format(n)) email_domain = Sequence(lambda n: "pf{0}.accelerator.org".format(n)) phone_number = "617-555-1212" physical_address = "Boston" is_open_for_startups = True is_open_for_experts = True use_site_tree_side_nav = False
Move sidebar to the left
<?php /* @var $this Controller */ ?> <?php $this->beginContent('//layouts/main'); ?> <div class="row"> <div class="span3"> <div id="sidebar"> <?php $this->beginWidget('zii.widgets.CPortlet', array( 'title'=>'Operations', )); $this->widget('bootstrap.widgets.TbMenu', array( 'items'=>$this->menu, 'htmlOptions'=>array('class'=>'operations'), )); $this->endWidget(); ?> </div><!-- sidebar --> </div> <div class="span9"> <div id="content"> <?php echo $content; ?> </div><!-- content --> </div> </div> <?php $this->endContent(); ?>
<?php /* @var $this Controller */ ?> <?php $this->beginContent('//layouts/main'); ?> <div class="row"> <div class="span9"> <div id="content"> <?php echo $content; ?> </div><!-- content --> </div> <div class="span3"> <div id="sidebar"> <?php $this->beginWidget('zii.widgets.CPortlet', array( 'title'=>'Operations', )); $this->widget('bootstrap.widgets.TbMenu', array( 'items'=>$this->menu, 'htmlOptions'=>array('class'=>'operations'), )); $this->endWidget(); ?> </div><!-- sidebar --> </div> </div> <?php $this->endContent(); ?>
Make sure bot jobs can be deserialized
"""Heroku web worker.""" import os import redis listen = ['high', 'default', 'low'] redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': # pragma: nocover # These imports are inside the __main__ block # to make sure that we only import from rq_gevent_worker # (which has the side effect of applying gevent monkey patches) # in the worker process. This way other processes can import the # redis connection without that side effect. from rq import ( Queue, Connection ) try: from rq_gevent_worker import GeventWorker as Worker except ImportError: from rq import Worker from dallinger.config import initialize_experiment_package initialize_experiment_package(os.getcwd()) import logging logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work()
"""Heroku web worker.""" import os import redis listen = ['high', 'default', 'low'] redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': # pragma: nocover # These imports are inside the __main__ block # to make sure that we only import from rq_gevent_worker # (which has the side effect of applying gevent monkey patches) # in the worker process. This way other processes can import the # redis connection without that side effect. from rq import ( Queue, Connection ) try: from rq_gevent_worker import GeventWorker as Worker except ImportError: from rq import Worker import logging logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work()
Fix typo in variable name.
import "../core/global"; import "../net/parseURLQueryTerms" var sn_env = { debug : false, host : 'data.solarnetwork.net', tls : (function() { return (global !== undefined && global.location !== undefined && global.location.protocol !== undefined && global.location.protocol.toLowerCase().indexOf('https') === 0 ? true : false); }()), path : '/solarquery', solarUserPath : '/solaruser', secureQuery : false }; function sn_env_setDefaultEnv(defaults) { var prop; for ( prop in defaults ) { if ( defaults.hasOwnProperty(prop) ) { if ( sn_env[prop] === undefined ) { sn_env[prop] = defaults[prop]; } } } } function sn_env_setEnv(environment) { var prop; for ( prop in environment ) { if ( environment.hasOwnProperty(prop) ) { sn_env[prop] = environment[prop]; } } } sn.env = sn_env; sn.setEnv = sn_env_setEnv; sn.setDefaultEnv = sn_env_setDefaultEnv; if ( global !== undefined && global.location !== undefined && global.location.search !== undefined ) { sn_env_setEnv(sn_net_parseURLQueryTerms(global.location.search)); }
import "../core/global"; import "../net/parseURLQueryTerms" var sn_env = { debug : false, host : 'data.solarnetwork.net', tls : (function() { return (global !== undefined && global.locaion !== undefined && global.location.protocol !== undefined && global.location.protocol.toLowerCase().indexOf('https') === 0 ? true : false); }()), path : '/solarquery', solarUserPath : '/solaruser', secureQuery : false }; function sn_env_setDefaultEnv(defaults) { var prop; for ( prop in defaults ) { if ( defaults.hasOwnProperty(prop) ) { if ( sn_env[prop] === undefined ) { sn_env[prop] = defaults[prop]; } } } } function sn_env_setEnv(environment) { var prop; for ( prop in environment ) { if ( environment.hasOwnProperty(prop) ) { sn_env[prop] = environment[prop]; } } } sn.env = sn_env; sn.setEnv = sn_env_setEnv; sn.setDefaultEnv = sn_env_setDefaultEnv; if ( global !== undefined && global.location !== undefined && global.location.search !== undefined ) { sn_env_setEnv(sn_net_parseURLQueryTerms(global.location.search)); }
Add trove classifiers for supported Python versions
from distutils.core import setup import re versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M) with open("axiom/_version.py", "rt") as f: version = versionPattern.search(f.read()).group(1) setup( name="Axiom", version=version, description="An in-process object-relational database", url="http://divmod.org/trac/wiki/DivmodAxiom", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", install_requires=["twisted", "epsilon"], packages=[ 'axiom', 'axiom.scripts', 'axiom.test', 'axiom.test.upgrade_fixtures', 'axiom.test.historic', 'axiom.plugins', 'twisted.plugins' ], scripts=['bin/axiomatic'], license="MIT", platforms=["any"], classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Twisted", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2 :: Only", "Topic :: Database"])
from distutils.core import setup import re versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M) with open("axiom/_version.py", "rt") as f: version = versionPattern.search(f.read()).group(1) setup( name="Axiom", version=version, description="An in-process object-relational database", url="http://divmod.org/trac/wiki/DivmodAxiom", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", install_requires=["twisted", "epsilon"], packages=[ 'axiom', 'axiom.scripts', 'axiom.test', 'axiom.test.upgrade_fixtures', 'axiom.test.historic', 'axiom.plugins', 'twisted.plugins' ], scripts=['bin/axiomatic'], license="MIT", platforms=["any"], classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Twisted", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Database"])
Update to pass live server url as param to protractor
# -*- coding: utf-8 -*- import os import subprocess class ProtractorTestCaseMixin(object): protractor_conf = 'protractor.conf.js' suite = None specs = None @classmethod def setUpClass(cls): super(ProtractorTestCaseMixin, cls).setUpClass() with open(os.devnull, 'wb') as f: subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f) cls.webdriver = subprocess.Popen( ['webdriver-manager', 'start'], stdout=f, stderr=f) @classmethod def tearDownClass(cls): cls.webdriver.kill() super(ProtractorTestCaseMixin, cls).tearDownClass() def test_run(self): protractor_command = 'protractor {}'.format(self.protractor_conf) if self.specs: protractor_command += ' --specs {}'.format(','.join(self.specs)) if self.suite: protractor_command += ' --suite {}'.format(self.suite) protractor_command += ' --params.live_server_url={}'.format(self.live_server_url) return_code = subprocess.call(protractor_command.split()) self.assertEqual(return_code, 0)
# -*- coding: utf-8 -*- import os import subprocess class ProtractorTestCaseMixin(object): protractor_conf = 'protractor.conf.js' suite = None specs = None @classmethod def setUpClass(cls): super(ProtractorTestCaseMixin, cls).setUpClass() with open(os.devnull, 'wb') as f: subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f) cls.webdriver = subprocess.Popen( ['webdriver-manager', 'start'], stdout=f, stderr=f) @classmethod def tearDownClass(cls): cls.webdriver.kill() super(ProtractorTestCaseMixin, cls).tearDownClass() def test_run(self): protractor_command = 'protractor {}'.format(self.protractor_conf) if self.specs: protractor_command += ' --specs {}'.format(','.join(self.specs)) if self.suite: protractor_command += ' --suite {}'.format(self.suite) return_code = subprocess.call(protractor_command.split()) self.assertEqual(return_code, 0)
Change url for media list api
from django.conf.urls import url, include from nimbus.apps import debug_urls from . import views urlpatterns = debug_urls() urlpatterns += [ url(r"^$", views.api_root, name="api_root"), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth$', 'rest_framework.authtoken.views.obtain_auth_token'), url(r"^media/list$", views.MediaList.as_view(), name="media_list"), url(r"^media/filter_media_type/(?P<media_type>[A-Z]+)", views.TypeFilteredMediaList.as_view(), name="filter_media_api"), url(r"^media/show$", views.MediaDetail.as_view(), name="media_detail"), url(r"^media/add_file$", views.AddFile.as_view(), name="add_file"), url(r"^media/add_link$", views.AddLink.as_view(), name="add_link"), url(r"^media/delete$", views.delete_media, name="delete_media"), ]
from django.conf.urls import url, include from nimbus.apps import debug_urls from . import views urlpatterns = debug_urls() urlpatterns += [ url(r"^$", views.api_root, name="api_root"), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth$', 'rest_framework.authtoken.views.obtain_auth_token'), url(r"^media$", views.MediaList.as_view(), name="media_list"), url(r"^media/filter_media_type/(?P<media_type>[A-Z]+)", views.TypeFilteredMediaList.as_view(), name="filter_media_api"), url(r"^media/show$", views.MediaDetail.as_view(), name="media_detail"), url(r"^media/add_file$", views.AddFile.as_view(), name="add_file"), url(r"^media/add_link$", views.AddLink.as_view(), name="add_link"), url(r"^media/delete$", views.delete_media, name="delete_media"), ]
Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
Update the sequence alignment example.
from alignment.sequence import Sequence from alignment.vocabulary import Vocabulary from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner # Create sequences to be aligned. a = Sequence("what a beautiful day".split()) b = Sequence("what a disappointingly bad day".split()) print "Sequence A:", a print "Sequence B:", b print # Create a vocabulary and encode the sequences. v = Vocabulary() aEncoded = v.encodeSequence(a) bEncoded = v.encodeSequence(b) print "Encoded A:", aEncoded print "Encoded B:", bEncoded print # Create a scoring and align the sequences using global aligner. scoring = SimpleScoring(2, -1) aligner = GlobalSequenceAligner(scoring, -2) score, encodeds = aligner.align(aEncoded, bEncoded, backtrace=True) # Iterate over optimal alignments and print them. for encoded in encodeds: alignment = v.decodeSequenceAlignment(encoded) print alignment print "Alignment score:", alignment.score print "Percent identity:", alignment.percentIdentity() print
# Create sequences to be aligned. from alignment.sequence import Sequence a = Sequence("what a beautiful day".split()) b = Sequence("what a disappointingly bad day".split()) print "Sequence A:", a print "Sequence B:", b print # Create a vocabulary and encode the sequences. from alignment.vocabulary import Vocabulary v = Vocabulary() aEncoded = v.encodeSequence(a) bEncoded = v.encodeSequence(b) print "Encoded A:", aEncoded print "Encoded B:", bEncoded print # Create a scoring and align the sequences using global aligner. from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner scoring = SimpleScoring(2, -1) aligner = GlobalSequenceAligner(scoring, -2) score, encodeds = aligner.align(aEncoded, bEncoded, backtrace=True) # Iterate over optimal alignments and print them. for encoded in encodeds: alignment = v.decodeSequenceAlignment(encoded) print alignment print "Alignment score:", alignment.score print "Percent identity:", alignment.percentIdentity() print
Update test to mock stripes-loader alias
import mockReq from 'mock-require'; import chai from 'chai'; import { shallow } from 'enzyme'; import Match from 'react-router/Match'; chai.should(); global.OKAPI_URL = 'http://localhost:9130'; mockReq('stripes-loader', { modules: { app: [ { displayName: 'someApp', module: 'some-app', getModule: () => () => 'Close enough to a React component for this purpose.', route: '/someapp' } ] } }); mockReq('some-app', () => <div></div>); const routes = require('../src/moduleRoutes').default; const inst = shallow(routes[0]).instance(); describe('routes', () => { it('should be an array of Match components', () => { routes.should.be.a('array'); inst.should.be.instanceOf(Match); }); });
import mockReq from 'mock-require'; import chai from 'chai'; import { shallow } from 'enzyme'; import Match from 'react-router/Match'; chai.should(); global.OKAPI_URL = 'http://localhost:9130'; mockReq('stripes-loader!', { modules: { app: [ { displayName: 'someApp', module: 'some-app', getModule: () => () => 'Close enough to a React component for this purpose.', route: '/someapp' } ] } }); mockReq('some-app', () => <div></div>); const routes = require('../src/moduleRoutes').default; const inst = shallow(routes[0]).instance(); describe('routes', () => { it('should be an array of Match components', () => { routes.should.be.a('array'); inst.should.be.instanceOf(Match); }); });
Clean up JS a bit
(function() { 'use strict'; var $sidebarButtonA = $('.sidebar-header-bills'); var $sidebarButtonB = $('.sidebar-header-resources'); var $sidebarContentA = $('.sidebar-content-bills'); var $sidebarContentB = $('.sidebar-content-resources'); function toggleBillSearch() { $sidebarContentA.toggleClass('collapse'); } function toggleResources() { $sidebarContentB.toggleClass('collapse'); } $sidebarButtonA.click(function() { toggleBillSearch(); }); $sidebarButtonB.click(function() { toggleResources(); }); var $storyStream = $('.story-stream'); $storyStream.slick({ dots: true, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1 }); })();
$(function () { 'use strict'; var sidebarButtonA = $('.sidebar-header-bills'); var sidebarButtonB = $('.sidebar-header-resources'); var sidebarContentA = $('.sidebar-content-bills'); var sidebarContentB = $('.sidebar-content-resources'); function toggleBillSearch() { sidebarContentA.toggleClass('collapse'); } function toggleResources() { sidebarContentB.toggleClass('collapse'); } $(sidebarButtonA).click(function() { toggleBillSearch(); }); $(sidebarButtonB).click(function() { toggleResources(); }); })(); $(document).ready(function() { $('.story-stream').slick({ dots: true, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1 }); });
Fix jsdoc to pass lint
/** @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /* eslint-disable no-unused-vars */ /** * When using Closure Compiler, JSCompiler_renameProperty(property, object) is replaced by the munged name for object[property] * We cannot alias this function, so we have to use a small shim that has the same behavior when not compiling. * * @param {string} prop Property name * @param {?Object} obj Reference object * @return {string} Dereferenced value */ window.JSCompiler_renameProperty = function(prop, obj) { return prop; }; /* eslint-enable */ export {};
/** @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /* eslint-disable no-unused-vars */ /** * When using Closure Compiler, JSCompiler_renameProperty(property, object) is replaced by the munged name for object[property] * We cannot alias this function, so we have to use a small shim that has the same behavior when not compiling. * * @param {string} prop * @param {?Object} obj * @return {string} */ window.JSCompiler_renameProperty = function(prop, obj) { return prop; }; /* eslint-enable */ export {};
Use mock instead of own class
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
import os import pytest from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir): class Response: pass response = Response() with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
Add namespace for products client
<?php namespace WoowUp; use WoowUp\Endpoints\Purchases; use WoowUp\Endpoints\Users; use WoowUp\Endpoints\Products; class Client { const HOST = 'https://api.woowup.com'; const VERSION = 'apiv3'; protected $http; public $purchases; public $mailings; public $users; public $segments; public $products; public function __construct($apikey) { $this->purchases = new Purchases(self::HOST . '/' . self::VERSION, $apikey); $this->users = new Users(self::HOST . '/' . self::VERSION, $apikey); $this->products = new Products(self::HOST . '/' . self::VERSION, $apikey); } }
<?php namespace WoowUp; use WoowUp\Endpoints\Purchases; use WoowUp\Endpoints\Users; class Client { const HOST = 'https://api.woowup.com'; const VERSION = 'apiv3'; protected $http; public $purchases; public $mailings; public $users; public $segments; public $products; public function __construct($apikey) { $this->purchases = new Purchases(self::HOST . '/' . self::VERSION, $apikey); $this->users = new Users(self::HOST . '/' . self::VERSION, $apikey); $this->products = new Products(self::HOST . '/' . self::VERSION, $apikey); } }
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
Fix GORM v1 compile error
package utils import ( "fmt" "os" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) // TestDB initialize a db for testing func TestDB() *gorm.DB { dbuser, dbpwd, dbname := "qor", "qor", "qor_test" if os.Getenv("TEST_ENV") == "CI" { dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD") } var db *gorm.DB var err error if os.Getenv("TEST_DB") == "postgres" { db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname)) } else { // CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor'; // CREATE DATABASE qor_test; // GRANT ALL ON qor_test.* TO 'qor'@'localhost'; db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname)) } if err != nil { panic(err) } return db }
package utils import ( "fmt" "os" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) // TestDB initialize a db for testing func TestDB() *gorm.DB { dbuser, dbpwd, dbname := "qor", "qor", "qor_test" if os.Getenv("TEST_ENV") == "CI" { dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD") } var db gorm.DB var err error if os.Getenv("TEST_DB") == "postgres" { db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname)) } else { // CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor'; // CREATE DATABASE qor_test; // GRANT ALL ON qor_test.* TO 'qor'@'localhost'; db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname)) } if err != nil { panic(err) } return &db }
Modify board_slug in url regex to pass numeric letter
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
Switch Workbox strategy from StaleWhileRevalidate to NetworkFirst
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); workbox.precaching.precache([ '/offline/', '/static/images/avatar.jpg?cloudinary=w_200,f_auto', '/static/images/avatar.jpg?cloudinary=w_40,f_auto' ]); const persistentPages = ['/', '/blog/', '/events/', '/projects/']; const persistentPagesStrategy = new workbox.strategies.NetworkFirst({ cacheName: 'persistent-pages', plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }); persistentPages.forEach(path => { workbox.routing.registerRoute(path, persistentPagesStrategy); }); // https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route workbox.routing.setCatchHandler(context => { if (context.event.request.destination === 'document') { return caches.match('/offline/'); } return Response.error(); }); workbox.routing.setDefaultHandler( new workbox.strategies.NetworkOnly() );
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); workbox.precaching.precache([ '/offline/', '/static/images/avatar.jpg?cloudinary=w_200,f_auto', '/static/images/avatar.jpg?cloudinary=w_40,f_auto' ]); const persistentPages = ['/', '/blog/', '/events/', '/projects/']; const persistentPagesStrategy = new workbox.strategies.StaleWhileRevalidate({ cacheName: 'persistent-pages', plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }); persistentPages.forEach(path => { workbox.routing.registerRoute(path, persistentPagesStrategy); }); // https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route workbox.routing.setCatchHandler(context => { if (context.event.request.destination === 'document') { return caches.match('/offline/'); } return Response.error(); }); workbox.routing.setDefaultHandler( new workbox.strategies.NetworkOnly() );
Raise word limit by 50%
import os import json from random import randrange, seed, sample MAX_LEN = 75 def shift(s, new): space = s.find(' ') if space == -1: raise Exception('bad shift string ' + s) return s[space+1:] + ' ' + new def main(): getw = lambda arr: sample(arr, 1)[0] words = {} starters = 0 wordlen = 1 seed() with open('../data/mapping.json') as f: words = json.load(f) sparse = words.get('sparse').get('data') dense = words.get('dense').get('data') word = getw(sparse) associated = sparse[word] secret = word + ' ' + getw(associated) word = secret while wordlen < MAX_LEN: associated = dense.get(word, []) if len(associated) == 0: break tmp = getw(associated) secret += ' ' + tmp word = shift(word, tmp) wordlen += 1 print secret if __name__ == '__main__': main()
import os import json from random import randrange, seed, sample MAX_LEN = 50 def shift(s, new): space = s.find(' ') if space == -1: raise Exception('bad shift string ' + s) return s[space+1:] + ' ' + new def main(): getw = lambda arr: sample(arr, 1)[0] words = {} starters = 0 wordlen = 1 seed() with open('../data/mapping.json') as f: words = json.load(f) sparse = words.get('sparse').get('data') dense = words.get('dense').get('data') word = getw(sparse) associated = sparse[word] secret = word + ' ' + getw(associated) word = secret while wordlen < MAX_LEN: associated = dense.get(word, []) if len(associated) == 0: break tmp = getw(associated) secret += ' ' + tmp word = shift(word, tmp) wordlen += 1 print secret if __name__ == '__main__': main()
Improve html markup of added item
// activity item template var itemtemplate = ['<li class="activity-item">', '<a href="{{modifier_url}}">', '<img src="{{modifier_siteicon}}" />', '</a>', '<div>', '<p>', '<a href="{{modifier_url}}">{{modifier}}</a> is {{action}} ', '<a class="tiddler-title" href="{{tiddler_url}}">{{tiddler_title}}</a>', '</p>', '</div>', '</li>'].join(""); var ws = new WebSocket('ws://10.10.1.142:8080/'); var el = $("#realtime")[0] || document.body; var container = $("<ul />").appendTo(el); ws.onmessage = function(e) { var url = e.data; $.ajax({ url: url, dataType: "json", success: function(tiddler) { var html = Mustache.to_html(itemtemplate, tiddler); container.prepend(html); } }) };
// activity item template var itemtemplate = ['<div class="activity-item">', '<a href="{{modifier_url}}">', '<img src="{{modifier_siteicon}}" />', '</a>', '<div>', '<p>', '<a href="{{modifier_url}}">{{modifier}}</a> is {{action}} ', '<a class="tiddler-title" href="{{tiddler_url}}">{{tiddler_title}}</a>', '</p>', '</div>', '</div>'].join(""); var ws = new WebSocket('ws://localhost:8080/'); var el = $("#realtime")[0] || document.body; var container = $("<ul />").appendTo(el); ws.onmessage = function(e) { var url = e.data; $.ajax({ url: url, dataType: "json", success: function(tiddler) { var html = Mustache.to_html(itemtemplate, tiddler); $("<li />").html(html).prependTo(container); } }) };
Make ubiquity work with at other paths than the base path
exports.addClassName = function(element, className) { if (!(' ' + element.className + ' ').match(' ' + className + ' ')) { element.className += className + ' '; } } exports.removeClassName = function(element, className) { className += ' '; var current = element.className; var index = current.indexOf(className); element.className = current.slice(0, index) + current.slice(index + className.length); } var base = 'css/'; var loadedStyles = {}; exports.loadStyles = function(path) { path = path.split('.').join('/'); if (loadedStyles[path]) { return; } loadedStyles[path] = true; var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = base + path + '.css'; document.getElementsByTagName('head')[0].appendChild(link); }
exports.addClassName = function(element, className) { if (!(' ' + element.className + ' ').match(' ' + className + ' ')) { element.className += className + ' '; } } exports.removeClassName = function(element, className) { className += ' '; var current = element.className; var index = current.indexOf(className); element.className = current.slice(0, index) + current.slice(index + className.length); } var base = '/css/'; var loadedStyles = {}; exports.loadStyles = function(path) { path = path.split('.').join('/'); if (loadedStyles[path]) { return; } loadedStyles[path] = true; var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = base + path + '.css'; document.getElementsByTagName('head')[0].appendChild(link); }
Fix problem rendering oneof() predicate when the members aren't strings
class OneOf: def __init__(self, members): self.members = members def __call__(self, candidate): if candidate in self.members: return True return "%s not in %s" % (candidate, self.members) def __repr__(self): return "one of %s" % ', '.join(map(repr, self.members)) def oneof(*members): return OneOf(members) class InRange: def __init__(self, start, end): self.start = start self.end = end def __call__(self, candidate): if self.start <= candidate <= self.end: return True return "%s not between %s and %s" % (candidate, self.start, self.end) def __repr__(self): return "between %s and %s" % (self.start, self.end) def inrange(start, end): return InRange(start, end)
class OneOf: def __init__(self, members): self.members = members def __call__(self, candidate): if candidate in self.members: return True return "%s not in %s" % (candidate, self.members) def __repr__(self): return "one of %s" % ', '.join(self.members) def oneof(*members): return OneOf(members) class InRange: def __init__(self, start, end): self.start = start self.end = end def __call__(self, candidate): if self.start <= candidate <= self.end: return True return "%s not between %s and %s" % (candidate, self.start, self.end) def __repr__(self): return "between %s and %s" % (self.start, self.end) def inrange(start, end): return InRange(start, end)
Fix app files test on windows
package cf_test import ( . "cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "path/filepath" "path" ) var _ = Describe("AppFiles", func() { fixturePath := filepath.Join("..", "fixtures", "applications") Describe("AppFilesInDir", func() { It("all files have '/' path separators", func() { files, err := AppFilesInDir(fixturePath) Expect(err).ShouldNot(HaveOccurred()) for _, afile := range files { Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path))) } }) It("excludes files based on the .cfignore file", func() { appPath := filepath.Join(fixturePath, "app-with-cfignore") files, err := AppFilesInDir(appPath) Expect(err).ShouldNot(HaveOccurred()) paths := []string{} for _, file := range files { paths = append(paths, file.Path) } Expect(paths).To(Equal([]string{ path.Join("dir1", "child-dir", "file3.txt"), path.Join("dir1", "file1.txt"), })) }) }) })
package cf_test import ( . "cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "path/filepath" ) var _ = Describe("AppFiles", func() { fixturePath := filepath.Join("..", "fixtures", "applications") Describe("AppFilesInDir", func() { It("all files have '/' path separators", func() { files, err := AppFilesInDir(fixturePath) Expect(err).ShouldNot(HaveOccurred()) for _, afile := range files { Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path))) } }) It("excludes files based on the .cfignore file", func() { appPath := filepath.Join(fixturePath, "app-with-cfignore") files, err := AppFilesInDir(appPath) Expect(err).ShouldNot(HaveOccurred()) paths := []string{} for _, file := range files { paths = append(paths, file.Path) } Expect(paths).To(Equal([]string{ filepath.Join("dir1", "child-dir", "file3.txt"), filepath.Join("dir1", "file1.txt"), })) }) }) })
Add hexdec filter for Twig
<?php namespace Scat; class TwigExtension extends \Twig\Extension\AbstractExtension implements \Twig\Extension\GlobalsInterface { public function getGlobals() { return [ 'DEBUG' => $GLOBALS['DEBUG'], 'PUBLIC' => ORDURE, 'PUBLIC_CATALOG' => ORDURE . '/art-supplies', 'STATIC' => ORDURE_STATIC ]; } public function getFunctions() { return [ new \Twig\TwigFunction('notes', [ $this, 'getNotes' ]), ]; } public function getFilters() { return [ new \Twig_SimpleFilter('hexdec', 'hexdec') ]; } public function getNotes() { return \Model::factory('Note') ->where('parent_id', 0) ->where('todo', 1) ->order_by_asc('id') ->find_many(); } }
<?php namespace Scat; class TwigExtension extends \Twig\Extension\AbstractExtension implements \Twig\Extension\GlobalsInterface { public function getGlobals() { return [ 'DEBUG' => $GLOBALS['DEBUG'], 'PUBLIC' => ORDURE, 'PUBLIC_CATALOG' => ORDURE . '/art-supplies', 'STATIC' => ORDURE_STATIC ]; } public function getFunctions() { return [ new \Twig\TwigFunction('notes', [ $this, 'getNotes' ]), ]; } public function getNotes() { return \Model::factory('Note') ->where('parent_id', 0) ->where('todo', 1) ->order_by_asc('id') ->find_many(); } }
Allow running gulp install as root
var alloy = require('../.alloy'); var gulp = require('gulp'); var path = require('path'); var replace = require('gulp-replace'); var run = require('run-sequence'); var spawn = require('spawn-local-bin'); var ROOT = path.join(__dirname, '..'); gulp.task('init', function(callback) { run('init-bower', 'init-npm', 'init-yui', callback); }); gulp.task('init-bower', function(callback) { var args = ['install', '--allow-root']; var cmd = 'bower'; var cwd = ROOT; spawn(cmd, args, cwd) .on('exit', function() { callback(); }); }); gulp.task('init-npm', function(callback) { var args = ['install']; var cmd = 'npm'; var cwd = ROOT; spawn(cmd, args, cwd) .on('exit', function() { callback(); }); }); gulp.task('init-yui', function() { return gulp.src('bower_components/yui3/build/**', { cwd: ROOT }) .pipe(replace('@VERSION@', alloy.yuiversion, {skipBinary: true})) .pipe(gulp.dest('build', { cwd: ROOT })); });
var alloy = require('../.alloy'); var gulp = require('gulp'); var path = require('path'); var replace = require('gulp-replace'); var run = require('run-sequence'); var spawn = require('spawn-local-bin'); var ROOT = path.join(__dirname, '..'); gulp.task('init', function(callback) { run('init-bower', 'init-npm', 'init-yui', callback); }); gulp.task('init-bower', function(callback) { var args = ['install']; var cmd = 'bower'; var cwd = ROOT; spawn(cmd, args, cwd) .on('exit', function() { callback(); }); }); gulp.task('init-npm', function(callback) { var args = ['install']; var cmd = 'npm'; var cwd = ROOT; spawn(cmd, args, cwd) .on('exit', function() { callback(); }); }); gulp.task('init-yui', function() { return gulp.src('bower_components/yui3/build/**', { cwd: ROOT }) .pipe(replace('@VERSION@', alloy.yuiversion, {skipBinary: true})) .pipe(gulp.dest('build', { cwd: ROOT })); });
server: Add Authorization to Access-Control-Allow-Headers list.
package org.opencb.opencga.server; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by pfurio on 04/10/16. */ public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("Request " + request.getMethod()); HttpServletResponse resp = (HttpServletResponse) servletResponse; resp.addHeader("Access-Control-Allow-Origin","*"); resp.addHeader("Access-Control-Allow-Methods","GET,POST"); resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range, Authorization"); // Just ACCEPT and REPLY OK if OPTIONS if (request.getMethod().equals("OPTIONS")) { resp.setStatus(HttpServletResponse.SC_OK); return; } chain.doFilter(request, servletResponse); } @Override public void destroy() {} }
package org.opencb.opencga.server; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by pfurio on 04/10/16. */ public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("Request " + request.getMethod()); HttpServletResponse resp = (HttpServletResponse) servletResponse; resp.addHeader("Access-Control-Allow-Origin","*"); resp.addHeader("Access-Control-Allow-Methods","GET,POST"); resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range"); // Just ACCEPT and REPLY OK if OPTIONS if (request.getMethod().equals("OPTIONS")) { resp.setStatus(HttpServletResponse.SC_OK); return; } chain.doFilter(request, servletResponse); } @Override public void destroy() {} }
Adjust MorphForm textarea boxes to fill available height
import * as v from '../../styles/variables' const styles = { section: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'stretch', alignContent: 'flex-start', width: '100%' }, container: { position: 'relative', width: '100%', height: `calc(100% - ${2 * v.lnht}rem)` /* 100% minus the header height */ }, dataInput: { position: 'absolute', width: '100%', height: '100%', resize: 'none', wordWrap: 'normal', padding: 2 }, textAreaSpacer: { width: '100%', height: '100%', wordWrap: 'normal', whiteSpace: 'pre', padding: { top: 2, right: `${v.lnht}rem`, bottom: `${v.lnht}rem`, left: 2 }, borderWidth: 1, visibility: 'hidden' }, inputSection: { minWidth: `${3 * v.ms6}rem`, flexGrow: 2, padding: `0 ${v.lnht / 2}rem` } } export default styles
import * as v from '../../styles/variables' const styles = { section: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'stretch', alignContent: 'flex-start', width: '100%' }, container: { position: 'relative', width: '100%' }, dataInput: { position: 'absolute', width: '100%', height: '100%', resize: 'none', wordWrap: 'normal', padding: 2 }, textAreaSpacer: { width: '100%', wordWrap: 'normal', whiteSpace: 'pre', padding: { top: 2, right: `${v.lnht}rem`, bottom: `${v.lnht}rem`, left: 2 }, borderWidth: 1, visibility: 'hidden' }, inputSection: { minWidth: `${3 * v.ms6}rem`, flexGrow: 2, padding: `0 ${v.lnht / 2}rem` } } export default styles
Reorganize for 100% for UserToken.
<?php namespace inklabs\kommerce\Entity; class UserTokenTest extends \PHPUnit_Framework_TestCase { public function testCreate() { $userToken = new UserToken; $userToken->setUserAgent('UserAgent'); $userToken->setToken('token'); $userToken->setType('type'); $userToken->setExpires(null); $this->assertEquals(null, $userToken->getId()); $this->assertEquals('UserAgent', $userToken->getUserAgent()); $this->assertEquals('token', $userToken->getToken()); $this->assertEquals('type', $userToken->getType()); $this->assertEquals(null, $userToken->getExpires()); } }
<?php namespace inklabs\kommerce\Entity; class UserTokenTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->userToken = new UserToken; $this->userToken->setUserAgent('XXX'); $this->userToken->setToken('XXX'); $this->userToken->setType('XXX'); $this->userToken->setExpires(null); } public function testGetter() { $this->assertEquals(null, $this->userToken->getId()); $this->assertEquals('XXX', $this->userToken->getUserAgent()); $this->assertEquals('XXX', $this->userToken->getToken()); $this->assertEquals('XXX', $this->userToken->getType()); $this->assertEquals(null, $this->userToken->getExpires()); } }
Update command to work with sublime 3
import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Fix forgot to make coffeescript :-)
// Generated by CoffeeScript 1.9.3 (function() { var $, Radio, initCordova; $ = require('jquery'); Radio = require('backbone.radio'); initCordova = function() { var eventName, i, len, ref; $(document).on('deviceready', function() { return require('./cordova/ios_network_activity').init(); }); ref = ['deviceready', 'pause', 'resume', 'backbutton', 'offline', 'online']; for (i = 0, len = ref.length; i < len; i++) { eventName = ref[i]; $(document).on(eventName, function(e) { return Radio.channel('app').trigger(e.type); }); } return $(function() { return $('body').addClass("platform-" + cordova.platformId); }); }; if (window.cordova) { initCordova(); } }).call(this);
// Generated by CoffeeScript 1.9.3 (function() { var $, Radio, initCordova; $ = require('jquery'); Radio = require('backbone.radio'); initCordova = function() { var eventName, i, len, ref; $(document).on('deviceready', function() { return require('./cordova/ios_network_activity').init(); }); ref = ['pause', 'resume', 'backbutton', 'offline', 'online']; for (i = 0, len = ref.length; i < len; i++) { eventName = ref[i]; $(document).on(eventName, function(e) { return Radio.channel('app').trigger(e.type); }); } return $(function() { return $('body').addClass("platform-" + cordova.platformId); }); }; if (window.cordova) { initCordova(); } }).call(this);
Handle GitHub's updated Content Security Policy It looks like GitHub changed their CSP recently. This extension didn't work for me until I added this code.
// this idea borrowed from // https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html chrome.webRequest.onHeadersReceived.addListener(function(details) { for (i = 0; i < details.responseHeaders.length; i++) { if (isCSPHeader(details.responseHeaders[i].name.toUpperCase())) { var csp = details.responseHeaders[i].value; csp = csp.replace("media-src 'none'", "media-src 'self' blob:"); csp = csp.replace("connect-src 'self' uploads.github.com status.github.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com wss://live.github.com", "connect-src 'self' uploads.github.com status.github.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com wss://live.github.com api.imgur.com"); details.responseHeaders[i].value = csp; } } return { // Return the new HTTP header responseHeaders: details.responseHeaders }; }, { urls: ["*://github.com/*"], types: ["main_frame"] }, ["blocking", "responseHeaders"]); function isCSPHeader(headerName) { return (headerName == 'CONTENT-SECURITY-POLICY') || (headerName == 'X-WEBKIT-CSP'); }
// this idea borrowed from // https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html chrome.webRequest.onHeadersReceived.addListener(function(details) { for (i = 0; i < details.responseHeaders.length; i++) { if (isCSPHeader(details.responseHeaders[i].name.toUpperCase())) { var csp = details.responseHeaders[i].value; csp = csp.replace("media-src 'none'", "media-src 'self' blob:"); details.responseHeaders[i].value = csp; } } return { // Return the new HTTP header responseHeaders: details.responseHeaders }; }, { urls: ["*://github.com/*"], types: ["main_frame"] }, ["blocking", "responseHeaders"]); function isCSPHeader(headerName) { return (headerName == 'CONTENT-SECURITY-POLICY') || (headerName == 'X-WEBKIT-CSP'); }
Add method to get the content as a string which is required for message manipulations in runtime
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.messaging; import java.util.Map; /** * An interface which represents the message after loading in to memory (After first built) */ public interface MessageDataSource { public String getValueAsString(String path); public String getValueAsString(String path, Map<String, String> properties); public Object getValue(String path); public Object getDataObject(); public String getContentType(); public void setContentType(String type); public void serializeData(); public String getMessageAsString(); }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.messaging; import java.util.Map; /** * An interface which represents the message after loading in to memory (After first built) */ public interface MessageDataSource { public String getValueAsString(String path); public String getValueAsString(String path, Map<String, String> properties); public Object getValue(String path); public Object getDataObject(); public String getContentType(); public void setContentType(String type); public void serializeData(); }
Load messages and set local properly Fixes missing uiv translations in plugin repo
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Vue2Filters from 'vue2-filters' import VueCookies from 'vue-cookies' import VueScrollTo from 'vue-scrollto' import VueFuse from 'vue-fuse' import VueI18n from 'vue-i18n' import uivLang from '../../utilities/uivi18n' import * as uiv from 'uiv' import store from './stores' import router from './router' import App from './App' Vue.config.productionTip = false Vue.use(VueCookies) Vue.use(VueScrollTo) Vue.use(VueFuse) Vue.use(Vue2Filters) Vue.use(uiv) let locale = window._rundeck.locale || 'en_US' let lang = window._rundeck.language || 'en' // include any i18n injected in the page by the app let messages = { [locale]: Object.assign({}, uivLang[locale] || uivLang[lang] || {}, window.Messages ) } console.log(messages) const i18n = new VueI18n({ silentTranslationWarn: true, locale, // set locale messages // set locale messages, }) /* eslint-disable no-new */ new Vue({ el: '#repository-vue', store, router, components: { App }, template: '<App/>', i18n })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Vue2Filters from 'vue2-filters' import VueCookies from 'vue-cookies' import VueScrollTo from 'vue-scrollto' import VueFuse from 'vue-fuse' import VueI18n from 'vue-i18n' import uivLang from '../../utilities/uivi18n' import * as uiv from 'uiv' import store from './stores' import router from './router' import App from './App' Vue.config.productionTip = false Vue.use(VueCookies) Vue.use(VueScrollTo) Vue.use(VueFuse) Vue.use(Vue2Filters) Vue.use(uiv) let messages = { en_US: Object.assign( {}, uivLang['en_US'] || uivLang['en'] || {}, window.Messages ) } const i18n = new VueI18n({ silentTranslationWarn: true, locale: 'en', // set locale messages // set locale messages, }) /* eslint-disable no-new */ new Vue({ el: '#repository-vue', store, router, components: { App }, template: '<App/>', i18n })
Fix last commit: use config.log()
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): skoleintra.config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
Add test case for OnlineStatistics where axis is a tuple
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0), ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) if isinstance(axis, (list, tuple)): data_size = np.prod([X.shape[ax] for ax in axis]) else: data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
Use / as the primary delimiter in compound key We want to avoid confusion between kebab_case'd model names, and components of the compound key. If for some reason a dev wants to parse the compound key (i.e. the Solr key) into parts, using a different top-level delimiter will ease this process.
<?php namespace App\Shop; use Illuminate\Database\Eloquent\Model; use App\Scopes\SortByLastUpdatedScope; use Laravel\Scout\Searchable; class ShopModel extends Model { use Searchable; public $incrementing = false; protected $primaryKey = 'shop_id'; protected $dates = ['source_created_at', 'source_modified_at']; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = []; protected static function boot() { parent::boot(); static::addGlobalScope(new SortByLastUpdatedScope()); } protected function searchableModel() { return kebab_case(class_basename(static::class)); } protected function searchableSource() { return 'shop'; } protected function searchableId() { return $this->searchableSource() .'/' .$this->searchableModel() .'/' .$this->shop_id; } }
<?php namespace App\Shop; use Illuminate\Database\Eloquent\Model; use App\Scopes\SortByLastUpdatedScope; use Laravel\Scout\Searchable; class ShopModel extends Model { use Searchable; public $incrementing = false; protected $primaryKey = 'shop_id'; protected $dates = ['source_created_at', 'source_modified_at']; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = []; protected static function boot() { parent::boot(); static::addGlobalScope(new SortByLastUpdatedScope()); } protected function searchableModel() { return kebab_case(class_basename(static::class)); } protected function searchableSource() { return 'shop'; } protected function searchableId() { return $this->searchableSource() .'-' .$this->searchableModel() .'-' .$this->shop_id; } }
Fix typo for named argument
import tensorflow as tf def masked_softmax_cross_entropy(preds, labels, mask): """Softmax cross-entropy loss with masking.""" loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) loss *= mask return tf.reduce_mean(loss) def masked_accuracy(preds, labels, mask): """Accuracy with masking.""" correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) accuracy_all = tf.cast(correct_prediction, tf.float32) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) accuracy_all *= mask return tf.reduce_mean(accuracy_all)
import tensorflow as tf def masked_softmax_cross_entropy(preds, labels, mask): """Softmax cross-entropy loss with masking.""" loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, lables=labels) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) loss *= mask return tf.reduce_mean(loss) def masked_accuracy(preds, labels, mask): """Accuracy with masking.""" correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1)) accuracy_all = tf.cast(correct_prediction, tf.float32) mask = tf.cast(mask, dtype=tf.float32) mask /= tf.reduce_mean(mask) accuracy_all *= mask return tf.reduce_mean(accuracy_all)
Add RPI3B+ support and remove IMX6UL Update samples to add RPI3B+ and remove IMX6UL support. Bug: 112590677 Bug: 112603667 Change-Id: I99d174bf17bc75e1d17192bc1e1227c97f85d171
/* * Copyright 2016, The Android Open Source Project * * 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. */ package com.example.androidthings.doorbell; import android.os.Build; @SuppressWarnings("WeakerAccess") public class BoardDefaults { private static final String DEVICE_RPI3 = "rpi3"; private static final String DEVICE_RPI3BP = "rpi3bp"; private static final String DEVICE_IMX7D_PICO = "imx7d_pico"; /** * Return the GPIO pin that the Button is connected on. */ public static String getGPIOForButton() { switch (Build.DEVICE) { case DEVICE_RPI3: case DEVICE_RPI3BP: return "BCM21"; case DEVICE_IMX7D_PICO: return "GPIO6_IO14"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } }
/* * Copyright 2016, The Android Open Source Project * * 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. */ package com.example.androidthings.doorbell; import android.os.Build; @SuppressWarnings("WeakerAccess") public class BoardDefaults { private static final String DEVICE_RPI3 = "rpi3"; private static final String DEVICE_IMX7D_PICO = "imx7d_pico"; /** * Return the GPIO pin that the Button is connected on. */ public static String getGPIOForButton() { switch (Build.DEVICE) { case DEVICE_RPI3: return "BCM21"; case DEVICE_IMX7D_PICO: return "GPIO6_IO14"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } }
Improve comment around transformed attributes
import { Component, Children, PropTypes } from "react"; import withSideEffect from "react-side-effect"; const supportedHTML4Attributes = { "bgColor": "bgcolor" }; class BodyAttributes extends Component { render() { return Children.only(this.props.children); } } BodyAttributes.propTypes = { children: PropTypes.node.isRequired }; function reducePropsToState(propsList) { const attrs = {}; propsList.forEach(function (props) { const transformedAttrs = transformHTML4Props(props); Object.assign(attrs, props, transformedAttrs); }); return attrs; } function handleStateChangeOnClient(attrs) { for (const key in attrs) { document.body.setAttribute(key, attrs[key]); } } function transformHTML4Props(props) { const transformedProps = {}; /* * Provide support for HTML4 attributes on the body tag for * e-mail purposes. Convert tags to ones oy-vey can translate * during the render. * * Note: Only attributes that are white-listed by oy-vey will be rendered * */ Object.keys(supportedHTML4Attributes).forEach(propName => { if (props.hasOwnProperty(propName)) { const name = supportedHTML4Attributes[propName]; const value = props[propName]; const transformedProp = { [`data-oy-${name}`]: value }; Object.assign(transformedProps, transformedProp); } }); return transformedProps; } export default withSideEffect( reducePropsToState, handleStateChangeOnClient )(BodyAttributes);
import { Component, Children, PropTypes } from "react"; import withSideEffect from "react-side-effect"; const supportedHTML4Attributes = { "bgColor": "bgcolor" }; class BodyAttributes extends Component { render() { return Children.only(this.props.children); } } BodyAttributes.propTypes = { children: PropTypes.node.isRequired }; function reducePropsToState(propsList) { const attrs = {}; propsList.forEach(function (props) { const transformedAttrs = transformHTML4Props(props); Object.assign(attrs, props, transformedAttrs); }); return attrs; } function handleStateChangeOnClient(attrs) { for (const key in attrs) { document.body.setAttribute(key, attrs[key]); } } function transformHTML4Props(props) { const transformedProps = {}; // Provide support for HTML4 attributes on the body tag for // e-mail purposes. Convert tags to ones oy-vey can translate // during the render. Object.keys(supportedHTML4Attributes).forEach(propName => { if (props.hasOwnProperty(propName)) { const name = supportedHTML4Attributes[propName]; const value = props[propName]; const transformedProp = { [`data-oy-${name}`]: value }; Object.assign(transformedProps, transformedProp); } }); return transformedProps; } export default withSideEffect( reducePropsToState, handleStateChangeOnClient )(BodyAttributes);
Remove 'b' classifer on FileToList's read() usage
""" Class for FileToList """ class FileToList(object): """ FileToList is a helper class used to import text files and turn them into lists, with each index in the list representing a single line from the text file. """ @staticmethod def to_list(file_path): """ Static method. Takes in a file path, and outputs a list of stings. Each element in the list corresponds to a line in the file. :param file_path: string file path :return: A list of strings, with elements in the list corresponding to lines in the file pointed to in file_path """ l = [] f = open(file_path, 'r') for line in f: l.append(line) f.close() return l
""" Class for FileToList """ class FileToList(object): """ FileToList is a helper class used to import text files and turn them into lists, with each index in the list representing a single line from the text file. """ @staticmethod def to_list(file_path): """ Static method. Takes in a file path, and outputs a list of stings. Each element in the list corresponds to a line in the file. :param file_path: string file path :return: A list of strings, with elements in the list corresponding to lines in the file pointed to in file_path """ l = [] f = open(file_path, 'rb') for line in f: l.append(line) f.close() return l
Add more accurate time to unit observations
import React from 'react'; import moment from 'moment'; import {translate} from 'react-i18next'; const formatTime = (time: Date, t: Function) => { const now = moment(); let lookup = 'TIME.'; let options = {}; if(now.diff(time, 'days') === 0) { lookup += 'TODAY'; } else if (now.diff(time, 'days') === 1) { lookup += 'YESTERDAY'; } else if (now.diff(time, 'weeks') === 0) { lookup += 'DAYS_AGO'; options.days = now.diff(time, 'days'); } else if (now.diff(time, 'months') === 0) { lookup += 'WEEKS_AGO'; options.weeks = now.diff(time, 'weeks'); } else if (now.diff(time, 'years' > 1)) { lookup += 'NOT_AVAILABLE'; } else { lookup += 'MONTHS_AGO'; options.months = now.diff(time, 'months'); } return t(lookup, options); }; const Time = translate()(({time, t}) => <time dateTime={time.toISOString()}> { formatTime(time, t) } {moment().diff(time, 'days') < 2 && ' '+time.getHours()+':'+time.getMinutes()} </time> ); export default Time;
import React from 'react'; import moment from 'moment'; import {translate} from 'react-i18next'; const formatTime = (time: Date, t: Function) => { const now = moment(); let lookup = 'TIME.'; let options = {}; if(now.diff(time, 'days') === 0) { lookup += 'TODAY'; } else if (now.diff(time, 'days') === 1) { lookup += 'YESTERDAY'; } else if (now.diff(time, 'weeks') === 0) { lookup += 'DAYS_AGO'; options.days = now.diff(time, 'days'); } else if (now.diff(time, 'months') === 0) { lookup += 'WEEKS_AGO'; options.weeks = now.diff(time, 'weeks'); } else if (now.diff(time, 'years' > 1)) { lookup += 'NOT_AVAILABLE'; } else { lookup += 'MONTHS_AGO'; options.months = now.diff(time, 'months'); } return t(lookup, options); }; const Time = translate()(({time, t}) => <time dateTime={time.toISOString()}> { formatTime(time, t) } </time> ); export default Time;
Add PERSISTENT option to MySQL connection.
<?php namespace Jafaripur\DAL; /** * Abstract Class MySQLOwnClient for using MySQL * * Each of model want to use MySQL should extend from this class * * @author A.Jafaripur <mjafaripur@yahoo.com> * */ abstract class MySQLOwnClient extends \PDO { const SERVER = 'localhost'; const USERNAME = 'jafaripur'; const PASSWORD = '123456'; const DB = 'test'; public function __construct() { try { $options = array( \PDO::ATTR_PERSISTENT => true, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, ); parent::__construct("mysql:dbname=" . self::DB . ";host=" . self::SERVER, self::USERNAME, self::PASSWORD, $options); $this->exec("SET NAMES utf8"); } catch (\PDOException $e) { echo '<p>' . $ex->getMessage() . "</p>"; echo $ex->getTraceAsString(); die(); } } }
<?php namespace Jafaripur\DAL; /** * Abstract Class MySQLOwnClient for using MySQL * * Each of model want to use MySQL should extend from this class * * @author A.Jafaripur <mjafaripur@yahoo.com> * */ abstract class MySQLOwnClient extends \PDO { const SERVER = 'localhost'; const USERNAME = 'jafaripur'; const PASSWORD = '123456'; const DB = 'test'; public function __construct() { try { $options = array( \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, ); parent::__construct("mysql:dbname=" . self::DB . ";host=" . self::SERVER, self::USERNAME, self::PASSWORD, $options); $this->exec("SET NAMES utf8"); } catch (\PDOException $e) { echo '<p>' . $ex->getMessage() . "</p>"; echo $ex->getTraceAsString(); die(); } } }
Expand default testing on new object types
import cybox.utils class ObjectTestCase(object): """A base class for testing all subclasses of ObjectProperties. Each subclass of ObjectTestCase should subclass both unittest.TestCase and ObjectTestCase, and defined two class-level fields: - klass: the ObjectProperties subclass being tested - object_type: The name prefix used in the XML Schema bindings for the object. """ def test_type_exists(self): # Verify that the correct class has been added to the OBJECT_TYPES_DICT # dictionary in cybox.utils.nsparser # Skip this base class if type(self) == type(ObjectTestCase): return t = self.__class__.object_type expected_class = cybox.utils.get_class_for_object_type(t) actual_class = self.__class__.klass self.assertEqual(expected_class, actual_class) expected_namespace = expected_class._XSI_NS actual_namespace = cybox.utils.nsparser.OBJECT_TYPES_DICT.get(t).get('namespace_prefix') self.assertEqual(expected_namespace, actual_namespace) self.assertEqual(expected_class._XSI_TYPE, t)
import cybox.utils class ObjectTestCase(object): """A base class for testing all subclasses of ObjectProperties. Each subclass of ObjectTestCase should subclass both unittest.TestCase and ObjectTestCase, and defined two class-level fields: - klass: the ObjectProperties subclass being tested - object_type: The name prefix used in the XML Schema bindings for the object. """ def test_type_exists(self): # Verify that the correct class has been added to the OBJECTS # dictionary in cybox.utils print(type(self)) if type(self) == type(ObjectTestCase): return t = self.__class__.object_type c = self.__class__.klass self.assertEqual(cybox.utils.get_class_for_object_type(t), c)
[INTERNAL] CardExplorer: Use correct path in Custom Actions sample Change-Id: I73b3f8aadd7b375267435e0b43cc1376c0d3447f BCP: 2080456866
sap.ui.define(["sap/ui/integration/Extension", "sap/ui/integration/ActionDefinition"], function (Extension, ActionDefinition) { "use strict"; var CustomActionsExtension = Extension.extend("card.explorer.extension.customActions.CustomActionsExtension"); CustomActionsExtension.prototype.onCardReady = function () { var oCard = this.getCard(); oCard.addActionDefinition(new ActionDefinition({ type: "Custom", text: "{i18n>reportActionText}", enabled: true, press: function (oEvent) { var oReportAction = oEvent.getSource(); oReportAction.setEnabled(false); } })); // Actions can be added at any time, for example after response from a backend oCard.request({ url: "./urlInfo.json" }).then(function (oRes) { oCard.addActionDefinition(new ActionDefinition({ type: "Navigation", text: "{i18n>bookActionText}", icon: "sap-icon://learning-assistant", parameters: { url: oRes.url } })); }); }; return CustomActionsExtension; });
sap.ui.define(["sap/ui/integration/Extension", "sap/ui/integration/ActionDefinition"], function (Extension, ActionDefinition) { "use strict"; var CustomActionsExtension = Extension.extend("card.explorer.extension.customActions.CustomActionsExtension"); CustomActionsExtension.prototype.onCardReady = function () { var oCard = this.getCard(); oCard.addActionDefinition(new ActionDefinition({ type: "Custom", text: "{i18n>reportActionText}", enabled: true, press: function (oEvent) { var oReportAction = oEvent.getSource(); oReportAction.setEnabled(false); } })); // Actions can be added at any time, for example after response from a backend oCard.request({ url: sap.ui.require.toUrl("card/explorer/extension/customActions/urlInfo.json") }).then(function (oRes) { oCard.addActionDefinition(new ActionDefinition({ type: "Navigation", text: "{i18n>bookActionText}", icon: "sap-icon://learning-assistant", parameters: { url: oRes.url } })); }); }; return CustomActionsExtension; });
Fix errors cause by key error in sys.modules and wrong type error by uFid.
import importlib import importlib.machinery import sys from module import Module import json def message_to_function(raw_message): """ converting json formatted string to a executable module. Args: raw_message (str): json formatted. Returns: None if raw_message is in wrong format, else return the executable module. """ if raw_message is None: return None try: wisp = json.loads(raw_message) except json.JSONDecodeError: return None function_object = wisp["function_object"] path = function_object["function_path"] force_update = function_object["validate"] params = wisp["params"] name = str(wisp["uFid"]) loader = importlib.machinery.SourceFileLoader(name, path) # if modules exists on the memory. if name in sys.modules.keys(): if force_update: del sys.modules[name] else: return sys.modules[name] mod = None try: mod = loader.load_module() except FileNotFoundError: print("Module not found") finally: if mod is not None: wisp_module = Module(mod, params) return wisp_module return mod
import importlib import importlib.machinery import sys from module import Module import json def message_to_function(raw_message): """ converting json formatted string to a executable module. Args: raw_message (str): json formatted. Returns: None if raw_message is in wrong format, else return the executable module. """ if raw_message is None: return None try: wisp = json.loads(raw_message) except json.JSONDecodeError: return None function_object = wisp["function_object"] path = function_object["function_path"] force_update = function_object["validate"] params = wisp["params"] name = wisp["uFid"] loader = importlib.machinery.SourceFileLoader(name, path) # if force update is enabled, and module exists. if force_update and sys.modules[name]: del sys.modules[name] # if force update is not enabled and module exists. elif sys.modules[name]: return sys.modules[name] # Whether force update or module does not exists. mod = None try: mod = loader.load_module() except FileNotFoundError: print("Module not found") finally: if mod is not None: wisp_module = Module(mod, params) return wisp_module return mod
Update test runner syntax to the new arista-transcode syntax and always output a status report even if the user stops the tests early.
#!/usr/bin/env python """ Run Arista Transcode Tests ========================== Generate test files in various formats and transcode them to all available output devices and qualities. """ import os import subprocess import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) import arista; arista.init() if not os.path.exists("tests"): os.system("./utils/generate_tests.py") files = os.listdir("tests") status = [] try: for id, device in arista.presets.get().items(): for file in files: print device.make + " " + device.model + ": " + file cmd = "./arista-transcode -q -d %s -o test_output tests/%s" % (id, file) print cmd ret = subprocess.call(cmd, shell=True) if ret: status.append([file, device, True]) else: status.append([file, device, False]) except KeyboardInterrupt: pass print "Report" print "======" for file, device, failed in status: if failed: print device.make + " " + device.model + " (" + \ file + "): Failed" else: print device.make + " " + device.model + " (" + \ file + "): Succeeded" print "Tests completed."
#!/usr/bin/env python """ Run Arista Transcode Tests ========================== Generate test files in various formats and transcode them to all available output devices and qualities. """ import os import subprocess import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) import arista; arista.init() if not os.path.exists("tests"): os.system("./utils/generate_tests.py") files = os.listdir("tests") status = [] try: for id, device in arista.presets.get().items(): for file in files: print device.make + " " + device.model + ": " + file cmd = "./arista-transcode -q -d %s tests/%s test_output" % (id, file) print cmd ret = subprocess.call(cmd, shell=True) if ret: status.append([file, device, True]) else: status.append([file, device, False]) print "Report" print "======" for file, device, failed in status: if failed: print device.make + " " + device.model + " (" + \ file + "): Failed" else: print device.make + " " + device.model + " (" + \ file + "): Succeeded" print "Tests completed." except KeyboardInterrupt: pass
Switch from bold to red highlighting. With many terminal fonts bold is subtle. The red is much more clear.
# Copyright Google # BSD License import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, red_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) red_ids = [id(lot) for lot in red_lots] for lot in lots: header = '' footer = '' if id(lot) in red_ids: header = color.RED footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, red_lots): pass
# Copyright Google # BSD License import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, bold_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) bold_ids = [id(lot) for lot in bold_lots] for lot in lots: header = '' footer = '' if id(lot) in bold_ids: header = color.BOLD footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, bold_lots): pass
Add designer photo and location to designer page.
@extends('layout.app', [ 'title' => $designer->getTranslation()->name . ' - Designer', 'body_id' => 'designer-page', 'body_class' => 'designer-page', ]) @section('content') @if (!Auth::guest()) <div id="action-bar"> <div class="container"> <a href="{{ url('/designer/'.$designer->id.'/edit') }}" id="edit-button" class="btn btn-default pull-right">Edit</a> </div> </div> @endif <header> <div class="container"> <img src="{{ $designer->getMainImage()->getThumbUrl() }}" /> <h1 class="title">{{ $designer->getTranslation()->name }}</h1> <p>Helsinki, Finland</p> </div> </header> <div id="picture-carousel" class="carousel"> @foreach ($designer->getImages() as $image) <div class="picture-thumb" data-src="{{ url($image->getUrl()) }}" data-thumb="{{ url($image->getThumbUrl()) }}" style="background-image:url({{ url($image->getThumbUrl()) }})"></div> @endforeach </div> <article id="designer-{{ $designer->id }}" class="designer container"> {{ $designer->getTranslation()->content }} </article> @endsection
@extends('layout.app', [ 'title' => $designer->getTranslation()->name . ' - Designer', 'body_id' => 'designer-page', 'body_class' => 'designer-page', ]) @section('content') @if (!Auth::guest()) <div class="container"> <a href="{{ url('/designer/'.$designer->id.'/edit') }}" id="edit-button" class="btn btn-default pull-right">Edit</a> </div> @endif <div id="picture-carousel" class="carousel"> @foreach ($designer->getImages() as $image) <div class="picture-thumb" data-src="{{ url($image->getUrl()) }}" data-thumb="{{ url($image->getThumbUrl()) }}" style="background-image:url({{ url($image->getThumbUrl()) }})"></div> @endforeach </div> <article id="designer-{{ $designer->id }}" class="designer container"> <h1 class="title">{{ $designer->getTranslation()->name }}</h1> <div class="content">{!! $designer->getTranslation()->content !!}</div> </article> @endsection
Add case of escape branch for newMatcher
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`(abc)`)}, {"a,b", regexp.MustCompile(`(a|b)`)}, {"a\\,b", regexp.MustCompile(`(a,b)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`(abc)`)}, {"a,b", regexp.MustCompile(`(a|b)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
Fix sourcemap for dev mode
module.exports = { entry: { javascript: "./app/app.jsx" }, output: { path: __dirname, filename: "bundle.js" }, resolve: { extensions: ["", ".json", ".js", ".jsx"] }, module: { noParse: [/autoit.js/], loaders: [ { test: /\.css$/, loader: "style!css" }, { test: /\.jsx$/, loaders: ["react-hot", "babel-loader"] }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' } ] }, devtool: 'source-map' }
module.exports = { entry: { javascript: "./app/app.jsx" }, output: { path: __dirname, filename: "bundle.js" }, resolve: { extensions: ["", ".json", ".js", ".jsx"] }, module: { noParse: [/autoit.js/], loaders: [ { test: /\.css$/, loader: "style!css" }, { test: /\.jsx$/, loaders: ["react-hot", "babel-loader"] }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' } ] }, devtool: "#inline-source-map" }
Add multiple permissions to a single export
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret
Fix for a potential NPE Signed-off-by: Gorkem Ercan <401a00c042ea0ce3e74815aa3e2dca472ed1e2f8@gmail.com>
/******************************************************************************* * Copyright (c) 2013, 2014 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.thym.android.core.adt; import java.util.Comparator; public class AndroidAPILevelComparator implements Comparator<String>{ @Override public int compare(String sdk1, String sdk2) { if(sdk1 == null || sdk2 == null ){ throw new NullPointerException("comparator arguments can not be null"); } char[] l1 = sdk1.toCharArray(); char[] l2 = sdk2.toCharArray(); for (int i = 0; i < Math.min(l1.length, l2.length); i++) { if(l1[i] > l2[i]){ return 1; } if(l1[i] < l2[i]){ return -1; } } if(l1.length > l2.length ){ return 1; } if(l1.length < l2.length ){ return -1; } return 0; } }
/******************************************************************************* * Copyright (c) 2013, 2014 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.thym.android.core.adt; import java.util.Comparator; public class AndroidAPILevelComparator implements Comparator<String>{ @Override public int compare(String sdk1, String sdk2) { if(sdk1 == null && sdk2 == null ){ throw new NullPointerException("comparator arguments can not be null"); } char[] l1 = sdk1.toCharArray(); char[] l2 = sdk2.toCharArray(); for (int i = 0; i < Math.min(l1.length, l2.length); i++) { if(l1[i] > l2[i]){ return 1; } if(l1[i] < l2[i]){ return -1; } } if(l1.length > l2.length ){ return 1; } if(l1.length < l2.length ){ return -1; } return 0; } }
Remove call to `console.log` in build script
'use strict'; var zone = require('mdast-zone'); var u = require('unist-builder'); var sort = require('alphanum-sort/lib/compare'); var gemoji = require('gemoji').unicode; var emotion = require('..'); module.exports = support; function support() { return transformer; } function transformer(tree) { zone(tree, 'support', replace); } function replace(start, nodes, end) { return [start, table(), end]; } function table() { var header = ['Emoji', 'Name(s)', 'Polarity']; return u('table', {align: []}, [ u('tableRow', header.map(cell)) ].concat( emotion .sort(function (a, b) { return a.polarity - b.polarity || sort({}, gemoji[a.emoji].name, gemoji[b.emoji].name); }) .map(function (emotion) { return u('tableRow', [ cell(emotion.emoji), cell(gemoji[emotion.emoji].names.join('; ')), cell(emotion.polarity) ]); }) )); } function cell(value) { return u('tableCell', [u('text', value)]); }
'use strict'; var zone = require('mdast-zone'); var u = require('unist-builder'); var sort = require('alphanum-sort/lib/compare'); var gemoji = require('gemoji').unicode; var emotion = require('..'); module.exports = support; function support() { return transformer; } function transformer(tree) { zone(tree, 'support', replace); } function replace(start, nodes, end) { console.log('repl!'); return [start, table(), end]; } function table() { var header = ['Emoji', 'Name(s)', 'Polarity']; return u('table', {align: []}, [ u('tableRow', header.map(cell)) ].concat( emotion .sort(function (a, b) { return a.polarity - b.polarity || sort({}, gemoji[a.emoji].name, gemoji[b.emoji].name); }) .map(function (emotion) { return u('tableRow', [ cell(emotion.emoji), cell(gemoji[emotion.emoji].names.join('; ')), cell(emotion.polarity) ]); }) )); } function cell(value) { return u('tableCell', [u('text', value)]); }
Make call to wordpress installation (TODO: mock)
package com.afrozaar.wordpress.wpapi.v2; import com.afrozaar.wordpress.wpapi.v2.model.Post; import com.afrozaar.wordpress.wpapi.v2.util.ClientFactory; import org.assertj.core.api.Assertions; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; public class ClientTest { Logger LOG = LoggerFactory.getLogger(ClientTest.class); @Test public void foo() { Assertions.assertThat("x").isEqualTo("x"); } @Test public void posts() { Properties properties = new Properties(); properties.put("baseUrl", "http://localhost/"); properties.put("username", "username"); properties.put("password", "password"); LOG.debug("properties: {}", properties); Client client = ClientFactory.fromProperties(properties); final PagedResponse<Post> postPagedResponse = client.fetchPosts(); final long count = postPagedResponse.list.stream().count(); // TODO: } }
package com.afrozaar.wordpress.wpapi.v2; import com.afrozaar.wordpress.wpapi.v2.model.Post; import com.afrozaar.wordpress.wpapi.v2.util.ClientFactory; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.Properties; public class ClientTest { @Test public void foo() { Assertions.assertThat("x").isEqualTo("x"); } @Test public void posts() { Properties properties = new Properties(); properties.put("baseUrl", "http://localhost/"); Client client = ClientFactory.fromProperties(properties); final PagedResponse<Post> postPagedResponse = client.fetchPosts(); // TODO } }
Add assertion for number of fields on person
from test.utils.assertions import assert_header_value, assert_json_response from test.utils.helpers import get_json_from_response, get_identifier_for_created_person # noinspection PyPep8Naming,PyShadowingNames class Test_When_No_People_Exist(object): def test_status_code(self, get_people): assert get_people().status_code == 200 def test_header_content_type(self, get_people): assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers) def test_body(self, get_people): assert_json_response({'data': [], 'type': 'person_list'}, get_people()) # noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal class Test_When_One_Person_Exists(object): def test_body_should_contain_one_person(self, create_person, get_people): response = create_person('Frank Stella') people = get_json_from_response(get_people())['data'] assert len(people) == 1 person = people[0] person_id = get_identifier_for_created_person(response) assert len(person) == 2 assert person['name'] == 'Frank Stella' assert person['id'] == person_id
from test.utils.assertions import assert_header_value, assert_json_response from test.utils.helpers import get_json_from_response, get_identifier_for_created_person # noinspection PyPep8Naming,PyShadowingNames class Test_When_No_People_Exist(object): def test_status_code(self, get_people): assert get_people().status_code == 200 def test_header_content_type(self, get_people): assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers) def test_body(self, get_people): assert_json_response({'data': [], 'type': 'person_list'}, get_people()) # noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal class Test_When_One_Person_Exists(object): def test_body_should_contain_one_person(self, create_person, get_people): response = create_person('Frank Stella') people = get_json_from_response(get_people())['data'] assert len(people) == 1 person = people[0] person_id = get_identifier_for_created_person(response) assert person['name'] == 'Frank Stella' assert person['id'] == person_id
Move testing code into "if __name__ == '__main__'" so it's not run on import.
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise
Test reset on scatter pipe.
package com.tinkerpop.pipes.util; import com.tinkerpop.pipes.BaseTest; import com.tinkerpop.pipes.Pipe; import java.util.Arrays; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ScatterPipeTest extends BaseTest { public void testScatterPipe() { Pipe scatter = new ScatterPipe(); scatter.setStarts(Arrays.asList(Arrays.asList(1, 2, 3))); int counter = 0; while (scatter.hasNext()) { Object object = scatter.next(); assertTrue(object.equals(1) || object.equals(2) || object.equals(3)); counter++; } assertEquals(counter, 3); scatter.setStarts(Arrays.asList(Arrays.asList(1, 2, 3))); scatter.reset(); assertEquals(1, scatter.next()); scatter.setStarts(Arrays.asList(Arrays.asList(1, 2, 3))); scatter.reset(); assertEquals(1, scatter.next()); assertEquals(2, scatter.next()); assertEquals(3, scatter.next()); } }
package com.tinkerpop.pipes.util; import com.tinkerpop.pipes.BaseTest; import com.tinkerpop.pipes.Pipe; import java.util.Arrays; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ScatterPipeTest extends BaseTest { public void testScatterPipe() { Pipe scatter = new ScatterPipe(); scatter.setStarts(Arrays.asList(Arrays.asList(1, 2, 3))); int counter = 0; while (scatter.hasNext()) { Object object = scatter.next(); assertTrue(object.equals(1) || object.equals(2) || object.equals(3)); counter++; } assertEquals(counter, 3); } }
BUGFIX: Add the Generator constructor to the global scope to support Flow generator annotations
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended', 'plugin:import/errors' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true, Generator: true }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended', 'plugin:import/errors' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
FIX end contract depart letter generation
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2017 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, fields, api class EndContractWizard(models.TransientModel): _inherit = 'end.contract.wizard' generate_communication = fields.Boolean( 'Create depart communication') @api.multi def end_contract(self): self.ensure_one() if self.generate_communication: exit_config = self.env.ref( 'partner_communication_switzerland.' 'lifecycle_child_unplanned_exit') self.contract_id.with_context( default_object_ids=self.contract_id.id, default_auto_send=False).send_communication(exit_config) return super(EndContractWizard, self).end_contract()
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2017 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, fields, api class EndContractWizard(models.TransientModel): _inherit = 'end.contract.wizard' generate_communication = fields.Boolean( 'Create depart communication') @api.multi def end_contract(self): self.ensure_one() child = self.child_id if self.generate_communication: exit_config = self.env.ref( 'partner_communication_switzerland.' 'lifecycle_child_unplanned_exit') self.contract_id.with_context( default_object_ids=child.id, default_auto_send=False).send_communication(exit_config) return super(EndContractWizard, self).end_contract()
Add fallback to freetype-config for compatibility.
import os from SCons.Script import * def configure(conf): env = conf.env conf.CBCheckHome('freetype2', inc_suffix=['/include', '/include/freetype2']) if not 'FREETYPE2_INCLUDE' in os.environ: try: env.ParseConfig('pkg-config freetype2 --cflags') except OSError: try: env.ParseConfig('freetype-config --cflags') except OSError: pass if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)): if not conf.CheckOSXFramework('CoreServices'): raise Exception('Need CoreServices framework') conf.CBRequireCHeader('ft2build.h') conf.CBRequireLib('freetype') conf.CBConfig('zlib') conf.CBCheckLib('png') return True def generate(env): env.CBAddConfigTest('freetype2', configure) env.CBLoadTools('osx zlib') def exists(): return 1
import os from SCons.Script import * def configure(conf): env = conf.env conf.CBCheckHome('freetype2', inc_suffix=['/include', '/include/freetype2']) if not 'FREETYPE2_INCLUDE' in os.environ: try: env.ParseConfig('pkg-config freetype2 --cflags') except OSError: pass if env['PLATFORM'] == 'darwin' or int(env.get('cross_osx', 0)): if not conf.CheckOSXFramework('CoreServices'): raise Exception('Need CoreServices framework') conf.CBRequireCHeader('ft2build.h') conf.CBRequireLib('freetype') conf.CBConfig('zlib') conf.CBCheckLib('png') return True def generate(env): env.CBAddConfigTest('freetype2', configure) env.CBLoadTools('osx zlib') def exists(): return 1
Use ejs templates to serve random video
var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var ObjectId = require('mongodb').ObjectID; var url = 'mongodb://localhost:27017/test'; var express = require("express"); var app = express(); var path = require("path"); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/')); app.get('/',function(req,res){ var randomID; MongoClient.connect(url, function(err, db) { assert.equal(null, err); db.collection('videos', function(err, coll) { coll.count(function(err, result){ db.collection('youtubes').findOne({_id: Math.floor(Math.random() * (result-1)) + 1}, function(err, document) { console.log(document); randomID = document["Video UR"]; console.log(randomID); db.close(); res.render(path.join(__dirname+'/index'), { videoID: randomID}); }); }); }); }); }); app.listen(3000);
var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var ObjectId = require('mongodb').ObjectID; var url = 'mongodb://localhost:27017/test'; var express = require("express"); var app = express(); var path = require("path"); app.use(express.static(__dirname + '/')); app.get('/',function(req,res){ res.sendFile(path.join(__dirname+'/index.html')); MongoClient.connect(url, function(err, db) { assert.equal(null, err); db.collection('videos', function(err, coll) { coll.count(function(err, result){ db.collection('youtubes').findOne({_id: Math.floor(Math.random() * (result-1)) + 1}, function(err, document) { console.log(document); console.log(document["Video UR"]); db.close(); }); }); }); }); }); app.listen(3000);
Replace test.done with test.end (patch)
'use strict' const tap = require('tap') const getDokumenter = require('../lib/journals/getDokumenter') tap.test('Requires options to be specified', function (test) { const options = false const expectedErrorMessage = 'Missing required input: options object' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.end() }) }) tap.test('Requires options.host to be specified', function (test) { const options = { host: false } const expectedErrorMessage = 'Missing required input: options.host' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.end() }) }) tap.test('Requires options.journalpostid to be specified', function (test) { const options = { host: true, journalpostid: false } const expectedErrorMessage = 'Missing required input: options.journalpostid' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.end() }) })
'use strict' const tap = require('tap') const getDokumenter = require('../lib/journals/getDokumenter') tap.test('Requires options to be specified', function (test) { const options = false const expectedErrorMessage = 'Missing required input: options object' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.done() }) }) tap.test('Requires options.host to be specified', function (test) { const options = { host: false } const expectedErrorMessage = 'Missing required input: options.host' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.done() }) }) tap.test('Requires options.journalpostid to be specified', function (test) { const options = { host: true, journalpostid: false } const expectedErrorMessage = 'Missing required input: options.journalpostid' getDokumenter(options, function (error, data) { tap.equal(error.message, expectedErrorMessage, expectedErrorMessage) test.done() }) })
Check that env variables are present
<?php declare(strict_types=1); use Discord\Discord; use Monolog\Logger; use PHPUnit\Framework\TestCase; use React\EventLoop\Factory; use React\EventLoop\LoopInterface; final class DiscordTest extends TestCase { public function testCheckEnvVariablesPresent() { $this->assertNotFalse(getenv('DISCORD_TOKEN'), 'Discord token is missing'); $this->assertNotFalse(getenv('TEST_CHANNEL'), 'Test channel ID is missing'); $this->assertNotFalse(getenv('TEST_CHANNEL_NAME'), 'Test channel name is missing'); } /** * @depends testCheckEnvVariablesPresent */ public function testCanConnect() { return wait(function (Discord $discord, $resolve) { $discord->on('ready', function () use ($resolve) { $this->assertTrue(true); $resolve(); }); }); } public function testCanGetChannel() { return wait(function (Discord $discord, $resolve) { $channel = $discord->getChannel(getenv('TEST_CHANNEL')); $this->assertEquals(getenv('TEST_CHANNEL_NAME'), $channel->name); $resolve($channel); }); } }
<?php declare(strict_types=1); use Discord\Discord; use Monolog\Logger; use PHPUnit\Framework\TestCase; use React\EventLoop\Factory; use React\EventLoop\LoopInterface; final class DiscordTest extends TestCase { public function testCanConnect() { return wait(function (Discord $discord, $resolve) { $discord->on('ready', function () use ($resolve) { $this->assertTrue(true); $resolve(); }); }); } public function testCanGetChannel() { return wait(function (Discord $discord, $resolve) { $channel = $discord->getChannel(getenv('TEST_CHANNEL')); $this->assertEquals(getenv('TEST_CHANNEL_NAME'), $channel->name); $resolve($channel); }); } }
Improve the get_nick a tiny amount
class IRCMessage: """ Class to store and parse an IRC Message. """ def __init__(self, msg): """ Parse a raw IRC message to IRCMessage. """ self.sender = None self.nick = None self.command = None self.params = [] self.__parse_msg(msg) def __parse_msg(self, msg): if msg[0] == ':': self.sender, msg = msg[1:].split(' ', 1) self.nick = get_nick(self.sender) if ' :' in msg: msg, trailing = msg.split(' :', 1) self.params = msg.split(' ') self.params.append(trailing) else: self.params = msg.split(' ') self.command = self.params.pop(0) def __repr__(self): """ Print the IRCMessage all nice 'n' pretty. """ return "Sender: {};\nCommand: {};\nParams: {};\n".format( self.sender, self.command, self.params) def action(message): """ Make the message an action. """ return '\u0001ACTION {}\u0001'.format(message) def get_nick(host): """ Get the user's nick from a host. """ return host.split('!', 1)[0]
class IRCMessage: """ Class to store and parse an IRC Message. """ def __init__(self, msg): """ Parse a raw IRC message to IRCMessage. """ self.sender = None self.nick = None self.command = None self.params = [] self.__parse_msg(msg) def __parse_msg(self, msg): if msg[0] == ':': self.sender, msg = msg[1:].split(' ', 1) self.nick = get_nick(self.sender) if ' :' in msg: msg, trailing = msg.split(' :', 1) self.params = msg.split(' ') self.params.append(trailing) else: self.params = msg.split(' ') self.command = self.params.pop(0) def __repr__(self): """ Print the IRCMessage all nice 'n' pretty. """ return "Sender: {};\nCommand: {};\nParams: {};\n".format( self.sender, self.command, self.params) def action(message): """ Make the message an action. """ return '\u0001ACTION {}\u0001'.format(message) def get_nick(host): """ Get the user's nick from a host. """ return host.split('!')[0]
Switch experiment to using Facebook with HTTPS
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 3, timeout: 0 }); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'http://facebook.com/?breach-test', amount: 3, timeout: 0 }); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
[infrastructure] Allow all valid semvers as commit messages
const fs = require('fs') const path = require('path') const chalk = require('chalk') const boxen = require('boxen') const semver = require('semver') const commitMsgPath = path.join(__dirname, '..', process.env.GIT_PARAMS) const msg = fs.readFileSync(commitMsgPath, 'utf8').trim() const template = /^\[[a-z-\/]+]\s[A-Z0-9]\w+/ if (!template.test(msg) && !semver.valid(msg)) { console.error(boxen([ chalk.yellow('No, your commit message should look like this:'), chalk.green('[package] Description of the change'), '', 'Example:', chalk.green('[desk-tool] Improve performance of list rendering') ].join('\n'), {padding: 1, margin: 1, borderStyle: 'double', borderColor: 'red'})) process.exit(1) }
const fs = require('fs') const path = require('path') const chalk = require('chalk') const boxen = require('boxen') const childProc = require('child_process') const commitMsgPath = path.join(__dirname, '..', process.env.GIT_PARAMS) const msg = fs.readFileSync(commitMsgPath, 'utf8').trim() const template = /^\[[a-z-\/]+]\s[A-Z0-9]\w+/ const versionTemplate = /^v\d+\.\d+.\d+(-[a-z0-9-]+)?$/ if (!template.test(msg) && !versionTemplate.test(msg)) { console.error(boxen([ chalk.yellow('No, your commit message should look like this:'), chalk.green('[package] Description of the change'), '', 'Example:', chalk.green('[desk-tool] Improve performance of list rendering') ].join('\n'), {padding: 1, margin: 1, borderStyle: 'double', borderColor: 'red'})) process.exit(1) }
Convert 'Go Back' from clickable span to button
import React, {PropTypes} from 'react'; import {browserHistory} from 'react-router'; import {HOME_PAGE_URI} from '../../utils/constants'; class Footer extends React.Component { constructor(props, context) { super(props, context); this.redirectToPreviousPage = this.redirectToPreviousPage.bind(this); } redirectToPreviousPage(){ browserHistory.goBack(); } render() { let isHomepage = false; if(this.context.location.pathname === HOME_PAGE_URI){ isHomepage = true; } return ( <div className="footer"> {isHomepage === true ? "" : <button type="button" className="btn btn-link" onClick={this.redirectToPreviousPage}>Go Back</button> } </div> ); } } Footer.contextTypes = { location: PropTypes.object }; export default Footer;
import React, {PropTypes} from 'react'; import {browserHistory} from 'react-router'; import {HOME_PAGE_URI} from '../../utils/constants'; class Footer extends React.Component { constructor(props, context) { super(props, context); this.redirectToPreviousPage = this.redirectToPreviousPage.bind(this); } redirectToPreviousPage(){ browserHistory.goBack(); } render() { let isHomepage = false; if(this.context.location.pathname === HOME_PAGE_URI){ isHomepage = true; } return ( <div className="footer"> {isHomepage === true ? "" : <span className="btn btn-link" onClick={this.redirectToPreviousPage}>Go Back</span> } </div> ); } } Footer.contextTypes = { location: PropTypes.object }; export default Footer;
Use product_id stored in order item instead of getting it from product instance.
<?php class SPM_ShopyMind_DataMapper_OrderItem { public function format(Mage_Sales_Model_Order_Item $orderItem) { $product = $orderItem->getProduct(); $combinationId = $this->getCombinationId($orderItem, $product); return array( 'id_product' => $orderItem->getProductId(), 'id_combination' => $combinationId, 'id_manufacturer' => Mage::helper('shopymind')->manufacturerIdOf($product), 'price' => $orderItem->getPriceInclTax(), 'qty' => $orderItem->getQtyOrdered() ); } private function getCombinationId(Mage_Sales_Model_Order_Item $orderItem) { $Product = Mage::getModel('catalog/product'); $combinationId = $orderItem->getHasChildren() ? $Product->getIdBySku($orderItem->getSku()) : $orderItem->getProductId(); return $combinationId; } }
<?php class SPM_ShopyMind_DataMapper_OrderItem { public function format(Mage_Sales_Model_Order_Item $orderItem) { $product = $orderItem->getProduct(); $combinationId = $this->getCombinationId($orderItem, $product); return array( 'id_product' => $product->getId(), 'id_combination' => $combinationId, 'id_manufacturer' => Mage::helper('shopymind')->manufacturerIdOf($product), 'price' => $orderItem->getPriceInclTax(), 'qty' => $orderItem->getQtyOrdered() ); } private function getCombinationId(Mage_Sales_Model_Order_Item $orderItem) { $Product = Mage::getModel('catalog/product'); $combinationId = $orderItem->getHasChildren() ? $Product->getIdBySku($orderItem->getSku()) : $orderItem->getProductId(); return $combinationId; } }
Use project-routes module to get route for projects.
var mount = require('koa-mount'); var router = require('koa-router')(); var koa = require('koa'); var Bus = require('busmq'); var app = koa(); require('koa-qs')(app); var ropts = { db: 'materialscommons', port: 30815 }; var r = require('rethinkdbdash')(ropts); var projectsModel = require('./model/db/projects')(r); var projects = require('./resources/projects-routes')(projectsModel); var bus = Bus.create({redis: ['redis://localhost:6379']}); var q; bus.on('online', function() { q = bus.queue('samples'); q.attach(); }); function* samples(next) { yield next; this.body = {samples:['a', 'b']}; } var router2 = require('koa-router')(); router2.get('/samples', samples); var usersModel = require('./model/db/users')(r); var keycache = require('./apikey-cache')(usersModel); var apikey = require('./apikey'); app.use(apikey(keycache)); app.use(mount('/', projects.routes())).use(projects.allowedMethods()); app.use(mount('/', router2.routes())); app.listen(3000);
var mount = require('koa-mount'); var router = require('koa-router')(); var koa = require('koa'); var Bus = require('busmq'); var app = koa(); require('koa-qs')(app); var ropts = { db: 'materialscommons', port: 30815 }; var r = require('rethinkdbdash')(ropts); var projectsModel = require('./model/db/projects')(r); var projects = require('./resources/projects')(projectsModel); var bus = Bus.create({redis: ['redis://localhost:6379']}); var q; bus.on('online', function() { q = bus.queue('samples'); q.attach(); }); function* samples(next) { yield next; this.body = {samples:['a', 'b']}; } var router2 = require('koa-router')(); router2.get('/samples', samples); var usersModel = require('./model/db/users')(r); var keycache = require('./apikey-cache')(usersModel); var apikey = require('./apikey'); app.use(apikey(keycache)); app.use(mount('/', projects.routes())).use(projects.allowedMethods()); app.use(mount('/', router2.routes())); app.listen(3000);
scripts: Move JSON dump parameters to a global dictionary.
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" import json import os json_dump_params = { 'ensure_ascii': False, 'indent': '\t', 'separators': (',', ': '), 'sort_keys': True } # Default parameters for JSON input and output def json_load(fn): with open(fn, 'r', encoding='utf-8') as file: return json.load(file) def json_store(fn, obj, dirs=['']): """Saves the JSON object [obj] to [fn], creating all necessary directories in the process. If [dirs] is given, the function is executed for every root directory in the array.""" for i in dirs: full_fn = os.path.join(i, fn) os.makedirs(os.path.dirname(full_fn), exist_ok=True) with open(full_fn, 'w', encoding='utf-8') as file: json.dump(obj, file, **json_dump_params) file.write('\n')
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" import json import os # Default parameters for JSON input and output def json_load(fn): with open(fn, 'r', encoding='utf-8') as file: return json.load(file) def json_store(fn, obj, dirs=['']): """Saves the JSON object [obj] to [fn], creating all necessary directories in the process. If [dirs] is given, the function is executed for every root directory in the array.""" for i in dirs: full_fn = os.path.join(i, fn) os.makedirs(os.path.dirname(full_fn), exist_ok=True) with open(full_fn, 'w', encoding='utf-8') as file: json.dump( obj, file, ensure_ascii=False, sort_keys=True, indent='\t', separators=(',', ': ') ) file.write('\n')
GBE-113: Add support for mixed geometry type (GEOMETRY_COLLECTION)
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.layer; import org.geomajas.global.Api; import java.io.Serializable; /** * <p> * Listing of all types of vector layers. * </p> * * @author Pieter De Graef * @since 1.6.0 */ @Api(allMethods = true) public enum LayerType implements Serializable { RASTER(1), POINT(2), LINESTRING(3), POLYGON(4), MULTIPOINT(5), MULTILINESTRING(6), MULTIPOLYGON(7), GEOMETRY_COLLECTION(8); private int code; /** * Create layer type. * * @param code code to apply */ private LayerType(int code) { this.code = code; } /** * Convert to string. * * @return string representation of layer type */ public String toString() { return Integer.toString(code); } }
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.layer; import org.geomajas.global.Api; import java.io.Serializable; /** * <p> * Listing of all types of vector layers. * </p> * * @author Pieter De Graef * @since 1.6.0 */ @Api(allMethods = true) public enum LayerType implements Serializable { RASTER(1), POINT(2), LINESTRING(3), POLYGON(4), MULTIPOINT(5), MULTILINESTRING(6), MULTIPOLYGON(7); private int code; /** * Create layer type. * * @param code code to apply */ private LayerType(int code) { this.code = code; } /** * Convert to string. * * @return string representation of layer type */ public String toString() { return Integer.toString(code); } }