text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add missing Vue.use in test
import Vue from 'vue'; import Vuex from 'vuex'; import component from '~/reports/components/modal_open_name.vue'; import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper'; Vue.use(Vuex); describe('Modal open name', () => { const Component = Vue.extend(component); let vm; const store = new Vuex.Store({ actions: { openModal: () => {}, }, state: {}, mutations: {}, }); beforeEach(() => { vm = mountComponentWithStore(Component, { store, props: { issue: { title: 'Issue', }, status: 'failed', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders the issue name', () => { expect(vm.$el.textContent.trim()).toEqual('Issue'); }); it('calls openModal actions when button is clicked', () => { spyOn(vm, 'openModal'); vm.$el.click(); expect(vm.openModal).toHaveBeenCalled(); }); });
import Vue from 'vue'; import Vuex from 'vuex'; import component from '~/reports/components/modal_open_name.vue'; import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper'; describe('Modal open name', () => { const Component = Vue.extend(component); let vm; const store = new Vuex.Store({ actions: { openModal: () => {}, }, state: {}, mutations: {}, }); beforeEach(() => { vm = mountComponentWithStore(Component, { store, props: { issue: { title: 'Issue', }, status: 'failed', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders the issue name', () => { expect(vm.$el.textContent.trim()).toEqual('Issue'); }); it('calls openModal actions when button is clicked', () => { spyOn(vm, 'openModal'); vm.$el.click(); expect(vm.openModal).toHaveBeenCalled(); }); });
Add JSON decoder to Request
// Copyright 2016 Marcel Gotsch. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package goserv import ( "encoding/json" "net/http" ) // A Request represents an HTTP request received by the Server. // // It embeds the native http.Request, thus all native fields are still available // through Request. Every Request has it's own Context providing a key-value store to share // data between multiple Handlers. In case that the Route handling the Request has parameters, the parameter // values are extracted from the Request's path and stored in .Params. type Request struct { // Embedded http.Request. *http.Request // Request specific key-value store to share data between Handlers Context *Context // Key-value store containing named parameter values extracted from // the Request's path. See Route. Params Params // Sanitized http.Request.URL.Path SanitizedPath string } // JSON parses the request's body using the encoding/json Decoder. In case // of a decoding error the error is returned. // // Note: The request's body is closed after calling this method. func (r *Request) JSON(v interface{}) error { err := json.NewDecoder(r.Body).Decode(v) r.Body.Close() if err != nil { return err } return nil } func newRequest(r *http.Request) *Request { return &Request{r, newContext(), make(Params), SanitizePath(r.URL.Path)} }
// Copyright 2016 Marcel Gotsch. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package goserv import ( "net/http" ) // A Request represents an HTTP request received by the Server. // // It embeds the native http.Request, thus all native fields are still available // through Request. Every Request has it's own Context providing a key-value store to share // data between multiple Handlers. In case that the Route handling the Request has parameters, the parameter // values are extracted from the Request's path and stored in .Params. type Request struct { // Embedded http.Request. *http.Request // Request specific key-value store to share data between Handlers Context *Context // Key-value store containing named parameter values extracted from // the Request's path. See Route. Params Params // Sanitized http.Request.URL.Path SanitizedPath string } func newRequest(r *http.Request) *Request { return &Request{r, newContext(), make(Params), SanitizePath(r.URL.Path)} }
Fix error handling and pass store onmessage and onclose
export default (init, { prepareAction = action => JSON.stringify({ action }), isWSAT = action => action.wsat !== false, getAction = ({ data }) => { const { action } = JSON.parse(data); return action && Object.assign({ wsat: false }, action); }, } = {}) => { let socket = init(); const { onclose, onmessage } = socket; const ws = (store) => { socket.onmessage = (message) => { const action = getAction(message); action && store.dispatch(action); onmessage && onmessage({ store, message }); }; socket.onclose = () => { socket = Object.assign(init(), { onmessage: socket.onmessage, onclose: socket.onclose, }); onclose && onclose({ store }); }; return next => action => (socket.readyState === 1 && isWSAT(action) ? socket.send(prepareAction(action)) : next(action) ); }; return new Promise((resolve, reject) => { socket.onopen = () => { resolve({ ws, socket }); }; socket.onerror = (error) => { reject({ error, ws, socket }); }; }); };
export default (init, { prepareAction = action => JSON.stringify({ action }), isWSAT = action => action.wsat !== false, getAction = ({ data }) => { const { action } = JSON.parse(data); return action && Object.assign({ wsat: false }, action); }, } = {}) => { let socket = init(); const { onclose, onopen, onmessage } = socket; const ws = (store) => { socket.onmessage = (message) => { const action = getAction(message); action && store.dispatch(action); onmessage && onmessage(message); }; return next => action => (isWSAT(action) ? socket.send(prepareAction(action)) : next(action) ); }; socket.onclose = () => { socket = Object.assign(init(), { onmessage: socket.onmessage, onclose: socket.onclose, }); onclose && onclose(); }; return new Promise((resolve) => { socket.onopen = () => { onopen(); resolve({ ws, socket }); }; }); };
Add program name to parser
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') def _execute(self): project_folder = utils.project_folder() self._logger.info(project_folder) working_folder = utils.working_folder('uog01', self.args.environment) self._logger.info(working_folder) project = utils.project() self._logger.info(project) self._logger.info(utils.is_git_repository())
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') def _execute(self): project_folder = utils.project_folder() self._logger.info(project_folder) working_folder = utils.working_folder('uog01', self.args.environment) self._logger.info(working_folder) project = utils.project() self._logger.info(project) self._logger.info(utils.is_git_repository())
Make tests match actual expected format for user-locators EchoAttributeManager::getUserCallable casts to array, which means that even a non-array value (e.g. a simple callback) becomes an array and NotificationController::evaluateUserCallable will handle it just fine. But tests seemed to thing it was wrong. Change-Id: Ia1e1e4015ebbc4d79bba5274e802911f222692c0
<?php class NotificationStructureTest extends MediaWikiTestCase { /** * @coversNothing * @dataProvider provideNotificationTypes * * @param string $type * @param array $info */ public function testNotificationTypes( $type, array $info ) { if ( isset( $info['presentation-model'] ) ) { self::assertTrue( class_exists( $info['presentation-model'] ), "Presentation model class {$info['presentation-model']} for {$type} must exist" ); } if ( isset( $info['user-locators'] ) ) { $locators = (array)$info['user-locators']; $callable = reset( $locators ); if ( is_array( $callable ) ) { $callable = reset( $callable ); } self::assertTrue( is_callable( $callable ), 'User locator ' . print_r( $callable, true ) . " for {$type} must be callable" ); } } public function provideNotificationTypes() { global $wgEchoNotifications; $result = []; foreach ( $wgEchoNotifications as $type => $info ) { $result[] = [ $type, $info ]; } return $result; } }
<?php class NotificationStructureTest extends MediaWikiTestCase { /** * @coversNothing * @dataProvider provideNotificationTypes * * @param string $type * @param array $info */ public function testNotificationTypes( $type, array $info ) { if ( isset( $info['presentation-model'] ) ) { self::assertTrue( class_exists( $info['presentation-model'] ), "Presentation model class {$info['presentation-model']} for {$type} must exist" ); } if ( isset( $info['user-locators'] ) ) { $locators = $info['user-locators']; $locator = reset( $locators ); if ( is_array( $locator ) ) { $locator = reset( $locator ); } self::assertTrue( is_callable( $locator ), 'User locator ' . print_r( $locator, true ) . " for {$type} must be callable" ); } } public function provideNotificationTypes() { global $wgEchoNotifications; $result = []; foreach ( $wgEchoNotifications as $type => $info ) { $result[] = [ $type, $info ]; } return $result; } }
Remove extra check of symlinks.
import os import io import json from aiohttp import web class Handler: def __init__(self, *, loop): self.loop = loop self.files = {} def lookup_files(self, path): for obj in os.listdir(path): _path = os.path.join(path, obj) if os.path.isfile(_path): name, _ = os.path.splitext(obj) with io.open(_path, mode='rt', encoding='utf-8') as fp: self.files[name] = json.dumps(json.load(fp)).encode('utf-8') # noqa def browsers(self, request): version = request.match_info['version'] if version not in self.files: raise web.HTTPNotFound( text='No data was found for version {version}'.format( version=version, ), ) return web.json_response(body=self.files[version])
import os import io import json from aiohttp import web class Handler: def __init__(self, *, loop): self.loop = loop self.files = {} def lookup_files(self, path): for obj in os.listdir(path): _path = os.path.join(path, obj) if os.path.isfile(_path) or os.path.islink(_path): name, _ = os.path.splitext(obj) with io.open(_path, mode='rt', encoding='utf-8') as fp: self.files[name] = json.dumps(json.load(fp)).encode('utf-8') # noqa def browsers(self, request): version = request.match_info['version'] if version not in self.files: raise web.HTTPNotFound( text='No data was found for version {version}'.format( version=version, ), ) return web.json_response(body=self.files[version])
Fix missing import in contrib script added in [2630]. git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@2631 af82e41b-90c4-0310-8c96-b1721e28e2e2
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more meaningful new defaults. # # Make sure to make a backup of the Trac environment before running this! import os import sys from trac.env import open_environment from trac.ticket.model import Priority, Severity priority_mapping = { 'highest': 'blocker', 'high': 'critical', 'normal': 'major', 'low': 'minor', 'lowest': 'trivial' } def main(): if len(sys.argv) < 2: print >> sys.stderr, 'usage: %s /path/to/projenv' \ % os.path.basename(sys.argv[0]) sys.exit(2) env = open_environment(sys.argv[1]) db = env.get_db_cnx() for oldprio, newprio in priority_mapping.items(): priority = Priority(env, oldprio, db) priority.name = newprio priority.update(db) for severity in list(Severity.select(env, db)): severity.delete(db) db.commit() if __name__ == '__main__': main()
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more meaningful new defaults. # # Make sure to make a backup of the Trac environment before running this! import sys from trac.env import open_environment from trac.ticket.model import Priority, Severity priority_mapping = { 'highest': 'blocker', 'high': 'critical', 'normal': 'major', 'low': 'minor', 'lowest': 'trivial' } def main(): if len(sys.argv) < 2: print >> sys.stderr, 'usage: %s /path/to/projenv' \ % os.path.basename(sys.argv[0]) sys.exit(2) env = open_environment(sys.argv[1]) db = env.get_db_cnx() for oldprio, newprio in priority_mapping.items(): priority = Priority(env, oldprio, db) priority.name = newprio priority.update(db) for severity in list(Severity.select(env, db)): severity.delete(db) db.commit() if __name__ == '__main__': main()
Change let to const in "Extract EXIF"
import * as ExifParser from "exif-parser"; import Utils from "../Utils.js"; /** * Image operations. * * @author tlwr [toby@toby.codes] * @copyright Crown Copyright 2017 * @license Apache-2.0 * * @namespace */ const Image = { runEXIF(input, args) { try { const bytes = Uint8Array.from(input); const parser = ExifParser.create(bytes.buffer); const result = parser.parse(); let lines = []; for (let tagName in result.tags) { let value = result.tags[tagName]; lines.push(`${tagName}: ${value}`); } const numTags = lines.length; lines.unshift(`Found ${numTags} tags.\n`); return lines.join("\n"); } catch (err) { throw "Could not extract EXIF data from image: " + err; } }, }; export default Image;
import * as ExifParser from "exif-parser"; import Utils from "../Utils.js"; /** * Image operations. * * @author tlwr [toby@toby.codes] * @copyright Crown Copyright 2017 * @license Apache-2.0 * * @namespace */ const Image = { runEXIF(input, args) { try { let bytes = Uint8Array.from(input); let parser = ExifParser.create(bytes.buffer); let result = parser.parse(); let lines = []; for (let tagName in result.tags) { let value = result.tags[tagName]; lines.push(`${tagName}: ${value}`); } let numTags = lines.length; lines.unshift(`Found ${numTags} tags.\n`); return lines.join("\n"); } catch (err) { throw "Could not extract EXIF data from image: " + err; } }, }; export default Image;
[server] Throw error if basePath or staticPath is missing
import path from 'path' import get from 'lodash/get' import merge from 'lodash/merge' const applyStaticLoaderFix = (wpConfig, sanityConfig) => { // We need to fix the public path, prefixing the server URL for assets such as // images to work in development mode (related to blob's generated by style-loader) const {httpHost, httpPort, staticPath, basePath} = sanityConfig if (!staticPath || !basePath) { throw new Error('`staticPath` and `basePath` must be specified in order for the static loader fix to work') } return get(wpConfig, 'module.loaders', []).map(loader => { if (typeof loader.loader !== 'string' || !loader.loader.includes('file-loader')) { return loader } const staticDir = path.relative(basePath, staticPath) const rootPath = staticDir.replace(/^\.*\/|\/+$/g, '') return merge({}, loader, { query: { publicPath: `http://${httpHost}:${httpPort}/${rootPath}/` } }) }) } export default applyStaticLoaderFix
import path from 'path' import get from 'lodash/get' import merge from 'lodash/merge' const applyStaticLoaderFix = (wpConfig, sanityConfig) => { // We need to fix the public path, prefixing the server URL for assets such as // images to work in development mode (related to blob's generated by style-loader) const {httpHost, httpPort, staticPath, basePath} = sanityConfig return get(wpConfig, 'module.loaders', []).map(loader => { if (typeof loader.loader !== 'string' || !loader.loader.includes('file-loader')) { return loader } const staticDir = path.relative(basePath, staticPath) const rootPath = staticDir.replace(/^\.*\/|\/+$/g, '') return merge({}, loader, { query: { publicPath: `http://${httpHost}:${httpPort}/${rootPath}/` } }) }) } export default applyStaticLoaderFix
Java: Add stream example methods using wildcards.
package p; import java.util.function.*; import java.util.Iterator; import java.util.stream.Collector; public class Stream<T> { public Iterator<T> iterator() { return null; } public boolean allMatch(Predicate<? super T> predicate) { throw null; } public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { throw null; } // Collector is not a functional interface, so this is not supported // public <R, A> R collect(Collector<? super T, A, R> collector) { // throw null; // } // public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> // b) { // throw null; // } public Stream<T> distinct() { throw null; } }
package p; import java.util.function.*; import java.util.Iterator; import java.util.stream.Collector; public class Stream<T> { public Iterator<T> iterator() { return null; } // public boolean allMatch(Predicate<? super T> predicate) { // throw null; // } // public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> // accumulator, BiConsumer<R, R> combiner) { // throw null; // } // public <R, A> R collect(Collector<? super T, A, R> collector) { // throw null; // } // public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> // b) { // throw null; // } public Stream<T> distinct() { throw null; } }
Exit process if promise succeeds
#!/usr/bin/env node const colors = require('colors') const git = require('nodegit') const exists = require('../lib/etc').isSite if (!exists()) { console.error('No site in here!'.red) process.exit(1) } const branch = new Promise(function (resolve, reject) { git.Repository.open(process.cwd()).then(function (repo) { git.Branch.lookup(repo, 'gh-pages', 1).then(function (reference) { resolve(repo, reference) }).catch(function (reason) { reject(reason.toString()) }) }).catch(function (reason) { const stringErr = reason.toString() if (stringErr.includes('Could not find')) { reject('This site isn\'t a repository!') } else { reject(stringErr) } }) }) branch.then(function (repo, branch) { console.log('Yeah, branch exists!') process.exit(1) }) branch.catch(function (reason) { console.error(reason) process.exit(1) })
#!/usr/bin/env node const colors = require('colors') const git = require('nodegit') const exists = require('../lib/etc').isSite if (!exists()) { console.error('No site in here!'.red) process.exit(1) } const branch = new Promise(function (resolve, reject) { git.Repository.open(process.cwd()).then(function (repo) { git.Branch.lookup(repo, 'gh-pages', 2).then(function (reference) { resolve(repo, reference) }).catch(function (reason) { reject(reason.toString()) }) }).catch(function (reason) { const stringErr = reason.toString() if (stringErr.includes('Could not find')) { reject('This site isn\'t a repository!') } else { reject(stringErr) } }) }) branch.then(function (repo, branch) { console.log('Yeah, branch exists!') }) branch.catch(function (reason) { console.error(reason) process.exit(1) })
Use non-empty value for sha
'use strict'; const fs = require('fs'); const path = require('path'); module.exports = function generate(overrides) { const branchPath = path.join(__dirname, 'branch'); const branchContent = fs.readFileSync(branchPath, 'utf8').trim(); const branch = branchContent.match(/BRANCH=(.*)/)[1]; const buildtime = Date.now(); const semver = require('./package.json').version; const version = Object.assign({ branch, buildtime, official: false, semver, sha: 'HEAD', }, overrides); let string = version.branch + ' ' + version.semver; if (version.sha) { string += ' ' + version.sha.slice(0, 7); } string += ' ' + new Date(version.buildtime).toISOString(); if (!version.official) { string += ' (unofficial)'; } version.string = string; return Object.freeze(version); };
'use strict'; const fs = require('fs'); const path = require('path'); module.exports = function generate(overrides) { const branchPath = path.join(__dirname, 'branch'); const branchContent = fs.readFileSync(branchPath, 'utf8').trim(); const branch = branchContent.match(/BRANCH=(.*)/)[1]; const buildtime = Date.now(); const semver = require('./package.json').version; const version = Object.assign({ branch, buildtime, official: false, semver, sha: '', }, overrides); let string = version.branch + ' ' + version.semver; if (version.sha) { string += ' ' + version.sha.slice(0, 7); } string += ' ' + new Date(version.buildtime).toISOString(); if (!version.official) { string += ' (unofficial)'; } version.string = string; return Object.freeze(version); };
Support udp scheme in raven.load
""" raven.conf ~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import urlparse def load(dsn, scope): """ Parses a Sentry compatible DSN and loads it into the given scope. >>> import raven >>> dsn = 'https://public_key:secret_key@sentry.local/project_id' >>> raven.load(dsn, locals()) """ url = urlparse.urlparse(dsn) if url.scheme not in ('http', 'https', 'udp'): raise ValueError('Unsupported Sentry DSN scheme: %r' % url.scheme) netloc = url.hostname if url.port and url.port != 80: netloc += ':%s' % url.port path_bits = url.path.rsplit('/', 1) if len(path_bits) > 1: path = path_bits[0] else: path = '' project = path_bits[-1] scope.update({ 'SENTRY_SERVERS': ['%s://%s%s/api/store/' % (url.scheme, netloc, path)], 'SENTRY_PROJECT': project, 'SENTRY_PUBLIC_KEY': url.username, 'SENTRY_SECRET_KEY': url.password, })
""" raven.conf ~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import urlparse def load(dsn, scope): """ Parses a Sentry compatible DSN and loads it into the given scope. >>> import raven >>> dsn = 'https://public_key:secret_key@sentry.local/project_id' >>> raven.load(dsn, locals()) """ url = urlparse.urlparse(dsn) if url.scheme not in ('http', 'https'): raise ValueError('Unsupported Sentry DSN scheme: %r' % url.scheme) netloc = url.hostname if url.port and url.port != 80: netloc += ':%s' % url.port path_bits = url.path.rsplit('/', 1) if len(path_bits) > 1: path = path_bits[0] else: path = '' project = path_bits[-1] scope.update({ 'SENTRY_SERVERS': ['%s://%s%s/api/store/' % (url.scheme, netloc, path)], 'SENTRY_PROJECT': project, 'SENTRY_PUBLIC_KEY': url.username, 'SENTRY_SECRET_KEY': url.password, })
Fix config_drive migration, per Matt Dietz.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # 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. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # 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. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
Update password functions for Django 1.8
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^login/$', 'django.contrib.auth.views.login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'), url(r'^changepassword/$', 'django.contrib.auth.views.password_change', name='password_change'), url(r'^changepassword/done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'), url(r'^', include('server.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), (r'^api/', include('api.urls')) #url(r'^$', 'namer.views.index', name='home'), ) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if 'config' in settings.INSTALLED_APPS: config_pattern = patterns('', url(r'^config/', include('config.urls')) ) urlpatterns += config_pattern
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^login/$', 'django.contrib.auth.views.login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'), url(r'^changepassword/$', 'django.contrib.auth.views.password_change'), url(r'^changepassword/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^', include('server.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), (r'^api/', include('api.urls')) #url(r'^$', 'namer.views.index', name='home'), ) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if 'config' in settings.INSTALLED_APPS: config_pattern = patterns('', url(r'^config/', include('config.urls')) ) urlpatterns += config_pattern
Use absolute import for python3
# -*- coding: utf-8 -*- """ cli.py === User-facing command-line functions for :module:`fto`. """ import string from fto.fto import print_exercise, MassUnit def process_input(units='lbs'): """Guide user through weight calculations via CLI prompts.""" name = input("Please enter the exercise name: ")\ .strip(string.whitespace) kgs = input("Kilograms? y or n: ").strip(string.whitespace) weight = int(input("Enter last week's max weight: ")) week = int(input("Enter current training week: ")) if week == 1: increment = int(input("How much are we adding? ")) else: increment = 0 units = MassUnit.kgs if kgs == 'y' else MassUnit.lbs print_exercise(name, weight, week, units, increment) if __name__ == '__main__': process_input()
# -*- coding: utf-8 -*- """ cli.py === User-facing command-line functions for :module:`fto`. """ import string from .fto import print_exercise, MassUnit def process_input(units='lbs'): """Guide user through weight calculations via CLI prompts.""" name = input("Please enter the exercise name: ")\ .strip(string.whitespace) kgs = input("Kilograms? y or n: ").strip(string.whitespace) weight = int(input("Enter last week's max weight: ")) week = int(input("Enter current training week: ")) if week == 1: increment = int(input("How much are we adding? ")) else: increment = 0 units = MassUnit.kgs if kgs == 'y' else MassUnit.lbs print_exercise(name, weight, week, units, increment) if __name__ == '__main__': process_input()
Add console scripts for both examples Now they are callable from console via $ demandlib_power_example and $ demandlib_heat_example when installed bia pip3.
#! /usr/bin/env python """TODO: Maybe add a docstring containing a long description This would double as something we could put int the `long_description` parameter for `setup` and it would squelch some complaints pylint has on `setup.py`. """ from setuptools import setup import os setup(name='demandlib', version='0.1.0rc1', author='oemof developing group', url='http://github.com/oemof/demandlib', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', packages=['demandlib', 'examples'], package_data = { 'demandlib': [os.path.join('bdew_data', '*.csv')], 'examples': ['*.csv']}, install_requires=['numpy >= 1.7.0', 'pandas >= 0.18.0'], entry_points={ 'console_scripts': [ 'demandlib_heat_example = examples.heat_demand_example:heat_example', 'demandlib_power_example = examples.power_demand_example:power_example',]} )
#! /usr/bin/env python """TODO: Maybe add a docstring containing a long description This would double as something we could put int the `long_description` parameter for `setup` and it would squelch some complaints pylint has on `setup.py`. """ from setuptools import setup import os setup(name='demandlib', version='0.1.0rc1', author='oemof developing group', url='http://github.com/oemof/demandlib', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', packages=['demandlib', 'examples'], package_data = { 'demandlib': [os.path.join('bdew_data', '*.csv')], 'examples': ['*.csv']}, install_requires=['numpy >= 1.7.0', 'pandas >= 0.18.0'] )
Allow transformResultsToCollection to fallback to other props
const { find } = require('lodash') const { transformInvestmentProjectToListItem } = require('../investment-projects/transformers') const { transformContactToListItem } = require('../contacts/transformers') const { buildPagination } = require('../../lib/pagination') const { buildSearchAggregation } = require('./builders') const { entities } = require('./services') function transformResultsToCollection (results, searchEntity, options = {}) { const resultsItems = results[`${searchEntity}s`] || results.items || results.results if (!resultsItems) { return null } const entity = find(entities, ['entity', searchEntity]) let items = resultsItems.map(item => Object.assign({}, item, { type: searchEntity })) if (searchEntity === 'investment_project') { items = items.map(transformInvestmentProjectToListItem) } if (searchEntity === 'contact') { items = items.map(transformContactToListItem) } return Object.assign({}, { items, count: results.count, countLabel: entity.noun, highlightTerm: options.searchTerm, pagination: buildPagination(options.query, results), aggregations: buildSearchAggregation(results.aggregations), }) } module.exports = { transformResultsToCollection, }
const { find } = require('lodash') const { transformInvestmentProjectToListItem } = require('../investment-projects/transformers') const { transformContactToListItem } = require('../contacts/transformers') const { buildPagination } = require('../../lib/pagination') const { buildSearchAggregation } = require('./builders') const { entities } = require('./services') function transformResultsToCollection (results, searchEntity, options = {}) { const resultsData = results[`${searchEntity}s`] if (!resultsData) { return null } const entity = find(entities, ['entity', searchEntity]) let items = resultsData.map(item => Object.assign({}, item, { type: searchEntity })) if (searchEntity === 'investment_project') { items = items.map(transformInvestmentProjectToListItem) } if (searchEntity === 'contact') { items = items.map(transformContactToListItem) } return Object.assign({}, { items, count: results.count, countLabel: entity.noun, highlightTerm: options.searchTerm, pagination: buildPagination(options.query, results), aggregations: buildSearchAggregation(results.aggregations), }) } module.exports = { transformResultsToCollection, }
Fix phpdocs; Remove unused import
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Http\Controllers; /** * This is the tax office name trait. * * @author Fábio Santos <ffsantos92@gmail.com> */ trait TaxOfficeNameTrait { /** * Get the tax office name. * * @param \Illuminate\Database\Eloquent\Collection $office * * @return string */ public static function getTaxOfficeName($office) { $name = $office->code.' - '; $name .= $office->municipality->name; if ($office->number) { $name .= ' ('.$office->number.')'; } return $name; } }
<?php /* * This file is part of Bens Penhorados, an undergraduate capstone project. * * (c) Fábio Santos <ffsantos92@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Http\Controllers; use App\Models\Attributes\Generic\Municipality; /** * This is the tax office name trait. * * @author Fábio Santos <ffsantos92@gmail.com> */ trait TaxOfficeNameTrait { /** * Get the tax office name. * * @param \Illuminate\Database\Eloquent\Collection $generic * * @return string */ public static function getTaxOfficeName($office) { $name = $office->code.' - '; $name .= $office->municipality->name; if ($office->number) { $name .= ' ('.$office->number.')'; } return $name; } }
Fix gulp cannot build all files
var gulp = require('gulp'), concat = require('gulp-concat'); jshint = require('gulp-jshint'); uglify = require('gulp-uglify'); rename = require('gulp-rename'); amdOptimize = require("amd-optimize"); watch = require('gulp-watch'); gulp.task('lint', function () { gulp.src('./src/js/**/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('rjs', function () { gulp.src([ './src/intro.js', './src/core.js', './src/**/*.js', './src/outro.js' ]) .pipe(concat('faiash.js')) .pipe(gulp.dest('dist')) .pipe(rename('faiash.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('watch', function () { gulp.watch('./src/**.js', ['lint', 'rjs']); }); gulp.task('default', function() { gulp.start('lint', 'rjs'); });
var gulp = require('gulp'), concat = require('gulp-concat'); jshint = require('gulp-jshint'); uglify = require('gulp-uglify'); rename = require('gulp-rename'); amdOptimize = require("amd-optimize"); watch = require('gulp-watch'); gulp.task('lint', function () { gulp.src('./src/js/**/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('rjs', function () { gulp.src([ './src/intro.js', './src/core.js', './src/**.js', './src/outro.js' ]) .pipe(concat('faiash.js')) .pipe(gulp.dest('dist')) .pipe(rename('faiash.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', function () { gulp.run('lint', 'rjs'); }); }); gulp.task('default', function() { gulp.start('lint', 'rjs'); });
Add an extra check in that test
import pytest import allegedb @pytest.fixture(scope='function') def orm(): with allegedb.ORM("sqlite:///:memory:") as it: yield it def test_single_plan(orm): g = orm.new_graph('graph') g.add_node(0) orm.turn = 1 g.add_node(1) with orm.plan(): orm.turn = 2 g.add_node(2) assert orm.turn == 1 assert 2 not in g orm.branch = 'b' assert 2 not in g assert 1 in g orm.turn = 2 assert 2 in g orm.turn = 1 orm.branch = 'trunk' orm.turn = 0 assert 1 not in g orm.branch = 'c' orm.turn = 2 assert 1 not in g assert 2 not in g orm.turn = 0 orm.branch = 'trunk' orm.turn = 2 assert 2 in g
import pytest import allegedb @pytest.fixture(scope='function') def orm(): with allegedb.ORM("sqlite:///:memory:") as it: yield it def test_single_plan(orm): g = orm.new_graph('graph') g.add_node(0) orm.turn = 1 g.add_node(1) with orm.plan(): orm.turn = 2 g.add_node(2) assert orm.turn == 1 assert 2 not in g orm.branch = 'b' assert 2 not in g assert 1 in g orm.turn = 2 assert 2 in g orm.turn = 1 orm.branch = 'trunk' orm.turn = 0 assert 1 not in g orm.branch = 'c' orm.turn = 2 assert 1 not in g assert 2 not in g
Reduce threshold until optimization appears to 1s
/* eslint-env browser */ /* global i18n: false */ const OPTIMIZATION_MESSAGE_DISPLAY_THRESHOLD = 1000; // milliseconds // type Canceler = () => Eff Unit // // setMessage :: Unit -> Eff (dom :: DOM) Canceler const setMessage = () => { const message = document.querySelector('.app-loading-screen .message'); if (!message) { return () => {}; } message.innerText = i18n('loading'); const optimizingMessageTimeoutId = setTimeout(() => { const innerMessage = document.querySelector('.app-loading-screen .message'); if (!innerMessage) { return; } innerMessage.innerText = i18n('optimizingApplication'); }, OPTIMIZATION_MESSAGE_DISPLAY_THRESHOLD); return () => { clearTimeout(optimizingMessageTimeoutId); }; }; module.exports = { setMessage, };
/* eslint-env browser */ /* global i18n: false */ const OPTIMIZATION_MESSAGE_DISPLAY_THRESHOLD = 2000; // milliseconds // type Canceler = () => Eff Unit // // setMessage :: Unit -> Eff (dom :: DOM) Canceler const setMessage = () => { const message = document.querySelector('.app-loading-screen .message'); if (!message) { return () => {}; } message.innerText = i18n('loading'); const optimizingMessageTimeoutId = setTimeout(() => { const innerMessage = document.querySelector('.app-loading-screen .message'); if (!innerMessage) { return; } innerMessage.innerText = i18n('optimizingApplication'); }, OPTIMIZATION_MESSAGE_DISPLAY_THRESHOLD); return () => { clearTimeout(optimizingMessageTimeoutId); }; }; module.exports = { setMessage, };
Switch to nosetests framework for testing
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() tests_require = [ 'mock >= 1.0.1', 'nose >= 1.3.4', ] install_requires = [ 'xmltodict >= 0.9.0', 'requests >= 2.5.1', ] setup( name='pynessus-api', version='1.0dev', description='A Python interface to the Nessus API', long_description=long_description, url='https://github.com/sait-berkeley-infosec/pynessus-api', author='Arlan Jaska', author_email='ajaska@berkeley.edu', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, )
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() tests_require = [ 'mock >= 1.0.1', ] install_requires = [ 'xmltodict >= 0.9.0', 'requests >= 2.5.1', ] setup( name='pynessus-api', version='1.0dev', description='A Python interface to the Nessus API', long_description=long_description, url='https://github.com/sait-berkeley-infosec/pynessus-api', author='Arlan Jaska', author_email='ajaska@berkeley.edu', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, )
Add task for pushing code with rsync
#!/usr/bin/env python from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix from fabric.contrib.project import rsync_project env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task def push_code(): rsync_project(local_dir='.', remote_dir=home, exclude=('.git', '.vagrant'), extra_opts='--filter=":- .gitignore"') @task def update_dependencies(): with prefix('workon jarvis2'): run(('pip install --quiet --use-mirrors --upgrade' ' -r {home}/requirements.txt').format(home=home)) @task def restart_server(): sudo('/etc/init.d/uwsgi restart', pty=False) @task def restart_client(): run('pkill -x midori') @task(default=True) def deploy(update_deps=False): push_code() if update_deps: update_dependencies() restart_server() restart_client() @task def full_deploy(): deploy(True)
#!/usr/bin/env python from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task def update_dependencies(): with prefix('workon jarvis2'): run('pip install --use-mirrors -r %s/requirements.txt' % (home,)) @task def restart_server(): sudo('/etc/init.d/uwsgi restart', pty=False) @task def restart_client(): run('pkill -x midori') @task(default=True) def deploy(update_deps=False): pull_code() if update_deps: update_dependencies() restart_server() restart_client() @task def full_deploy(): deploy(True)
Add support to .jsx files.
'use strict' const webpack = require('webpack') const path = require('path') const configuration = { entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', path.resolve(__dirname, 'app') ], output: { path: path.resolve(__dirname, 'public'), filename: 'bundle.js' }, devServer: { contentBase: path.resolve(__dirname, 'public'), historyApiFallback: true }, module: { loaders: [ { test: /\.jsx?$/, loader: 'react-hot', include: path.join(__dirname, 'app') }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], devtool: 'source-map', cache: true } module.exports = configuration
'use strict' const webpack = require('webpack') const path = require('path') const configuration = { entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', path.resolve(__dirname, 'app') ], output: { path: path.resolve(__dirname, 'public'), filename: 'bundle.js' }, devServer: { contentBase: path.resolve(__dirname, 'public'), historyApiFallback: true }, module: { loaders: [ { test: /\.js$/, loader: 'react-hot', include: path.join(__dirname, 'app') }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], devtool: 'source-map', cache: true } module.exports = configuration
Fix <EditableBasicRow> isn't exported to bundle
import './styles/index.scss'; // Visual elements import BasicRow from './BasicRow'; import EditableBasicRow from './EditableBasicRow'; import Icon from './Icon'; import StatusIcon from './StatusIcon'; import Tag from './Tag'; import Text from './Text'; import EditableText from './EditableText'; import Tooltip from './Tooltip'; import AnchoredTooltip from './AnchoredTooltip'; import SwitchIcon from './SwitchIcon'; // Layout helpers import FlexCell from './FlexCell'; import IconLayout from './IconLayout'; import TextEllipsis from './TextEllipsis'; // Row components import TextLabel from './TextLabel'; import EditableTextLabel from './EditableTextLabel'; import Button from './Button'; import IconButton from './IconButton'; import Checkbox from './Checkbox'; import IconCheckbox from './IconCheckbox'; import Switch from './Switch'; import TextInput from './TextInput'; import SearchInput from './SearchInput'; // Containers import InfiniteScroll from './InfiniteScroll'; export { BasicRow, EditableBasicRow, Icon, StatusIcon, Tag, Text, EditableText, Tooltip, AnchoredTooltip, SwitchIcon, FlexCell, IconLayout, TextEllipsis, TextLabel, EditableTextLabel, Button, IconButton, Checkbox, IconCheckbox, Switch, TextInput, SearchInput, InfiniteScroll, };
import './styles/index.scss'; // Visual elements import BasicRow from './BasicRow'; import Icon from './Icon'; import StatusIcon from './StatusIcon'; import Tag from './Tag'; import Text from './Text'; import EditableText from './EditableText'; import Tooltip from './Tooltip'; import AnchoredTooltip from './AnchoredTooltip'; import SwitchIcon from './SwitchIcon'; // Layout helpers import FlexCell from './FlexCell'; import IconLayout from './IconLayout'; import TextEllipsis from './TextEllipsis'; // Row components import TextLabel from './TextLabel'; import EditableTextLabel from './EditableTextLabel'; import Button from './Button'; import IconButton from './IconButton'; import Checkbox from './Checkbox'; import IconCheckbox from './IconCheckbox'; import Switch from './Switch'; import TextInput from './TextInput'; import SearchInput from './SearchInput'; // Containers import InfiniteScroll from './InfiniteScroll'; export { BasicRow, Icon, StatusIcon, Tag, Text, EditableText, Tooltip, AnchoredTooltip, SwitchIcon, FlexCell, IconLayout, TextEllipsis, TextLabel, EditableTextLabel, Button, IconButton, Checkbox, IconCheckbox, Switch, TextInput, SearchInput, InfiniteScroll, };
Remove useless dependency in webpack
var webpack = require('webpack'); var precss = require('precss'); var autoprefixer = require('autoprefixer'); module.exports = { entry: [ './src/js/main.js' ], module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: ['babel'], query: { 'presets': ['react', 'es2015'], 'plugins': [ 'transform-object-rest-spread' ] } } ] }, postcss: function () { return [precss, autoprefixer({ browsers: ['> 5%'] })] }, resolve: { extensions: ['', '.js'] }, output: { path: __dirname + '/dist/js', publicPath: 'js', // it depends on what we set as content-base option with // the CLI filename: 'model-explorer.js' } }
var webpack = require('webpack'); var precss = require('precss'); var autoprefixer = require('autoprefixer'); var postcssGradientFixer = require('postcss-gradientfixer') module.exports = { entry: [ './src/js/main.js' ], module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: ['babel'], query: { 'presets': ['react', 'es2015'], 'plugins': [ 'transform-object-rest-spread' ] } } ] }, postcss: function () { return [precss, autoprefixer({ browsers: ['> 5%'] }), postcssGradientFixer] }, resolve: { extensions: ['', '.js'] }, output: { path: __dirname + '/dist/js', publicPath: 'js', // it depends on what we set as content-base option with // the CLI filename: 'model-explorer.js' } }
Add waitOn to subscription of requests
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.userId() ? Meteor.subscribe('Notifications', Meteor.userId()) : null } }); Router.route('/', { name: 'projectsList', waitOn: function() { return [Meteor.subscribe('Projects'), Meteor.subscribe('Requests')]; } }); Router.route('projects/new', { name: 'projectCreate' }); Router.route('projects/:_id', { name: 'projectPage', data: function() { return Projects.findOne(this.params._id); } }); Router.route('user/:userId', { name: 'userProfile', data: function() { return Meteor.users.findOne({_id: this.params.userId}); } });
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.userId() ? Meteor.subscribe('Notifications', Meteor.userId()) : null } }); Router.route('/', { name: 'projectsList', waitOn: function() { return Meteor.subscribe('Projects'); } }); Router.route('projects/new', { name: 'projectCreate' }); Router.route('projects/:_id', { name: 'projectPage', data: function() { return Projects.findOne(this.params._id); } }); Router.route('user/:userId', { name: 'userProfile', data: function() { return Meteor.users.findOne({_id: this.params.userId}); } });
Comment out ftp deploy for now
/** * Gulpfile * -------- * Here are the commands you can run. * gulp * gulp --maps * gulp --ugly * gulp --hint * gulp jshint * gulp jshint --ugly * gulp browserify * gulp browserify --hint * gulp browserify --ugly * gulp handlebars * gulp polyfill * gulp polyfill --ugly * gulp sass * gulp sass --maps * gulp watch (The first time you run, you'll be asked for your virtual host name) * gulp watch --ugly * gulp watch --hint * gulp watch --maps */ // pass 2 arrays to the task generator in ./gulp/index.js // 1st argument is an array of task names to load into memory, and // 2nd argument is an array of task names to run by default var gulp = require('./gulp')([ 'eslint', 'browserify', 'handlebars', 'polyfill', 'scss-lint', 'sass', 'watch', 'imagemin'/*, 'ftp-deploy'*/ ], [ 'eslint', 'browserify', 'handlebars', 'polyfill', 'scss-lint', 'sass', 'imagemin' ]);
/** * Gulpfile * -------- * Here are the commands you can run. * gulp * gulp --maps * gulp --ugly * gulp --hint * gulp jshint * gulp jshint --ugly * gulp browserify * gulp browserify --hint * gulp browserify --ugly * gulp handlebars * gulp polyfill * gulp polyfill --ugly * gulp sass * gulp sass --maps * gulp watch (The first time you run, you'll be asked for your virtual host name) * gulp watch --ugly * gulp watch --hint * gulp watch --maps */ // pass 2 arrays to the task generator in ./gulp/index.js // 1st argument is an array of task names to load into memory, and // 2nd argument is an array of task names to run by default var gulp = require('./gulp')([ 'eslint', 'browserify', 'handlebars', 'polyfill', 'scss-lint', 'sass', 'watch', 'imagemin', 'ftp-deploy' ], [ 'eslint', 'browserify', 'handlebars', 'polyfill', 'scss-lint', 'sass', 'imagemin' ]);
Add playerName and playerScore to stats page
class Stats extends Phaser.State { create() { this.totalScore = this.game.state.states['Main'].totalScore this.game.stage.backgroundColor = '#DFF4FF'; let statsHeader = "STATS" let continuePhrase = "Tap to Continue" this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"}); this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"}); this.playerName = prompt("Please enter your name", "Player"); this.playerScore = this.game.add.text(20, 20, (this.playerName + "'s Score: " + this.totalScore), { font: "60px Arial", fill: "#fffff"}); } update() { if(this.game.input.activePointer.justPressed()) { this.game.state.start('End'); } } } export default Stats;
class Stats extends Phaser.State { create() { this.totalScore = this.game.state.states['Main'].totalScore this.game.stage.backgroundColor = '#DFF4FF'; let statsHeader = "STATS" let continuePhrase = "Tap to Continue" this.statsHeaderText = this.game.add.text(650, 50, statsHeader, { font: "250px Revalia", textalign: "center"}); this.continueText = this.game.add.text(820, 300, continuePhrase, { font: "50px Arial", textalign: "center"}); this.playerScore = this.game.add.text(20, 20, "Your score: " + this.totalScore, { font: "60px Arial", fill: "#fffff"}); } update() { if(this.game.input.activePointer.justPressed()) { this.game.state.start('End'); } } } export default Stats;
Convert to ES5 compatible code
var crypto = require('crypto') // Crockford's Base32 // https://en.wikipedia.org/wiki/Base32 var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" function strongRandomNumber() { return crypto.randomBytes(4).readUInt32LE() / 0xFFFFFFFF } function encodeTime(now, len) { var arr = [] for (var x = len; x > 0; x--) { var mod = now % ENCODING.length arr[x] = ENCODING.charAt(mod) now = (now - mod) / ENCODING.length } return arr } function encodeRandom(len) { var rand var arr = [] for (var x = len; x > 0; x--) { rand = Math.floor(ENCODING.length * strongRandomNumber()) arr[x] = ENCODING.charAt(rando) } return arr } function ulid() { return [] .concat(encodeTime(Date.now(), 10)) .concat(encodeRandom(16)) .join('') } module.exports = { "strongRandomNumber": strongRandomNumber, "encodeTime": encodeTime, "encodeRandom": encodeRandom, "ulid": ulid }
import { randomBytes } from 'crypto'; // Crockford's Base32 // https://en.wikipedia.org/wiki/Base32 const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" function strongRandomNumber() { return randomBytes(4).readUInt32LE() / 0xFFFFFFFF } function encodeTime(now, len) { let arr = [] for (let x = len; x > 0; x--) { let mod = now % ENCODING.length arr[x] = ENCODING.charAt(mod) now = (now - mod) / ENCODING.length } return arr } function encodeRandom(len) { let arr = [] for (let x = len; x > 0; x--) { let rando = Math.floor(ENCODING.length * strongRandomNumber()) arr[x] = ENCODING.charAt(rando) } return arr } function ulid() { return [] .concat(encodeTime(Date.now(), 10)) .concat(encodeRandom(16)) .join('') } export { strongRandomNumber, encodeTime, encodeRandom } export default ulid
Define extra fields setValue() and getValue() on formelements
<?php /* * Doctrine Admin * Copyright (C) 2013 Bastiaan Welmers, bastiaan@welmers.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace Bast1aan\DoctrineAdmin\View { use Bast1aan\DoctrineAdmin\Property; interface FormElement { /** * @return string */ function render(); function __toString(); function getProperty(); function setProperty(Property $property); /** * Set the value of the element from incoming form data * @param string|string[] $value */ function setValue($value); /** * Get the value of this element sutable for the view * @return string|string[] */ function getValue(); } }
<?php /* * Doctrine Admin * Copyright (C) 2013 Bastiaan Welmers, bastiaan@welmers.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace Bast1aan\DoctrineAdmin\View { use Bast1aan\DoctrineAdmin\Property; interface FormElement { /** * @return string */ function render(); function __toString(); function getProperty(); function setProperty(Property $property); } }
Make atcd depends on atc_thrift package implicitely
#!/usr/bin/env python # # Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # # import sys from distutils.core import setup readme = open("README.md", "r") install_requires = [ 'pyroute2==0.3.3', 'pyotp==1.4.1', 'sparts==0.7.1', 'atc_thrift' ] tests_require = install_requires + [ 'pytest' ] if sys.version < '3.3': tests_require.append('mock') scripts = ['bin/atcd'] setup( name='atcd', version='0.0.1', description='ATC Daemon', author='Emmanuel Bretelle', author_email='chantra@fb.com', url='https://github.com/facebook/augmented-traffic-control', packages=['atcd', 'atcd.backends', 'atcd.scripts', 'atcd.tools'], classifiers=['Programming Language :: Python', ], long_description=readme.read(), scripts=scripts, install_requires=install_requires, tests_require=tests_require, )
#!/usr/bin/env python # # Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # # import sys from distutils.core import setup readme = open("README.md", "r") install_requires = [ 'pyroute2==0.3.3', 'pyotp==1.4.1', 'sparts==0.7.1', 'thrift' ] tests_require = install_requires + [ 'pytest' ] if sys.version < '3.3': tests_require.append('mock') scripts = ['bin/atcd'] setup( name='atcd', version='0.0.1', description='ATC Daemon', author='Emmanuel Bretelle', author_email='chantra@fb.com', url='https://github.com/facebook/augmented-traffic-control', packages=['atcd', 'atcd.backends', 'atcd.scripts', 'atcd.tools'], classifiers=['Programming Language :: Python', ], long_description=readme.read(), scripts=scripts, # FIXME: add atc_thrift dependency once package is published to pip install_requires=install_requires, tests_require=tests_require, )
Fix find function in content manager controller
'use strict'; /** * A set of functions called "actions" for `ContentManager` */ module.exports = { models: async(ctx) => { ctx.body = strapi.models; }, find: async(ctx) => { const model = ctx.params.model; const { limit = 10, skip = 0, sort = '_id' } = ctx.request.query; const entries = await User .find() .limit(Number(limit)) .sort(sort) .skip(Number(skip)); ctx.body = entries; }, count: async(ctx) => { const model = ctx.params.model; const count = await User .count(); ctx.body = { count: Number(count) }; }, findOne: async(ctx) => { const model = ctx.params.model; const _id = ctx.params._id; const entries = await User .find({ id }); ctx.body = entries; }, update: async(ctx) => { const entryUpdated = await User .update({_id: ctx.request.params.id}, ctx.request.body); ctx.body = entryUpdated; }, delete: async(ctx) => { const entryDeleted = await User .remove({_id: ctx.request.params.id}); ctx.body = entryDeleted; } };
'use strict'; /** * A set of functions called "actions" for `ContentManager` */ module.exports = { models: async(ctx) => { ctx.body = strapi.models; }, find: async(ctx) => { const model = ctx.params.model; const { limit = 10, skip = 0, sort = '_id' } = ctx.request.query; const entries = await User .find() .limit(limit) .sort(sort) .limit(skip); ctx.body = entries; }, count: async(ctx) => { const model = ctx.params.model; const count = await User .count(); ctx.body = { count: Number(count) }; }, findOne: async(ctx) => { const model = ctx.params.model; const _id = ctx.params._id; const entries = await User .find({ id }); ctx.body = entries; }, update: async(ctx) => { const entryUpdated = await User .update({_id: ctx.request.params.id}, ctx.request.body); ctx.body = entryUpdated; }, delete: async(ctx) => { const entryDeleted = await User .remove({_id: ctx.request.params.id}); ctx.body = entryDeleted; } };
Remove JSON dependency in POST logic.
import boto3 sdb = boto3.client('sdb') def lambda_handler(data, context): """ Handler for posting data to SimpleDB. Args: data -- Data to be stored (Dictionary). context -- AWS context for the request (Object). """ if data['Password'] and data['Password'] == 'INSERT PASSWORD': try: for person in ['Sharon', 'Ryan']: old_slice_count = int( sdb.get_attributes( DomainName='pizza', ItemName=person, AttributeNames=['Slices'] )['Attributes'][0]['Value'] ) new_slice_count = old_slice_count + data[person] sdb.put_attributes( DomainName='pizza', ItemName=person, Attributes=[{ 'Name': 'Slices', 'Value': str(new_slice_count), 'Replace': True }] ) return {'Success': 'Your data was submitted!'} except: return {'Error': 'Your data was not submitted.'} else: return {'Error': 'Ah ah ah, you didn\'t say the magic word.'}
import boto3, json sdb = boto3.client('sdb') def lambda_handler(data, context): """ Handler for posting data to SimpleDB. Args: data -- Data to be stored (Dictionary). context -- AWS context for the request (Object). """ if data['Password'] and data['Password'] == 'INSERT PASSWORD': try: for person in ['Sharon', 'Ryan']: old_slice_count = int( sdb.get_attributes( DomainName='pizza', ItemName=person, AttributeNames=['Slices'] )['Attributes'][0]['Value'] ) new_slice_count = old_slice_count + data[person] sdb.put_attributes( DomainName='pizza', ItemName=person, Attributes=[{ 'Name': 'Slices', 'Value': str(new_slice_count), 'Replace': True }] ) return json.dumps({'Success': 'Your data was submitted!'}) except: return json.dumps({'Error': 'Your data was not submitted.'}) else: return json.dumps({ 'Error': 'Ah ah ah, you didn\'t say the magic word.' })
Add test for model representation
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long)
Make it compatible for updated ImageDTO class.
/** * */ package gov.nih.nci.nbia.dto; import junit.framework.TestCase; /** * @author lethai * */ public class ImageDTOTestCase extends TestCase { public void testAccessors() { String SOPInstanceUID="1.2.3.4.5.6"; String fileName="1.2.3.4.5.6.7.dcm"; Long dicomSize = new Long(514); String project="RIDER"; String site="RIDER"; String ssg="test"; int frameNum = 0; ImageDTO imageDTO = new ImageDTO(SOPInstanceUID, fileName, dicomSize, project, site, ssg, 0); assertTrue(imageDTO.getSOPInstanceUID().equals("1.2.3.4.5.6")); assertTrue(imageDTO.getFileName().equals("1.2.3.4.5.6.7.dcm")); assertTrue(imageDTO.getDicomSize() ==514L); assertTrue(imageDTO.getProject().equals("RIDER")); assertTrue(imageDTO.getSite().equals("RIDER")); assertTrue(imageDTO.getSsg().equals("test")); } }
/** * */ package gov.nih.nci.nbia.dto; import junit.framework.TestCase; /** * @author lethai * */ public class ImageDTOTestCase extends TestCase { public void testAccessors() { String SOPInstanceUID="1.2.3.4.5.6"; String fileName="1.2.3.4.5.6.7.dcm"; Long dicomSize = new Long(514); String project="RIDER"; String site="RIDER"; String ssg="test"; ImageDTO imageDTO = new ImageDTO(SOPInstanceUID, fileName, dicomSize, project, site, ssg); assertTrue(imageDTO.getSOPInstanceUID().equals("1.2.3.4.5.6")); assertTrue(imageDTO.getFileName().equals("1.2.3.4.5.6.7.dcm")); assertTrue(imageDTO.getDicomSize() ==514L); assertTrue(imageDTO.getProject().equals("RIDER")); assertTrue(imageDTO.getSite().equals("RIDER")); assertTrue(imageDTO.getSsg().equals("test")); } }
Remove all has to reflect changes to get next
from kombu import Connection, Exchange, Queue from flask import Flask import os app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) @app.route("/getnextqueuemessage") #Gets the next message from target queue. Returns the signed JSON. def get_last_queue_message(): #: By default messages sent to exchanges are persistent (delivery_mode=2), #: and queues and exchanges are durable. exchange = Exchange() connection = Connection(app.config['OUTGOING_QUEUE_HOSTNAME']) # Create/access a queue bound to the connection. queue = Queue(app.config['OUTGOING_QUEUE'], exchange, routing_key='#')(connection) queue.declare() message = queue.get() if message: signature = message.body message.ack() #acknowledges message, ensuring its removal. return signature else: return "no message", 404 @app.route("/removeallmessages") #Gets the next message from target queue. Returns the signed JSON. def remove_all_messages(): while True: queue_message = get_last_queue_message() if queue_message == ('no message', 404): break return "done", 202 @app.route("/") def check_status(): return "Everything is OK"
from kombu import Connection, Exchange, Queue from flask import Flask import os app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) @app.route("/getnextqueuemessage") #Gets the next message from target queue. Returns the signed JSON. def get_last_queue_message(): #: By default messages sent to exchanges are persistent (delivery_mode=2), #: and queues and exchanges are durable. exchange = Exchange() connection = Connection(app.config['OUTGOING_QUEUE_HOSTNAME']) # Create/access a queue bound to the connection. queue = Queue(app.config['OUTGOING_QUEUE'], exchange, routing_key='#')(connection) queue.declare() message = queue.get() if message: signature = message.body message.ack() #acknowledges message, ensuring its removal. return signature else: return "no message", 404 @app.route("/removeallmessages") #Gets the next message from target queue. Returns the signed JSON. def remove_all_messages(): while True: queue_message = get_last_queue_message() if queue_message == 'no message': break return "done", 202 @app.route("/") def check_status(): return "Everything is OK"
Fix escaping for stricter php7.3. Escaping the minus is the right fix.
<?php declare(strict_types = 1); namespace Soliant\SimpleFM\Client\ResultSet\Transformer; use Litipk\BigNumbers\Decimal; final class NumberTransformer { public function __invoke(string $value) { $cleanedValue = preg_replace_callback( '(^[^\d\-.]*(-?)([^.]*)(.?)(.*)$)', function (array $match) : string { return $match[1] . preg_replace('([^\d]+)', '', $match[2]) . $match[3] . preg_replace('([^\d]+)', '', $match[4]); }, $value ); if ('' === $cleanedValue) { return null; } if ('-' === $cleanedValue) { $cleanedValue = '0'; } if (0 === strpos($cleanedValue, '.')) { $cleanedValue = '0' . $cleanedValue; } return Decimal::fromString($cleanedValue); } }
<?php declare(strict_types = 1); namespace Soliant\SimpleFM\Client\ResultSet\Transformer; use Litipk\BigNumbers\Decimal; final class NumberTransformer { public function __invoke(string $value) { $cleanedValue = preg_replace_callback( '(^[^\d-\.]*(-?)([^.]*)(.?)(.*)$)', function (array $match) : string { return $match[1] . preg_replace('([^\d]+)', '', $match[2]) . $match[3] . preg_replace('([^\d]+)', '', $match[4]); }, $value ); if ('' === $cleanedValue) { return null; } if ('-' === $cleanedValue) { $cleanedValue = '0'; } if (0 === strpos($cleanedValue, '.')) { $cleanedValue = '0' . $cleanedValue; } return Decimal::fromString($cleanedValue); } }
Add get API to user service
var cote = require('cote'), models = require('../models'); var userResponder = new cote.Responder({ name: 'user responder', namespace: 'user', respondsTo: ['create'] }); var userPublisher = new cote.Publisher({ name: 'user publisher', namespace: 'user', broadcasts: ['update'] }); userResponder.on('*', console.log); userResponder.on('create', function(req, cb) { models.User.create({}, cb); updateUsers(); }); userResponder.on('list', function(req, cb) { var query = req.query || {}; models.User.find(query, cb); }); userResponder.on('get', function(req, cb) { models.User.get(req.id, cb); }); function updateUsers() { models.User.find(function(err, users) { userPublisher.publish('update', users); }); }
var cote = require('cote'), models = require('../models'); var userResponder = new cote.Responder({ name: 'user responder', namespace: 'user', respondsTo: ['create'] }); var userPublisher = new cote.Publisher({ name: 'user publisher', namespace: 'user', broadcasts: ['update'] }); userResponder.on('*', console.log); userResponder.on('create', function(req, cb) { models.User.create({}, cb); updateUsers(); }); userResponder.on('list', function(req, cb) { var query = req.query || {}; models.User.find(query, cb); }); function updateUsers() { models.User.find(function(err, users) { userPublisher.publish('update', users); }); }
Modify PriorityQueue constructor call to be compliant with JDK 7. Was using a JDK 8 only constructor.
package aima.core.search.framework; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; /** * Factory class for queues. Changes made here will affect all queue based * search algorithms of this library. * * @author Ruediger Lunde * */ public class QueueFactory { /** * Returns a {@link LinkedList}. */ public static <E> Queue<E> createFifoQueue() { return new LinkedList<E>(); } /** * Returns a Last-in-first-out (Lifo) view on a {@link LinkedList}. */ public static <E> Queue<E> createLifoQueue() { return Collections.asLifoQueue(new LinkedList<E>()); } /** * Returns a standard java {@link PriorityQueue}. Note that the smallest * element comes first! */ public static <E> Queue<E> createPriorityQueue(Comparator<? super E> comparator) { return new PriorityQueue<E>(11, comparator); } }
package aima.core.search.framework; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; /** * Factory class for queues. Changes made here will affect all queue based * search algorithms of this library. * * @author Ruediger Lunde * */ public class QueueFactory { /** * Returns a {@link LinkedList}. */ public static <E> Queue<E> createFifoQueue() { return new LinkedList<E>(); } /** * Returns a Last-in-first-out (Lifo) view on a {@link LinkedList}. */ public static <E> Queue<E> createLifoQueue() { return Collections.asLifoQueue(new LinkedList<E>()); } /** * Returns a standard java {@link PriorityQueue}. Note that the smallest * element comes first! */ public static <E> Queue<E> createPriorityQueue(Comparator<? super E> comparator) { return new PriorityQueue<E>(comparator); } }
Replace double quotes with single
<?php namespace Acd; /** * Request Class * @author Acidvertigo MIT Licence */ class Request { private $headers = []; /** * Check HTTP request headers * @return array list of response headers * @throws InvalidArgumentException if header is null */ public function getRequestHeaders() { if (function_exists('getallheaders()')) { $this->headers = getallheaders(); } else { $this->headers = $this->getServerHeaders(); } if ($this->headers !== null) { return $this->headers; } else { throw new \InvalidArgumentException('Unable to get Request Headers'); } } /** * Helper function if getallheaders() not available * @return array list of response headers */ private function getServerHeaders() { foreach (array_keys($_SERVER) as $skey) { if (strpos($skey, 'HTTP_') !== FALSE) { $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey]; } } return $this->headers; } }
<?php namespace Acd; /** * Request Class * @author Acidvertigo MIT Licence */ class Request { private $headers = []; /** * Check HTTP request headers * @return array list of response headers * @throws InvalidArgumentException if header is null */ public function getRequestHeaders() { if (function_exists("getallheaders()")) { $this->headers = getallheaders(); } else { $this->headers = $this->getServerHeaders(); } if ($this->headers !== null) { return $this->headers; } else { throw new \InvalidArgumentException('Unable to get Request Headers'); } } /** * Helper function if getallheaders() not available * @return array list of response headers */ private function getServerHeaders() { foreach (array_keys($_SERVER) as $skey) { if (strpos($skey, 'HTTP_') !== FALSE) { $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey]; } } return $this->headers; } }
Remove support of uglify and change path
module.exports = function(grunt) { grunt.initConfig({ jshint: { all: ['Gruntfile.js', 'src/cookie.js', 'tests/spec.js'], options: { browser: true, evil: false, expr: true, supernew: true, eqeqeq: true, eqnull: true, forin: true, smarttabs: true } }, mocha: { all: { src: 'tests/index.html', run: true } }, watch: { files: ['src/cookie.js', 'tests/*'], tasks: 'development' } }); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('test', 'mocha'); grunt.registerTask('default', ['jshint', 'mocha']); grunt.registerTask('release', 'default'); grunt.registerTask('development', ['jshint', 'mocha']); };
module.exports = function(grunt) { grunt.initConfig({ jshint: { all: ['Gruntfile.js', 'cookie.js', 'tests/spec.js'], options: { browser: true, evil: false, expr: true, supernew: true, eqeqeq: true, eqnull: true, forin: true, smarttabs: true } }, mocha: { all: { src: 'tests/index.html', run: true } }, uglify: { options: { banner: grunt.file.read('cookie.js').split('\n')[0] + "\n" }, my_target: { files: { 'cookie.min.js': ['cookie.js'] } } }, watch: { files: ['cookie.js', 'tests/*'], tasks: 'development' } }); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('test', 'mocha'); grunt.registerTask('min', 'uglify'); grunt.registerTask('default', ['jshint', 'mocha', 'uglify']); grunt.registerTask('release', 'default'); grunt.registerTask('development', ['jshint', 'mocha']); };
Fix section listing on Firefox. Support browsers, like Firefox, that don't support innerText function call. They call it textContent there. Weirdos.
function create_section_listing() { $('div#sidebar h3').click(function(e) { window.scrollTo(0, 0); }); $('.section_title').each(function (i, e) { $("div#sidebar #section_listing").append("<a id='" + e.id + "_link'>" + (e.innerText || e.innerContent) + "</a>"); just_added = $("div#sidebar #section_listing").children().last(); if (e.tagName == "H2") { just_added.addClass("major"); } else { just_added.addClass("minor"); } }); $('#sidebar a').click(function(e) { section_id = $(this).attr("id").replace("_link", ""); window.scrollTo(0, $("#" + section_id)[0].offsetTop); }) }
function create_section_listing() { $('div#sidebar h3').click(function(e) { window.scrollTo(0, 0); }); $('.section_title').each(function (i, e) { $("div#sidebar #section_listing").append("<a id='" + e.id + "_link'>" + e.innerText + "</a>"); just_added = $("div#sidebar #section_listing").children().last(); if (e.tagName == "H2") { just_added.addClass("major"); } else { just_added.addClass("minor"); } }); $('#sidebar a').click(function(e) { section_id = $(this).attr("id").replace("_link", ""); window.scrollTo(0, $("#" + section_id)[0].offsetTop); }) }
Add display to game plugin, add redraw method on gsman
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; import display from "./overview/Display.js"; export default { install: (Vue) => { Vue.prototype.$game = { start() { GameStateManager.StartGame(); }, receiveInput(input) { console.log(input); GameStateManager.receiveInput(input); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); }, getCurrentState() { return GameStateManager.currentState; }, redraw() { return GameStateManager.redraw(); }, display: display, } } }
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; export default { install: (Vue) => { Vue.prototype.$game = { start() { GameStateManager.StartGame(); }, receiveInput(input) { console.log(input); GameStateManager.receiveInput(input); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); }, getCurrentState() { return GameStateManager.currentState; } } } }
Update proxy with a currently-working example
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "167.99.151.183:8080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "40.114.109.214:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Fix notification-center not to close when button clicked.
import { constant, includes } from 'lodash'; import { element } from 'angular'; import uiModules from 'ui/modules'; import registry from 'ui/registry/chrome_nav_controls'; import '../components/notification_center'; import template from './nav_control.html'; import 'ui/angular-bootstrap'; registry.register(constant({ name: 'notification_center', order: 1000, template })); const module = uiModules.get('notification_center', []); module.controller('notificationCenterNavController', ($scope, $compile, $document, NotificationCenter) => { function initNotificationCenter() { const $elem = $scope.$notificationCenter = $compile('<notification-center/>')($scope).appendTo('.app-wrapper'); $document.on('click', () => $elem.hide()); $elem.on('click', e => e.stopPropagation()); }; $scope.openNotificationCenter = event => { event.preventDefault(); if (!$scope.$notificationCenter) { initNotificationCenter(); } else { $scope.$notificationCenter.toggle(); } event.stopPropagation(); }; $scope.formatTooltip = () =>{ return `${NotificationCenter.notifications.length} new notifications`; }; });
import { constant, includes } from 'lodash'; import { element } from 'angular'; import uiModules from 'ui/modules'; import registry from 'ui/registry/chrome_nav_controls'; import '../components/notification_center'; import template from './nav_control.html'; import 'ui/angular-bootstrap'; registry.register(constant({ name: 'notification_center', order: 1000, template })); const module = uiModules.get('notification_center', []); module.controller('notificationCenterNavController', ($scope, $compile, $document, NotificationCenter) => { function initNotificationCenter() { const $elem = $scope.$notificationCenter = $compile('<notification-center></notification-center>')($scope).appendTo('.app-wrapper'); $document.on('click', ({ target }) => { if (target !== $elem[0] && !$elem[0].contains(target)) { $elem.hide(); } }); }; $scope.openNotificationCenter = event => { event.preventDefault(); if (!$scope.$notificationCenter) { initNotificationCenter(); } else { $scope.$notificationCenter.toggle(); } event.stopPropagation(); }; $scope.formatTooltip = () =>{ return `${NotificationCenter.notifications.length} new notifications`; }; });
Remove GDAL requirement (it's not a direct dependency)
from setuptools import setup setup( name='ncdjango', description='A map server for NetCDF data', keywords='netcdf,django,map server', version='0.4.0', packages=[ 'ncdjango', 'ncdjango.geoprocessing', 'ncdjango.migrations', 'ncdjango.interfaces', 'ncdjango.interfaces.arcgis', 'ncdjango.interfaces.arcgis_extended', 'ncdjango.interfaces.data' ], install_requires=[ 'six', 'requests', 'Django>=1.7.0,<1.9.0', 'Pillow>=2.9.0', 'Shapely>=1.3.2', 'django-tastypie>=0.11.1', 'netCDF4>=1.1.6', 'numpy>=1.8.1', 'pyproj>=1.9.4', 'fiona', 'rasterio>=0.28.0', 'clover', 'ply>=3.8', 'celery>=3.1.19', 'djangorestframework' ], dependency_links=[ 'git+https://github.com/consbio/clover.git' ], url='https://github.com/consbio/ncdjango', license='BSD', )
from setuptools import setup setup( name='ncdjango', description='A map server for NetCDF data', keywords='netcdf,django,map server', version='0.4.0', packages=[ 'ncdjango', 'ncdjango.geoprocessing', 'ncdjango.migrations', 'ncdjango.interfaces', 'ncdjango.interfaces.arcgis', 'ncdjango.interfaces.arcgis_extended', 'ncdjango.interfaces.data' ], install_requires=[ 'six', 'requests', 'Django>=1.7.0,<1.9.0', 'Pillow>=2.9.0', 'Shapely>=1.3.2', 'GDAL>=1.11.0', 'django-tastypie>=0.11.1', 'netCDF4>=1.1.6', 'numpy>=1.8.1', 'pyproj>=1.9.4', 'fiona', 'rasterio>=0.28.0', 'clover', 'ply>=3.8', 'celery>=3.1.19', 'djangorestframework' ], dependency_links=[ 'git+https://github.com/consbio/clover.git' ], url='https://github.com/consbio/ncdjango', license='BSD', )
Add unit test for Figshare ID in L1 presenter
import parseL1ArticlePresenters from '../../../../lib/repository-mappers/figshare/parseL1ArticlePresenters'; const figshareL1Articles = require('./resources/figshareL1Articles.json'); const convertedArticles = parseL1ArticlePresenters(figshareL1Articles); it('parses all articles figshare returns', () => expect(convertedArticles.length).toBe(2) ); it('parses Figshare article IDs', () => { expect(convertedArticles[0].id).toBe(figshareL1Articles[0].id); expect(convertedArticles[1].id).toBe(figshareL1Articles[1].id); }); it('converts Figshare article DOIs to codemeta identifier', () => { expect(convertedArticles[0].identifier).toBe(figshareL1Articles[0].doi); expect(convertedArticles[1].identifier).toBe(figshareL1Articles[1].doi); }); it('converts Figshare article titles to codemeta titles', () => { expect(convertedArticles[0].title).toBe(convertedArticles[0].title); expect(convertedArticles[1].title).toBe(convertedArticles[1].title); }); it('converts Figshare article published date to codemeta date published', () => { expect(convertedArticles[0].datePublished).toBe(figshareL1Articles[0].published_date); expect(convertedArticles[1].datePublished).toBe(figshareL1Articles[1].published_date); });
import parseL1ArticlePresenters from '../../../../lib/repository-mappers/figshare/parseL1ArticlePresenters'; const figshareL1Articles = require('./resources/figshareL1Articles.json'); const convertedArticles = parseL1ArticlePresenters(figshareL1Articles); it('parses all articles figshare returns', () => expect(convertedArticles.length).toBe(2) ); it('converts Figshare article DOIs to codemeta identifier', () => { expect(convertedArticles[0].identifier).toBe(figshareL1Articles[0].doi); expect(convertedArticles[1].identifier).toBe(figshareL1Articles[1].doi); }); it('converts Figshare article titles to codemeta titles', () => { expect(convertedArticles[0].title).toBe(convertedArticles[0].title); expect(convertedArticles[1].title).toBe(convertedArticles[1].title); }); it('converts Figshare article published date to codemeta date published', () => { expect(convertedArticles[0].datePublished).toBe(figshareL1Articles[0].published_date); expect(convertedArticles[1].datePublished).toBe(figshareL1Articles[1].published_date); });
Fix a typo in Hyperband’s test
from .tuner import Hyperband import unittest class HyperbandTestCase(unittest.TestCase): def test_run(self): observed_ns = [] observed_rs = [] observed_cs = [] def _get(n): observed_ns.append(n) return list(range(n)) def _test(r, c): observed_rs.append(int(r)) observed_cs.append(len(c)) return [r * c for c in c] tuner = Hyperband() tuner.run(_get, _test) expected_ns = [81, 34, 15, 8, 5] expected_rs = [1, 3, 9, 27, 81, 3, 9, 27, 81, 9, 27, 81, 27, 81, 81] expected_cs = [81, 27, 9, 3, 1, 27, 9, 3, 1, 9, 3, 1, 6, 2, 5] self.assertEqual(expected_ns, observed_ns) self.assertEqual(expected_rs, observed_rs) self.assertEqual(expected_cs, observed_cs)
from .tuner import Hyperband import unittest class HyperbandTestCase(unittest.TestCase): def test_run(self): observed_ns = [] observed_rs = [] observed_cs = [] def _get(n): observed_ns.append(n) return list(range(n)) def _test(r, c): observed_rs.append(int(r)) observed_cs.append(len(c)) return [r * c for c in c] tuner = Hyperband() tuner.run(_get, _test) expected_ns = [81, 34, 15, 8, 5] expected_rs = [1, 3, 9, 27, 81, 3, 9, 27, 81, 9, 27, 81, 27, 81, 81] expected_cs = [81, 27, 9, 3, 1, 27, 9, 3, 1, 9, 3, 1, 6, 2, 5] self.assertEqual(expected_ns, observed_ns) self.assertEqual(expected_rs, observed_rs) self.assertEqual(expected_rs, observed_rs)
Fix Blanket config to ignore generated files
// jscs: disable /* globals blanket, module */ var options = { modulePrefix: 'component-integration-tests', filter: /^component-integration-tests\//, antifilter: [ 'component-integration-tests/initializers/export-application-global', 'component-integration-tests/instance-initializers/app-version', 'component-integration-tests/controllers/array', 'component-integration-tests/controllers/object', '/tests/', '/config/', '/templates/', ], loaderExclusions: [], enableCoverage: true, cliOptions: { lcovOptions: { outputFile: 'lcov.dat', renamer: function(moduleName){ var expression = /^component-integration-tests/; return moduleName.replace(expression, 'app') + '.js'; } }, reporters: ['lcov'] } }; if (typeof exports === 'undefined') { blanket.options(options); } else { module.exports = options; }
// jscs: disable /* globals blanket, module */ var options = { modulePrefix: 'component-integration-tests', filter: /^component-integration-tests\//, antifilter: [ 'component-integration-tests/initializers/export-application-global', 'component-integration-tests/initializers/app-version', 'component-integration-tests/controllers/array.js', 'component-integration-tests/controllers/object.js', '/tests/', '/config/', '/templates/', ], loaderExclusions: [], enableCoverage: true, cliOptions: { lcovOptions: { outputFile: 'lcov.dat', renamer: function(moduleName){ var expression = /^component-integration-tests/; return moduleName.replace(expression, 'app') + '.js'; } }, reporters: ['lcov'] } }; if (typeof exports === 'undefined') { blanket.options(options); } else { module.exports = options; }
Use ">>" for indicating next event, fix bug with indexing
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:]
Remove propTypes in favor of real tests that verify the same thing.
import React from 'react'; export default class KataGroupsComponent extends React.Component { render() { const {kataGroups} = this.props; return ( <div id="nav" className="pure-u"> <a href="#" className="nav-menu-button">Menu</a> <div className="nav-inner"> <div className="pure-menu"> <ul className="pure-menu-list"> <li className="pure-menu-heading">Kata groups</li> <li className="pure-menu-item"> </li> {kataGroups.groups.map(kataGroup => <li className="pure-menu-item"> <a href={kataGroup.url} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a> </li>)} </ul> </div> </div> </div> ); } }
import React from 'react'; import {default as KataGroupsData} from '../katagroups.js'; export default class KataGroupsComponent extends React.Component { static propTypes = { kataGroups: React.PropTypes.instanceOf(KataGroupsData).isRequired }; render() { const {kataGroups} = this.props; return ( <div id="nav" className="pure-u"> <a href="#" className="nav-menu-button">Menu</a> <div className="nav-inner"> <div className="pure-menu"> <ul className="pure-menu-list"> <li className="pure-menu-heading">Kata groups</li> <li className="pure-menu-item"> </li> {kataGroups.groups.map(kataGroup => <li className="pure-menu-item"> <a href={kataGroup.url} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a> </li>)} </ul> </div> </div> </div> ); } }
TAP5-1126: Add a new validator, "none", used when overriding the @Validate annotation git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@940984 13f79535-47bb-0310-9956-ffa450edef68
// Copyright 2010 The Apache Software Foundation // // 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 org.apache.tapestry5.validator; import org.apache.tapestry5.Field; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.ValidationException; import org.apache.tapestry5.ioc.MessageFormatter; import org.apache.tapestry5.services.FormSupport; public class None extends AbstractValidator<Void, Object> { public None() { super(null, Object.class, "required"); } /** Does nothing. */ public void render(Field field, Void constraintValue, MessageFormatter formatter, MarkupWriter writer, FormSupport formSupport) { } /** Does nothing. */ public void validate(Field field, Void constraintValue, MessageFormatter formatter, Object value) throws ValidationException { } }
// Copyright 2010 The Apache Software Foundation // // 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 org.apache.tapestry5.validator; import org.apache.tapestry5.Field; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.ValidationException; import org.apache.tapestry5.ioc.MessageFormatter; import org.apache.tapestry5.services.FormSupport; public class None extends AbstractValidator<Void, Object> { public None() { super(Void.class, Object.class, "not-used"); } /** Does nothing. */ public void render(Field field, Void constraintValue, MessageFormatter formatter, MarkupWriter writer, FormSupport formSupport) { } /** Does nothing. */ public void validate(Field field, Void constraintValue, MessageFormatter formatter, Object value) throws ValidationException { } }
Use bootstrap4 markup for tabs
import React, { Component, Children, PropTypes } from 'react' export function Tab(props, {activeTab, changeTab}) { const onClick = (e) => { e.preventDefault() changeTab(props.for) } let active = props.for === activeTab if (props.render) { return(props.render({active, changeTab: () => changeTab(props.for) })) } let className = active ? 'active' : null return( <li key={props.for} role="tab" className='nav-item'> <a href={`#${props.for}`} className={'nav-link ' + className} onClick={e => onClick(e)}> {props.children} </a> </li> ) } Tab.propTypes = { for: PropTypes.string.isRequired, render: PropTypes.func } Tab.contextTypes = { activeTab: PropTypes.string, changeTab: PropTypes.func }
import React, { Component, Children, PropTypes } from 'react' export function Tab(props, {activeTab, changeTab}) { const onClick = (e) => { e.preventDefault() changeTab(props.for) } let active = props.for === activeTab if (props.render) { return(props.render({active, changeTab: () => changeTab(props.for) })) } let className = active ? 'active' : null return( <li key={props.for} role="tab" className={className}> <a href={`#${props.for}`} onClick={e => onClick(e)}> {props.children} </a> </li> ) } Tab.propTypes = { for: PropTypes.string.isRequired, render: PropTypes.func } Tab.contextTypes = { activeTab: PropTypes.string, changeTab: PropTypes.func }
Add reducer to change highlighted state of help button
import { Map } from 'immutable'; const tutorial = ( state = Map({ active: false, current: 0, totalPopUps: 0, highlightHelp: false }), action ) => { switch (action.type) { case 'OPEN_TUTORIAL': return state.merge(Map({ active: true, current: 1 })); case 'CLOSE_TUTORIAL': return state.set('active', false); case 'VIEW_NEXT': return state.get('current') === state.get('totalPopUps') ? state.merge(Map({ active: false, current: 0 })) : state.set('current', state.get('current') + 1); case 'VIEW_PREVIOUS': return state.set('current', state.get('current') - 1); case 'SET_LENGTH': return state.set('totalPopUps', action.totalPopUps); case 'TOGGLE_HELP_HIGHLIGHT': return state.set('highlightHelp', !state.get('highlightHelp')); default: return state; } }; export default tutorial;
import { Map } from 'immutable'; const tutorial = ( state = Map({ active: false, current: 0, totalPopUps: 0 }), action ) => { switch (action.type) { case 'OPEN_TUTORIAL': return state.merge(Map({ active: true, current: 1 })); case 'CLOSE_TUTORIAL': return state.set('active', false); case 'VIEW_NEXT': return state.get('current') === state.get('totalPopUps') ? state.merge(Map({ active: false, current: 0 })) : state.set('current', state.get('current') + 1); case 'VIEW_PREVIOUS': return state.set('current', state.get('current') - 1); case 'SET_LENGTH': return state.set('totalPopUps', action.totalPopUps); default: return state; } }; export default tutorial;
Add spinner to upload button Signed-off-by: Walker Crouse <a52c6ce3cf7a08dcbb27377aa79f9b994b446d4c@hotmail.com>
var MAX_FILE_SIZE = 1048576; $(function() { $('#pluginFile').on('change', function() { var alert = $('.alert-file'); var fileName = $(this).val().trim(); var fileSize = this.files[0].size; if (!fileName) { alert.fadeOut(1000); return; } if (fileSize > MAX_FILE_SIZE) { alert.find('i').removeClass('fa-upload').addClass('fa-times'); alert.find('.file-upload').find('button') .removeClass('btn-success') .addClass('btn-danger') .prop('disabled', true); alert.find('.file-size').css('color', '#d9534f'); } fileName = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length); alert.find('.file-name').text(fileName); alert.find('.file-size').text(filesize(this.files[0].size)); alert.fadeIn('slow'); }); $('.file-upload').find('button').click(function() { $(this).find('i').removeClass('fa-upload').addClass('fa-spinner fa-spin'); }); });
var MAX_FILE_SIZE = 1048576; $(function() { $('#pluginFile').on('change', function() { var alert = $('.alert-file'); var fileName = $(this).val().trim(); var fileSize = this.files[0].size; if (!fileName) { alert.fadeOut(1000); return; } if (fileSize > MAX_FILE_SIZE) { alert.find('i').removeClass('fa-upload').addClass('fa-times'); alert.find('.file-upload').find('button') .removeClass('btn-success') .addClass('btn-danger') .prop('disabled', true); alert.find('.file-size').css('color', '#d9534f'); } fileName = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length); alert.find('.file-name').text(fileName); alert.find('.file-size').text(filesize(this.files[0].size)); alert.fadeIn('slow'); }); });
Fix packaging issue in 0.3 release Signed-off-by: Brennan Ashton <3c2365aa085787349a5327558db844b55eabde30@brennanashton.com>
""" Flask-InfluxDB """ from setuptools import setup setup( name="Flask-InfluxDB", version="0.3.1", url="http://github.com/btashton/flask-influxdb", license="BSD", author="Brennan Ashton", author_email="brennan@ombitron.com", description="Flask bindings for the InfluxDB time series database", long_description=__doc__, packages=["flask_influxdb"], zip_safe=False, include_package_data=True, platforms="any", install_requires=["Flask", "influxdb==5.2.2",], classifiers=[ "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", ], )
""" Flask-InfluxDB """ from setuptools import setup setup( name="Flask-InfluxDB", version="0.3", url="http://github.com/btashton/flask-influxdb", license="BSD", author="Brennan Ashton", author_email="brennan@ombitron.com", description="Flask bindings for the InfluxDB time series database", long_description=__doc__, py_modules=["flask_influxdb"], zip_safe=False, include_package_data=True, platforms="any", install_requires=["Flask", "influxdb==5.2.2",], classifiers=[ "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", ], )
Fix something in the the expected invocation example.
var Ajax = { get: function(uri) { } }; var Updater = Class.create({ initialize: function(bookId) { this.bookId = bookId; }, run: function() { var book = Ajax.get('http://example.com/books/'+this.bookId+'.json'); var title = book.title; $('title').innerHTML = book.title; } }); Moksi.describe('Updater', { setup: function() { setSample('<div id="title"></div>'); this.suite.updater = new Updater(12); }, 'fetches book information from the correct URL': function() { expects(Ajax).receives('get', { withArguments: ['http://example.com/books/12.json'], returns: { title: 'The Haunter of the Dark' } }); this.suite.updater.run(); } });
var Ajax = { get: function(uri) { } }; var Updater = Class.create({ initialize: function(bookId) { this.bookId = bookId; setSample('<div id="title"></div>'); }, run: function() { var book = Ajax.get('http://example.com/books/'+this.bookId+'.json'); var title = book.title; $('title').innerHTML = book.title; } }); Moksi.describe('Updater', { setup: function() { this.suite.updater = new Updater(12); }, 'fetches book information from the correct URL': function() { expects(Ajax).receives('get', { withArguments: ['http://example.com/books/12.json'], returns: { title: 'The Haunter of the Dark' } }); this.suite.updater.run(); } });
Remove "!" from test since it is not sent by a service
/* * Copyright (C) 2016-2017 Lightbend Inc. <https://www.lightbend.com> */ package org.cakesolutions.hello.impl; import org.cakesolutions.hello.api.HelloService; import org.cakesolutions.hello.api.KGreetingMessage; import org.junit.Test; import static com.lightbend.lagom.javadsl.testkit.ServiceTest.defaultSetup; import static com.lightbend.lagom.javadsl.testkit.ServiceTest.withServer; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; public class HelloServiceTest { @Test public void shouldStorePersonalizedGreeting() throws Exception { withServer(defaultSetup().withCassandra(true), server -> { HelloService service = server.client(HelloService.class); String msg1 = service.hello("Alice").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hello, Alice", msg1); // default greeting service.useGreeting("Alice").invoke(new KGreetingMessage("Hi")).toCompletableFuture().get(5, SECONDS); String msg2 = service.hello("Alice").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hi, Alice", msg2); String msg3 = service.hello("Bob").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hello, Bob", msg3); // default greeting }); } }
/* * Copyright (C) 2016-2017 Lightbend Inc. <https://www.lightbend.com> */ package org.cakesolutions.hello.impl; import org.cakesolutions.hello.api.HelloService; import org.cakesolutions.hello.api.KGreetingMessage; import org.junit.Test; import static com.lightbend.lagom.javadsl.testkit.ServiceTest.defaultSetup; import static com.lightbend.lagom.javadsl.testkit.ServiceTest.withServer; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; public class HelloServiceTest { @Test public void shouldStorePersonalizedGreeting() throws Exception { withServer(defaultSetup().withCassandra(true), server -> { HelloService service = server.client(HelloService.class); String msg1 = service.hello("Alice").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hello, Alice!", msg1); // default greeting service.useGreeting("Alice").invoke(new KGreetingMessage("Hi")).toCompletableFuture().get(5, SECONDS); String msg2 = service.hello("Alice").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hi, Alice!", msg2); String msg3 = service.hello("Bob").invoke().toCompletableFuture().get(5, SECONDS); assertEquals("Hello, Bob!", msg3); // default greeting }); } }
Put the device lookup code back for Linux
package main import ( "bufio" "fmt" "os" "regexp" ) func findDeviceFromMount (mount string) (string, error) { // stub for Mac devel //return "/dev/xvda", nil var device string = "" // Serious Linux-only stuff happening here... file := "/proc/mounts" v, err := os.Open(file) if err != nil { fmt.Printf("Failed to open %s: %v", file, err) return "", err } scanner := bufio.NewScanner(v) // leading slash on device to avoid matching things like "rootfs" r := regexp.MustCompile(`^(?P<device>/\S+) (?P<mount>\S+) `) for scanner.Scan() { result := r.FindStringSubmatch(scanner.Text()) if len(result) > 1 { if result[2] == mount { println ("fDFM: found device", result[1], " mount ", result[2]) device = result[1] } } } if device == "" { return device, fmt.Errorf("No device found for mount %s", mount) } return device, nil } func verifyInstance(instance string) (string, error) { // if there's no instance specified, go look it up in metadata //if instance == "" && { return "", nil }
package main import ( // "bufio" // "fmt" // "os" // "regexp" ) func findDeviceFromMount (mount string) (string, error) { // stub for Mac devel return "/dev/xvda", nil /* var device string = "" // Serious Linux-only stuff happening here... file := "/proc/mounts" v, err := os.Open(file) if err != nil { fmt.Printf("Failed to open %s: %v", file, err) return "", err } scanner := bufio.NewScanner(v) // leading slash on device to avoid matching things like "rootfs" r := regexp.MustCompile(`^(?P<device>/\S+) (?P<mount>\S+) `) for scanner.Scan() { result := r.FindStringSubmatch(scanner.Text()) if len(result) > 1 { if result[2] == mount { println ("fDFM: found device", result[1], " mount ", result[2]) device = result[1] } } } if device == "" { return device, fmt.Errorf("No device found for mount %s", mount) } return device, nil */ } func verifyInstance(instance string) (string, error) { // if there's no instance specified, go look it up in metadata //if instance == "" && { return "", nil }
Fix the DeployResources() call args.
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package resourceadapters import ( "github.com/juju/errors" "gopkg.in/juju/charm.v6-unstable" charmresource "gopkg.in/juju/charm.v6-unstable/resource" "github.com/juju/juju/api" "github.com/juju/juju/resource/cmd" ) // DeployResources uploads the bytes for the given files to the server and // creates pending resource metadata for the all resource mentioned in the // metadata. It returns a map of resource name to pending resource IDs. func DeployResources(serviceID string, files map[string]string, resources map[string]charmresource.Meta, conn api.Connection) (ids map[string]string, err error) { client, err := newAPIClient(conn) if err != nil { return nil, errors.Trace(err) } var cURL *charm.URL ids, err = cmd.DeployResources(cmd.DeployResourcesArgs{ ServiceID: serviceID, CharmURL: cURL, Specified: files, ResourcesMeta: resources, Client: client, }) if err != nil { return nil, errors.Trace(err) } return ids, nil }
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package resourceadapters import ( "github.com/juju/errors" charmresource "gopkg.in/juju/charm.v6-unstable/resource" "github.com/juju/juju/api" "github.com/juju/juju/resource/cmd" ) // DeployResources uploads the bytes for the given files to the server and // creates pending resource metadata for the all resource mentioned in the // metadata. It returns a map of resource name to pending resource IDs. func DeployResources(serviceID string, files map[string]string, resources map[string]charmresource.Meta, conn api.Connection) (ids map[string]string, err error) { client, err := newAPIClient(conn) if err != nil { return nil, errors.Trace(err) } ids, err = cmd.DeployResources(serviceID, files, resources, client) if err != nil { return nil, errors.Trace(err) } return ids, nil }
Revert "style for None option button on picklists" This reverts commit d46c7325118f53f24ef8e969a01b0673a384a758.
/// <reference path="../../../../../argos-sdk/libraries/ext/ext-core-debug.js"/> /// <reference path="../../../../../argos-sdk/libraries/sdata/sdata-client-debug"/> /// <reference path="../../../../../argos-sdk/libraries/Simplate.js"/> /// <reference path="../../../../../argos-sdk/src/View.js"/> /// <reference path="../../../../../argos-sdk/src/List.js"/> Ext.namespace("Mobile.SalesLogix.Owner"); (function() { Mobile.SalesLogix.Owner.List = Ext.extend(Sage.Platform.Mobile.List, { //Templates contentTemplate: new Simplate([ '<h3>{%: $.OwnerDescription %}</h3>' ]), //Localization titleText: 'Owners', //View Properties icon: 'content/images/Accounts_24x24.gif', id: 'owner_list', queryOrderBy: 'OwnerDescription', querySelect: [ 'OwnerDescription' ], resourceKind: 'owners', formatSearchQuery: function(query) { return String.format('upper(OwnerDescription) like "%{0}%"', this.escapeSearchQuery(query.toUpperCase())); } }); })();
/// <reference path="../../../../../argos-sdk/libraries/ext/ext-core-debug.js"/> /// <reference path="../../../../../argos-sdk/libraries/sdata/sdata-client-debug"/> /// <reference path="../../../../../argos-sdk/libraries/Simplate.js"/> /// <reference path="../../../../../argos-sdk/src/View.js"/> /// <reference path="../../../../../argos-sdk/src/List.js"/> Ext.namespace("Mobile.SalesLogix.Owner"); (function() { Mobile.SalesLogix.Owner.List = Ext.extend(Sage.Platform.Mobile.List, { //Templates contentTemplate: new Simplate([ '<h3>{%: $.OwnerDescription %}</h3>' ]), //Localization titleText: 'Owners', //View Properties icon: 'content/images/Accounts_24x24.gif', id: 'owner_list', queryOrderBy: 'OwnerDescription', querySelect: [ 'OwnerDescription' ], resourceKind: 'owners', hasNoneOption: true, formatSearchQuery: function(query) { return String.format('upper(OwnerDescription) like "%{0}%"', this.escapeSearchQuery(query.toUpperCase())); } }); })();
Mark event enrichment as func. interface
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.enrich; import com.google.protobuf.Message; import io.spine.base.EventMessage; import io.spine.core.EventContext; /** * Base interface for event enrichment functions. * * @param <M> the type of the event message * @param <E> the type of the enrichment message */ @FunctionalInterface public interface EventEnrichmentFn<M extends EventMessage, E extends Message> extends EnrichmentFn<M, EventContext, E> { }
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.enrich; import com.google.protobuf.Message; import io.spine.base.EventMessage; import io.spine.core.EventContext; /** * Base interface for event enrichment functions. * * @param <M> the type of the event message * @param <E> the type of the enrichment message */ public interface EventEnrichmentFn<M extends EventMessage, E extends Message> extends EnrichmentFn<M, EventContext, E> { }
Install lib package and script
""" Setup script for PyPI """ from setuptools import setup from yayson import VERSION setup( name='yayson', version=VERSION, license='Apache License, Version 2.0', description='Get colorized and indented JSON in the terminal', author='Sebastian Dahlgren', author_email='sebastian.dahlgren@gmail.com', url='http://sebdah.github.com/yayson/', keywords="color colorized json indented beautiful pretty", platforms=['Any'], scripts=['yayson.py'], package_dir={'': '.'}, packages=['.'], include_package_data=True, zip_safe=False, install_requires=[ 'colorama >= 0.2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python' ] )
""" Setup script for PyPI """ from setuptools import setup from yayson import VERSION setup( name='yayson', version=VERSION, license='Apache License, Version 2.0', description='Get colorized and indented JSON in the terminal', author='Sebastian Dahlgren', author_email='sebastian.dahlgren@gmail.com', url='http://sebdah.github.com/yayson/', keywords="color colorized json indented beautiful pretty", platforms=['Any'], package_dir={'yayson': '.'}, scripts=['yayson.py'], include_package_data=True, zip_safe=False, install_requires=[ 'colorama >= 0.2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python' ] )
Remove unused require of react
'use strict'; var path = require('path'), navigateAction = require('flux-router-component').navigateAction, bodyParser = require('body-parser'), express = require('express'), server = express(), morgan = require('morgan'), logger = require('./logger'), renderOnServer = require('./lib/renderOnServer'), errorHandler = require('./middleware/errorHandler'), IsomorphicApp = require('../shared/IsomorphicApp'), isomorphicApp; isomorphicApp = IsomorphicApp.createIsomorphicApp(); server.use(morgan('dev')); server.use('/public', express.static(path.join(__dirname, '../build/'))); server.use(bodyParser.json()); server.use(errorHandler); server.get('*', applicationRouteHandler); function applicationRouteHandler(req, res, next) { var context = isomorphicApp.createContext(); context.executeAction(navigateAction, { url: req.url }, function (error) { var html; if (error) { return next(error); } html = renderOnServer(isomorphicApp); res.write('<!DOCTYPE html>'); res.write(html); res.end(); }); } module.exports = server;
'use strict'; var path = require('path'), React = require('react'), navigateAction = require('flux-router-component').navigateAction, bodyParser = require('body-parser'), express = require('express'), server = express(), morgan = require('morgan'), logger = require('./logger'), renderOnServer = require('./lib/renderOnServer'), errorHandler = require('./middleware/errorHandler'), IsomorphicApp = require('../shared/IsomorphicApp'), isomorphicApp; isomorphicApp = IsomorphicApp.createIsomorphicApp(); server.use(morgan('dev')); server.use('/public', express.static(path.join(__dirname, '../build/'))); server.use(bodyParser.json()); server.use(errorHandler); server.get('*', applicationRouteHandler); function applicationRouteHandler(req, res, next) { var context = isomorphicApp.createContext(); context.executeAction(navigateAction, { url: req.url }, function (error) { var html; if (error) { return next(error); } html = renderOnServer(isomorphicApp); res.write('<!DOCTYPE html>'); res.write(html); res.end(); }); } module.exports = server;
gwt: Use new services.py reply format for login().
package ro.pub.cs.vmchecker.client.service.json; import ro.pub.cs.vmchecker.client.model.AuthenticationResponse; import ro.pub.cs.vmchecker.client.model.User; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; public class AuthenticationResponseDecoder implements JSONDecoder<AuthenticationResponse> { public static final String statusKey = "status"; public static final String fullnameKey = "fullname"; public static final String usernameKey = "username"; public static final String infoKey = "info"; @Override public AuthenticationResponse decode(String text) throws Exception { JSONValue jsonValue = JSONParser.parse(text); JSONObject jsonObj = jsonValue.isObject(); boolean status = jsonObj.get(statusKey).isBoolean().booleanValue(); String info = jsonObj.get(infoKey).isString().stringValue(); if (!status) { /* * Authentication failed. */ return new AuthenticationResponse(status, null, info); } String username = jsonObj.get(usernameKey).isString().stringValue(); String fullname = jsonObj.get(fullnameKey).isString().stringValue(); return new AuthenticationResponse(status, new User(username, fullname), info); } }
package ro.pub.cs.vmchecker.client.service.json; import ro.pub.cs.vmchecker.client.model.AuthenticationResponse; import ro.pub.cs.vmchecker.client.model.User; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; public class AuthenticationResponseDecoder implements JSONDecoder<AuthenticationResponse> { public static final String statusKey = "status"; public static final String usernameKey = "username"; public static final String useridKey = "userid"; public static final String infoKey = "info"; @Override public AuthenticationResponse decode(String text) throws Exception { JSONValue jsonValue = JSONParser.parse(text); JSONObject jsonObj = jsonValue.isObject(); boolean status = jsonObj.get(statusKey).isBoolean().booleanValue(); String info = jsonObj.get(infoKey).isString().stringValue(); if (!status) { /* * Authentication failed. */ return new AuthenticationResponse(status, null, info); } String username = jsonObj.get(usernameKey).isString().stringValue(); String userid = jsonObj.get(useridKey).isString().stringValue(); return new AuthenticationResponse(status, new User(userid, username), info); } }
Fix the track number for the Track model
define(function(require, exports, module) { var uuid = require("lib/uuid"); function Track(options) { this.id = options.id || options._id; this._id = options.id || options._id; this.title = options.title; this.album = options.album; this.artist = options.artist; this.track = options.track; this.data = options.data; this.hash = options.hash; this.artistId = options.artistId || null; this.albumId = options.albumId || null; } Track.id = uuid; Track.prototype = { toFile: function() { return new Blob([this.data], {type: "audio/mpeg"}); }, hashCode: function() { return parseInt(this.hash.slice(this.hash.length - 8), 16); }, equals: function(other) { return this.hash === other.hash; } }; return { Track: Track, } });
define(function(require, exports, module) { var uuid = require("lib/uuid"); function Track(options) { this.id = options.id || options._id; this._id = options.id || options._id; this.title = options.title; this.album = options.album; this.artist = options.artist; this.data = options.data; this.hash = options.hash; this.artistId = options.artistId || null; this.albumId = options.albumId || null; } Track.id = uuid; Track.prototype = { toFile: function() { return new Blob([this.data], {type: "audio/mpeg"}); }, hashCode: function() { return parseInt(this.hash.slice(this.hash.length - 8), 16); }, equals: function(other) { return this.hash === other.hash; } }; return { Track: Track, } });
Fix bug in integer matrix
/* * Copyright 2010-2015 Allette Systems (Australia) * http://www.allette.com.au * * 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 org.pageseeder.diffx.algorithm; /** * A matrix implementation which backbone is a matrix of integers. * * @author Christophe Lauret (Allette Systems) * @version 0.9.0 */ public final class MatrixInt extends MatrixIntBase { @Override public void incrementPath(int i, int j) { this.matrix[i][j] = this.matrix[i - 1][j - 1] + 1; } @Override public void incrementByMaxPath(int i, int j) { this.matrix[i][j] = Math.max(this.matrix[i - 1][j], this.matrix[i][j - 1]); } public int getLCSLength() { return this.get(this.matrix.length - 1, this.matrix[0].length - 1); } }
/* * Copyright 2010-2015 Allette Systems (Australia) * http://www.allette.com.au * * 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 org.pageseeder.diffx.algorithm; /** * A matrix implementation which backbone is a matrix of integers. * * @author Christophe Lauret (Allette Systems) * @version 0.9.0 */ public final class MatrixInt extends MatrixIntBase { @Override public void incrementPath(int i, int j) { this.matrix[i][j] = this.matrix[i - 1][j - 1]; } @Override public void incrementByMaxPath(int i, int j) { this.matrix[i][j] = Math.max(this.matrix[i - 1][j], this.matrix[i][j - 1]); } public int getLCSLength() { return this.get(this.matrix.length - 1, this.matrix[0].length - 1); } }
Update freestyle version to 0.3.3.
/******************************************************************************* * Copyright 2012-present Pixate, Inc. * * 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.pixate.freestyle; /** * Holds version information. This info, for example, is being used with the * pings. * * @author Shalom Gibly */ public interface Version { public static String PIXATE_FREESTYLE_VERSION = "0.3.3"; public static int PIXATE_FREESTYLE_API_VERSION = 2; }
/******************************************************************************* * Copyright 2012-present Pixate, Inc. * * 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.pixate.freestyle; /** * Holds version information. This info, for example, is being used with the * pings. * * @author Shalom Gibly */ public interface Version { public static String PIXATE_FREESTYLE_VERSION = "0.3.2"; public static int PIXATE_FREESTYLE_API_VERSION = 2; }
Make sure getBeanFactory() is available in access traits.
<?php namespace ampf\skeleton\beanAccess\repos; use \ampf\skeleton\doctrine\repositories\Test; trait Test { protected $__testRepository = null; /** * @return Test */ public function getTestRepository() { if ($this->__testRepository === null) { $this->setTestRepository( $this->getBeanFactory()->get( 'Doctrine.Repository.Test', function(\ampf\beans\BeanFactory $beanFactory, array &$beanConfig) { return $beanFactory ->get('EntityManagerFactory') ->get() ->getRepository('\ampf\skeleton\doctrine\entities\Test'); } ) ); } return $this->__testRepository; } /** * @param Test $testRepository */ public function setTestRepository(Test $testRepository) { $this->__testRepository = $testRepository; } /** * @return \ampf\beans\BeanFactory */ abstract public function getBeanFactory(); }
<?php namespace ampf\skeleton\beanAccess\repos; use \ampf\skeleton\doctrine\repositories\Test; trait Test { protected $__testRepository = null; /** * @return Test */ public function getTestRepository() { if ($this->__testRepository === null) { $this->setTestRepository( $this->getBeanFactory()->get( 'Doctrine.Repository.Test', function(\ampf\beans\BeanFactory $beanFactory, array &$beanConfig) { return $beanFactory ->get('EntityManagerFactory') ->get() ->getRepository('\ampf\skeleton\doctrine\entities\Test'); } ) ); } return $this->__testRepository; } /** * @param Test $testRepository */ public function setTestRepository(Test $testRepository) { $this->__testRepository = $testRepository; } }
Set djangorestframework as a install requirement
# -*- coding: utf-8 -*8- from setuptools import setup, find_packages from todomvc import version setup( name='django-todomvc', version=version.to_str(), description='TodoMVC django app', author='Adones Cunha', author_email='adonescunha@gmail.com', url='https://github.com/adonescunha/django-todomvc', packages=find_packages(exclude=['tests']), package_data={ 'todomvc': [ ], }, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', ], install_requires=[ 'djangorestframework' ], zip_safe=False, )
# -*- coding: utf-8 -*8- from setuptools import setup, find_packages from todomvc import version setup( name='django-todomvc', version=version.to_str(), description='TodoMVC django app', author='Adones Cunha', author_email='adonescunha@gmail.com', url='https://github.com/adonescunha/django-todomvc', packages=find_packages(exclude=['tests']), package_data={ 'todomvc': [ ], }, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', ] install_requires=[ ], zip_safe=False, )
Fix mapping file for zh_Hant
<?php namespace libphonenumber\prefixmapper; /** * A utility which knows the data files that are available for the phone prefix mappers to use. * The data files contain mappings from phone number prefixes to text descriptions, and are * organized by country calling code and language that the text descriptions are in. * * Class MappingFileProvider * @package libphonenumber\prefixmapper */ class MappingFileProvider { private $map; public function __construct($map) { $this->map = $map; } public function getFileName($countryCallingCode, $language, $script, $region) { if (strlen($language) == 0) { return ""; } if ($language === 'zh' && ($region == 'TW' || $region == 'HK' || $region == 'MO')) { $language = 'zh_Hant'; } if ($this->inMap($language, $countryCallingCode)) { return $language . DIRECTORY_SEPARATOR . $countryCallingCode . '.php'; } return ""; } private function inMap($language, $countryCallingCode) { return (array_key_exists($language, $this->map) && in_array($countryCallingCode, $this->map[$language])); } }
<?php namespace libphonenumber\prefixmapper; /** * A utility which knows the data files that are available for the phone prefix mappers to use. * The data files contain mappings from phone number prefixes to text descriptions, and are * organized by country calling code and language that the text descriptions are in. * * Class MappingFileProvider * @package libphonenumber\prefixmapper */ class MappingFileProvider { private $map; public function __construct($map) { $this->map = $map; } public function getFileName($countryCallingCode, $language, $script, $region) { if (strlen($language) == 0) { return ""; } if ($this->inMap($language, $countryCallingCode)) { return $language . DIRECTORY_SEPARATOR . $countryCallingCode . '.php'; } return ""; } private function inMap($language, $countryCallingCode) { return (array_key_exists($language, $this->map) && in_array($countryCallingCode, $this->map[$language])); } }
Add functions to generate timestamp for logfiles & filenames; use localtimezone
import datetime from time import gmtime, strftime import pytz #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time #http://www.epochconverter.com/ #1/6/2015, 8:19:34 AM PST -> 23 hours ago #print HTM(1420561174000/1000) def HTM(aa): a = int(aa) b = int(datetime.datetime.now().strftime("%s")) c = b - a days = c // 86400 hours = c // 3600 % 24 minutes = c // 60 % 60 seconds = c % 60 ago = "ago" if (days > 0): return ( str(days) + " days " + ago) elif (hours > 0): return (str(hours) + " hours " + ago) elif (minutes > 0): return ( str(minutes) + " minutes " + ago) elif (seconds > 0): return (str(seconds) + " seconds " + ago) else: return (a) #Error #My Timestamp used in logfile def MT(): fmt = '%Y-%m-%d %H:%M:%S' return (datetime.datetime.now(pytz.timezone("America/Los_Angeles")).strftime(fmt)) #My Timestamp for filename def FT(): fmt = '%d%b%Y-%H%M%S' return ( datetime.datetime.now(pytz.timezone("America/Los_Angeles")).strftime(fmt) )
import datetime #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time def HTM(aa): a = int(aa) b = int(datetime.datetime.now().strftime("%s")) c = b - a days = c // 86400 hours = c // 3600 % 24 minutes = c // 60 % 60 seconds = c % 60 ago = "ago" if (days > 0): return ( str(days) + " days " + ago) elif (hours > 0): return (str(hours) + " hours " + ago) elif (minutes > 0): return ( str(minutes) + " minutes " + ago) elif (seconds > 0): return (str(seconds) + " seconds " + ago) else: return (a) #Error #http://www.epochconverter.com/ #1/6/2015, 8:19:34 AM PST -> 23 hours ago #print HTM(1420561174000/1000)
Add rest_to_html_fragment to be able to convert just the body part
# -*- coding: utf-8 -*- """ flaskjk.restconverter ~~~~~~~~~~~~~~~~~~~~~ Helper functions for converting RestructuredText This class heavily depends on the functionality provided by the docutils package. See http://wiki.python.org/moin/ReStructuredText for more information :copyright: (c) 2010 by Jochem Kossen. :license: BSD, see LICENSE for more details. """ from docutils import core from docutils.writers.html4css1 import Writer, HTMLTranslator class HTMLFragmentTranslator(HTMLTranslator): def __init__(self, document): HTMLTranslator.__init__(self, document) self.head_prefix = ['','','','',''] self.body_prefix = [] self.body_suffix = [] self.stylesheet = [] def astext(self): return ''.join(self.body) html_fragment_writer = Writer() html_fragment_writer.translator_class = HTMLFragmentTranslator def rest_to_html(s): """Convert ReST input to HTML output""" return core.publish_string(s, writer=html_fragment_writer) def rest_to_html_fragment(s): parts = core.publish_parts( source=s, writer_name='html') return parts['body_pre_docinfo']+parts['fragment']
# -*- coding: utf-8 -*- """ flaskjk.restconverter ~~~~~~~~~~~~~~~~~~~~~ Helper functions for converting RestructuredText This class heavily depends on the functionality provided by the docutils package. :copyright: (c) 2010 by Jochem Kossen. :license: BSD, see LICENSE for more details. """ from docutils import core from docutils.writers.html4css1 import Writer, HTMLTranslator class HTMLFragmentTranslator(HTMLTranslator): def __init__(self, document): HTMLTranslator.__init__(self, document) self.head_prefix = ['','','','',''] self.body_prefix = [] self.body_suffix = [] self.stylesheet = [] def astext(self): return ''.join(self.body) html_fragment_writer = Writer() html_fragment_writer.translator_class = HTMLFragmentTranslator def rest_to_html(s): """Convert ReST input to HTML output""" return core.publish_string(s, writer=html_fragment_writer)
Allow registering additional extensions for container
<?php namespace Yolo; use Symfony\Component\DependencyInjection\ContainerBuilder; use Yolo\DependencyInjection\YoloExtension; use Yolo\Compiler\EventSubscriberPass; class Factory { public static function createContainer(array $parameters = [], array $extensions = []) { $container = new ContainerBuilder(); $container->registerExtension(new YoloExtension()); foreach ($extensions as $extension) { $container->registerExtension($extension); } $container->getParameterBag()->add($parameters); foreach ($container->getExtensions() as $extension) { $container->loadFromExtension($extension->getAlias()); } $container->addCompilerPass(new EventSubscriberPass()); $container->compile(); return $container; } }
<?php namespace Yolo; use Symfony\Component\DependencyInjection\ContainerBuilder; use Yolo\DependencyInjection\YoloExtension; use Yolo\Compiler\EventSubscriberPass; class Factory { public static function createContainer(array $parameters = []) { $container = new ContainerBuilder(); $container->registerExtension(new YoloExtension()); $container->getParameterBag()->add($parameters); foreach ($container->getExtensions() as $extension) { $container->loadFromExtension($extension->getAlias()); } $container->addCompilerPass(new EventSubscriberPass()); $container->compile(); return $container; } }
Make the test window bigger in Java.
/** * Copyright 2010 The PlayN Authors * * 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 playn.tests.java; import playn.core.PlayN; import playn.java.JavaPlatform; import playn.tests.core.TestsGame; public class TestsGameJava { public static void main(String[] args) { JavaPlatform.Config config = new JavaPlatform.Config(); if (args.length > 0) { config.scaleFactor = Float.parseFloat(args[0]); } config.width = 800; config.height = 600; JavaPlatform platform = JavaPlatform.register(config); platform.setTitle("Tests"); PlayN.run(new TestsGame()); } }
/** * Copyright 2010 The PlayN Authors * * 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 playn.tests.java; import playn.core.PlayN; import playn.java.JavaPlatform; import playn.tests.core.TestsGame; public class TestsGameJava { public static void main(String[] args) { JavaPlatform.Config config = new JavaPlatform.Config(); if (args.length > 0) { config.scaleFactor = Float.parseFloat(args[0]); } JavaPlatform platform = JavaPlatform.register(config); platform.setTitle("Tests"); PlayN.run(new TestsGame()); } }
Print out the unsupported object when encountered.
// Load the node-ffi extensions require('./ffi-extend') // The main exports is the casting function module.exports = $ $._ = $ // legacy. TODO: remove by 0.1.0 // export the exports from the 'import' module var Import = require('./import') $.import = Import.import $.resolve = Import.resolve // This function accepts native JS types (String, Number, Date) and converts them // to the proper Objective-C type (NSString, NSNumber, NSDate). // Syntax Sugar... function $ (o) { var t = typeof o if (t == 'string') { return $.NSString('stringWithUTF8String', String(o)) } else if (t == 'number') { return $.NSNumber('numberWithDouble', Number(o)) } else if (isDate(o)) { return $.NSDate('dateWithTimeIntervalSince1970', o / 1000) } throw new Error('Unsupported object passed in to convert: ' + o) } function isDate (d) { return d instanceof Date || Object.prototype.toString.call(d) == '[object Date]' }
// Load the node-ffi extensions require('./ffi-extend') // The main exports is the casting function module.exports = $ $._ = $ // legacy. TODO: remove by 0.1.0 // export the exports from the 'import' module var Import = require('./import') $.import = Import.import $.resolve = Import.resolve // This function accepts native JS types (String, Number, Date) and converts them // to the proper Objective-C type (NSString, NSNumber, NSDate). // Syntax Sugar... function $ (o) { var t = typeof o if (t == 'string') { return $.NSString('stringWithUTF8String', String(o)) } else if (t == 'number') { return $.NSNumber('numberWithDouble', Number(o)) } else if (isDate(o)) { return $.NSDate('dateWithTimeIntervalSince1970', o / 1000) } throw new Error('Unsupported object passed in to convert') } function isDate (d) { return d instanceof Date || Object.prototype.toString.call(d) == '[object Date]' }
Update str() and add comments
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
Add gulp status on script build
const browserify = require('browserify'); const watchify = require('watchify'); const gulp = require('gulp'); const $ = require('gulp-load-plugins')(); const config = require('../config'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); let bundler = browserify(config.scripts.sources) .transform('babelify', { presets: ['es2015'] }) .transform('stringify', { appliesTo: { includeExtensions: ['.html'] }, }) .transform('browserify-ngannotate') .transform('browserify-css'); function bundle() { const stream = bundler.bundle() .pipe($.plumber()) .pipe(source(`${config.scripts.destinationName}.js`)) .pipe(buffer()) .pipe(gulp.dest(config.dist)); if (config.production) { stream .pipe($.sourcemaps.init({ loadMaps: true, })) .pipe($.uglify()) .pipe($.rename({ extname: '.min.js', })) .pipe($.rev()) .pipe($.sourcemaps.write('./')) .pipe(gulp.dest(config.dist)); } stream.pipe($.connect.reload()); return stream; } gulp.task('build:scripts', bundle); gulp.task('watch:scripts', () => { bundler = watchify(bundler); bundler.on('update', () => gulp.start('build:scripts')); });
const browserify = require('browserify'); const watchify = require('watchify'); const gulp = require('gulp'); const $ = require('gulp-load-plugins')(); const config = require('../config'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); let bundler = browserify(config.scripts.sources) .transform('babelify', { presets: ['es2015'] }) .transform('stringify', { appliesTo: { includeExtensions: ['.html'] }, }) .transform('browserify-ngannotate') .transform('browserify-css'); function bundle() { const stream = bundler.bundle() .pipe($.plumber()) .pipe(source(`${config.scripts.destinationName}.js`)) .pipe(buffer()) .pipe(gulp.dest(config.dist)); if (config.production) { stream .pipe($.sourcemaps.init({ loadMaps: true, })) .pipe($.uglify()) .pipe($.rename({ extname: '.min.js', })) .pipe($.rev()) .pipe($.sourcemaps.write('./')) .pipe(gulp.dest(config.dist)); } stream.pipe($.connect.reload()); return stream; } gulp.task('build:scripts', bundle); gulp.task('watch:scripts', () => { bundler = watchify(bundler); bundler.on('update', bundle); });
Change default eventually timeout to 1 minute [#126989119] Signed-off-by: Chris Piraino <f047703f03f13cc8e1b226aa8ba85c2dfc238f94@pivotal.io>
package helpers import ( "os" "time" "github.com/onsi/gomega" ) var DEFAULT_EVENTUALLY_TIMEOUT = 1 * time.Minute var DEFAULT_CONSISTENTLY_DURATION = 5 * time.Second func RegisterDefaultTimeouts() { var err error if os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT") != "" { DEFAULT_EVENTUALLY_TIMEOUT, err = time.ParseDuration(os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT")) if err != nil { panic(err) } } if os.Getenv("DEFAULT_CONSISTENTLY_DURATION") != "" { DEFAULT_CONSISTENTLY_DURATION, err = time.ParseDuration(os.Getenv("DEFAULT_CONSISTENTLY_DURATION")) if err != nil { panic(err) } } gomega.SetDefaultEventuallyTimeout(DEFAULT_EVENTUALLY_TIMEOUT) gomega.SetDefaultConsistentlyDuration(DEFAULT_CONSISTENTLY_DURATION) // most things hit some component; don't hammer it gomega.SetDefaultConsistentlyPollingInterval(100 * time.Millisecond) gomega.SetDefaultEventuallyPollingInterval(500 * time.Millisecond) }
package helpers import ( "os" "time" "github.com/onsi/gomega" ) var DEFAULT_EVENTUALLY_TIMEOUT = 2 * time.Minute var DEFAULT_CONSISTENTLY_DURATION = 5 * time.Second func RegisterDefaultTimeouts() { var err error if os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT") != "" { DEFAULT_EVENTUALLY_TIMEOUT, err = time.ParseDuration(os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT")) if err != nil { panic(err) } } if os.Getenv("DEFAULT_CONSISTENTLY_DURATION") != "" { DEFAULT_CONSISTENTLY_DURATION, err = time.ParseDuration(os.Getenv("DEFAULT_CONSISTENTLY_DURATION")) if err != nil { panic(err) } } gomega.SetDefaultEventuallyTimeout(DEFAULT_EVENTUALLY_TIMEOUT) gomega.SetDefaultConsistentlyDuration(DEFAULT_CONSISTENTLY_DURATION) // most things hit some component; don't hammer it gomega.SetDefaultConsistentlyPollingInterval(100 * time.Millisecond) gomega.SetDefaultEventuallyPollingInterval(500 * time.Millisecond) }
Fix module name for UMD
import rollupBabel from "rollup-plugin-babel"; const pkg = require("./package.json"); export default { entry: "src/index.js", plugins: [ rollupBabel({ babelrc: false, presets: [ ["env", { modules: false }], "stage-3" ] }) ], targets: [ { dest: pkg.main, format: "umd", moduleName: "TileTools", sourceMap: true }, { dest: pkg.module, format: "es", sourceMap: true } ] };
import rollupBabel from "rollup-plugin-babel"; const pkg = require("./package.json"); export default { entry: "src/index.js", plugins: [ rollupBabel({ babelrc: false, presets: [ ["env", { modules: false }], "stage-3" ] }) ], targets: [ { dest: pkg.main, format: "umd", moduleName: "dtileTilemap", sourceMap: true }, { dest: pkg.module, format: "es", sourceMap: true } ] };
Fix aspect dropdown on people search page inserted after initial page load
// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later var List = { runDelayedSearch: function( searchTerm ) { $.getJSON('/people/refresh_search', { q: searchTerm }, List.handleSearchRefresh ); }, handleSearchRefresh: function( data ) { var streamEl = $("#people_stream.stream"); var string = data.search_html || $("<p>", { text : Diaspora.I18n.t("people.not_found") }); streamEl.html(string); $('.aspect_membership_dropdown').each(function(){ new app.views.AspectMembership({el: this}); }); }, startSearchDelay: function (theSearch) { setTimeout( "List.runDelayedSearch('" + theSearch + "')", 10000); } }; // @license-end
// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later var List = { runDelayedSearch: function( searchTerm ) { $.getJSON('/people/refresh_search', { q: searchTerm }, List.handleSearchRefresh ); }, handleSearchRefresh: function( data ) { var streamEl = $("#people_stream.stream"); var string = data.search_html || $("<p>", { text : Diaspora.I18n.t("people.not_found") }); streamEl.html(string); }, startSearchDelay: function (theSearch) { setTimeout( "List.runDelayedSearch('" + theSearch + "')", 10000); } }; // @license-end
Make notices.hide_after column retain timezone information
<?php use Phinx\Migration\AbstractMigration; use Phinx\Util\Literal; class CreateNoticesTable extends AbstractMigration { public function change() { $this->table('notices', ['id' => false, 'primary_key' => 'id']) ->addColumn('id', 'uuid', ['default' => Literal::from('uuid_generate_v4()')]) ->addColumn('message_html', 'string', ['length' => 500]) ->addColumn('type', 'string', ['length' => 16]) ->addColumn('posted_by', 'uuid') ->addTimestamps(null, null, true) ->addColumn('hide_after', 'timestamp', ['timezone' => true]) ->addForeignKey('posted_by', 'users', 'id', ['update' => 'CASCADE', 'delete' => 'RESTRICT']) ->addIndex('posted_by') ->create(); } }
<?php use Phinx\Migration\AbstractMigration; use Phinx\Util\Literal; class CreateNoticesTable extends AbstractMigration { public function change() { $this->table('notices', ['id' => false, 'primary_key' => 'id']) ->addColumn('id', 'uuid', ['default' => Literal::from('uuid_generate_v4()')]) ->addColumn('message_html', 'string', ['length' => 500]) ->addColumn('type', 'string', ['length' => 16]) ->addColumn('posted_by', 'uuid') ->addTimestamps(null, null, true) ->addColumn('hide_after', 'timestamp') ->addForeignKey('posted_by', 'users', 'id', ['update' => 'CASCADE', 'delete' => 'RESTRICT']) ->addIndex('posted_by') ->create(); } }
Define inserts and deletes on CFs.
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name self.ROWS = set() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: self.ROWS.add(column) return True except: return False def __repr__(self): return '<%r>' % self.name
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name pass def insert(self, Column): pass def get(self, key): # NOTE: Check for tombstones / TTL here pass def delete(self, key): # NOTE: Really an insert with a tombstone insert(key, tombstone=True) pass def __repr__(self): return '<%r>' % self.name
Update fcn to get an object's native class
'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var RE = require( '@stdlib/regex/function-name' ); var isBuffer = require( '@stdlib/utils/is-buffer' ); // CONSTRUCTOR NAME // /** * FUNCTION: constructorName( v ) * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {String} name of a value's constructor */ function constructorName( v ) { var name; var ctor; name = nativeClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } return RE.exec( ctor.toString() )[ 1 ]; } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // end FUNCTION constructorName() // EXPORTS // module.exports = constructorName;
'use strict'; // MODULES // var specificationClass = require( '@stdlib/utils/specification-class' ); var RE = require( '@stdlib/regex/function-name' ); var isBuffer = require( '@stdlib/utils/is-buffer' ); // CONSTRUCTOR NAME // /** * FUNCTION: constructorName( v ) * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {String} name of a value's constructor */ function constructorName( v ) { var name; var ctor; name = specificationClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } return RE.exec( ctor.toString() )[ 1 ]; } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // end FUNCTION constructorName() // EXPORTS // module.exports = constructorName;
Add more options to Slack notifier phase
package phases import ( "github.com/Everlane/evan/common" "github.com/nlopes/slack" ) type SlackNotifierPhase struct { Client *slack.Client Channel string Format func(common.Deployment) (*string, *slack.PostMessageParameters, error) } func (snp *SlackNotifierPhase) CanPreload() bool { return false } func (snp *SlackNotifierPhase) Execute(deployment common.Deployment, _ interface{}) error { message, params, err := snp.Format(deployment) if err != nil { return err } // Don't send a message to Slack if the format function didn't return // a message to send if message == nil { return nil } if params == nil { defaultParams := slack.NewPostMessageParameters() params = &defaultParams } _, _, err = snp.Client.PostMessage(snp.Channel, *message, *params) if err != nil { return err } return nil }
package phases import ( "github.com/Everlane/evan/common" "github.com/nlopes/slack" ) type SlackNotifierPhase struct { Client *slack.Client Channel string Format func(common.Deployment) (string, error) } func (snp *SlackNotifierPhase) CanPreload() bool { return false } func (snp *SlackNotifierPhase) Execute(deployment common.Deployment, _ interface{}) error { message, err := snp.Format(deployment) if err != nil { return err } // If the `Format` function returned an empty strings that means we // shouldn't send a message to Slack. if message == "" { return nil } params := slack.NewPostMessageParameters() _, _, err = snp.Client.PostMessage(snp.Channel, message, params) if err != nil { return err } return nil }
Fix for links color in latest posts block
<?php /** * @package Last_posts * @category blocks * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2014-2016, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs\modules\Blogs; use h; $Posts = Posts::instance(); $posts = $Posts->get( $Posts->get_latest_posts(1, 5) ); /** * @var array $block */ echo h::{'div.cs-side-block'}( h::a( h::h3($block['title']), [ 'href' => 'Blogs' ] ). h::{'section.cs-blocks-last-posts article'}( array_map( function ($post) { return h::a( h::h3($post['title']), [ 'href' => "Blogs/$post[path]:$post[id]" ] ). h::p( truncate($post['content'], 200) ); }, $posts ) ) );
<?php /** * @package Last_posts * @category blocks * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2014-2016, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs\modules\Blogs; use h; $Posts = Posts::instance(); $posts = $Posts->get( $Posts->get_latest_posts(1, 5) ); /** * @var array $block */ echo h::{'div.cs-side-block'}( h::{'h3 a'}( $block['title'], [ 'href' => 'Blogs' ] ). h::{'section.cs-blocks-last-posts article'}( array_map( function ($post) { return h::{'h3 a'}( $post['title'], [ 'href' => "Blogs/$post[path]:$post[id]" ] ). h::p( truncate($post['content'], 200) ); }, $posts ) ) );
Update example to generate index.html files
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { App, Home, About, NotFound } from './App.js'; import { Products, Product, ProductColors, ProductColor, } from './Products.js'; export const routes = ( <Route path='/' title='App' component={App}> <IndexRoute component={Home} /> <Route path='products' title='App - Products' component={Products}> <Route path='first/' title='App - Products - First' component={Product} /> <Route path='second/' title='App - Products - Second' component={Product} /> <Route path='third' title='App - Products - Third' component={Product}> <Route path='colors' title='App - Products - Third - Colors' component={ProductColors}> <Route path='green/' title='App - Products - Third - Colors - Green' component={ProductColor} /> <Route path='blue/' title='App - Products - Third - Colors - Blue' component={ProductColor} /> </Route> </Route> </Route> <Route path='about' title='App - About' component={About} /> <Route path='*' title='404: Not Found' component={NotFound} /> </Route> ); export default routes;
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { App, Home, About, NotFound } from './App.js'; import { Products, Product, ProductColors, ProductColor, } from './Products.js'; export const routes = ( <Route path='/' title='App' component={App}> <IndexRoute component={Home} /> <Route path='products' title='App - Products' component={Products}> <Route path='first' title='App - Products - First' component={Product} /> <Route path='second' title='App - Products - Second' component={Product} /> <Route path='third' title='App - Products - Third' component={Product}> <Route path='colors' title='App - Products - Third - Colors' component={ProductColors}> <Route path='green' title='App - Products - Third - Colors - Green' component={ProductColor} /> <Route path='blue' title='App - Products - Third - Colors - Blue' component={ProductColor} /> </Route> </Route> </Route> <Route path='about' title='App - About' component={About} /> <Route path='*' title='404: Not Found' component={NotFound} /> </Route> ); export default routes;
Resolve failing test "should allow string input for execution"
;(function(global, factory) { // Use UMD pattern to expose exported functions if (typeof exports === 'object') { // Expose to Node.js module.exports = factory(); } else if (typeof define === 'function' && define.amd) { // Expose to RequireJS define([], factory); } // Expose to global object (likely browser window) var exports = factory(); for (var prop in exports) { global[prop] = exports[prop]; } }(this, function() { var numIntervals = 0, intervals = {}; var setCorrectingInterval = function(func, delay) { var id = numIntervals++, planned = Date.now() + delay; if (typeof func === 'string') { // Convert string to function func = function() { eval(this.func); }.bind({ func: func }); } function tick() { func(); if (intervals[id]) { planned += delay; intervals[id] = setTimeout(tick, planned - Date.now()); } } intervals[id] = setTimeout(tick, delay); return id; }; var clearCorrectingInterval = function(id) { clearTimeout(intervals[id]); delete intervals[id]; }; return { setCorrectingInterval: setCorrectingInterval, clearCorrectingInterval: clearCorrectingInterval }; }));
;(function(global, factory) { // Use UMD pattern to expose exported functions if (typeof exports === 'object') { // Expose to Node.js module.exports = factory(); } else if (typeof define === 'function' && define.amd) { // Expose to RequireJS define([], factory); } // Expose to global object (likely browser window) var exports = factory(); for (var prop in exports) { global[prop] = exports[prop]; } }(this, function() { var numIntervals = 0, intervals = {}; var setCorrectingInterval = function(func, delay) { var id = numIntervals++, planned = Date.now() + delay; function tick() { func(); if (intervals[id]) { planned += delay; intervals[id] = setTimeout(tick, planned - Date.now()); } } intervals[id] = setTimeout(tick, delay); return id; }; var clearCorrectingInterval = function(id) { clearTimeout(intervals[id]); delete intervals[id]; }; return { setCorrectingInterval: setCorrectingInterval, clearCorrectingInterval: clearCorrectingInterval }; }));
Fix options for check subcommand for staged files and commits
package main import ( "fmt" "github.com/libgit2/git2go" "github.com/urfave/cli" ) func GitSeekretCheck(c *cli.Context) error { err := gs.LoadConfig(true) if git.IsErrorClass(err, git.ErrClassConfig) { return fmt.Errorf("Config not initialised - Try: 'git-seekret config --init'") } if err != nil { return err } options := map[string]interface{}{ "commit-files": false, "staged-files": false, } if c.IsSet("commit") { options["commit-files"] = true options["commit-messages"] = true options["commit-count"] = c.Int("commit") } if c.IsSet("staged") { options["staged-files"] = true } secrets, err := gs.RunCheck(options) if err != nil { return err } if secrets != 0 { return fmt.Errorf("Please remove discovered secrets") } return nil }
package main import ( "fmt" "github.com/libgit2/git2go" "github.com/urfave/cli" ) func GitSeekretCheck(c *cli.Context) error { err := gs.LoadConfig(true) if git.IsErrorClass(err, git.ErrClassConfig) { return fmt.Errorf("Config not initialised - Try: 'git-seekret config --init'") } if err != nil { return err } options := map[string]interface{}{ "commit": false, "staged": false, } if c.IsSet("commit") { options["commit"] = true options["commitcount"] = c.Int("commit") } if c.IsSet("staged") { options["staged"] = true } secrets, err := gs.RunCheck(options) if err != nil { return err } if secrets != 0 { return fmt.Errorf("Please remove discovered secrets") } return nil }
Fix js error: currentType is undefined https://github.com/rancher/rancher/issues/23437
import { get } from '@ember/object'; import { alias } from '@ember/object/computed'; import { inject as service } from '@ember/service'; import Controller from '@ember/controller'; export default Controller.extend({ modalService: service('modal'), globalStore: service(), queryParams: ['type'], currentType: 'slack', notifiers: alias('model.notifiers'), actions: { showNewEditModal() { get(this, 'modalService').toggleModal('notifier/modal-new-edit', { closeWithOutsideClick: false, controller: this, currentType: get(this, 'currentType'), mode: 'add', }); }, }, });
import { get } from '@ember/object'; import { alias } from '@ember/object/computed'; import { inject as service } from '@ember/service'; import Controller from '@ember/controller'; export default Controller.extend({ modalService: service('modal'), globalStore: service(), queryParams: ['type'], currentType: 'slack', notifiers: alias('model.notifiers'), actions: { showNewEditModal() { get(this, 'modalService').toggleModal('notifier/modal-new-edit', { closeWithOutsideClick: false, controller: this, currentType: alias('controller.currentType'), mode: 'add', }); }, }, });
Use filename from css.parse errors. The file we're compiling might not be the same as the file that contains the error.
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var _ = require('lodash'); var rework = require('rework'); var lastIsObject = _.compose(_.isPlainObject, _.last); module.exports = function () { var args = [].slice.call(arguments); var options = lastIsObject(args) ? args.pop() : {}; var plugins = args; return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-rework', 'Streaming not supported')); return cb(); } try { var ret = rework(file.contents.toString(), {source: file.path}); plugins.forEach(ret.use.bind(ret)); file.contents = new Buffer(ret.toString(options)); } catch (err) { this.emit('error', new gutil.PluginError('gulp-rework', err, {fileName: err.filename || file.path})); } this.push(file); cb(); }); };
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var _ = require('lodash'); var rework = require('rework'); var lastIsObject = _.compose(_.isPlainObject, _.last); module.exports = function () { var args = [].slice.call(arguments); var options = lastIsObject(args) ? args.pop() : {}; var plugins = args; return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-rework', 'Streaming not supported')); return cb(); } try { var ret = rework(file.contents.toString(), {source: file.path}); plugins.forEach(ret.use.bind(ret)); file.contents = new Buffer(ret.toString(options)); } catch (err) { this.emit('error', new gutil.PluginError('gulp-rework', err, {fileName: file.path})); } this.push(file); cb(); }); };
Add sorting by link title to NavigationMenu.
<?php /** * A single navigtion menu * @author Jon Johnson <jon.johnson@ucsf.edu> * @license http://jazzee.org/license.txt * @package foundation * @subpackage navigation */ class Navigation_Menu { /** * The title for this menu * @var string */ public $title; /** * holds the links * @var array */ private $_links = array(); /** * Create a new link object * @param array $attributes * @return Navigation_Link */ public function newLink($attributes = array()){ $link = new Navigation_Link; foreach($attributes as $key=>$value){ $link->$key = $value; } $this->_links[] = $link; return $link; } /** * Get the links * return array */ public function getLinks(){ return $this->_links; } /** * Sort the links by title */ public function sortLinks(){ usort($this->_links, function($a, $b){ return strcmp($a->text, $b->text); }); } /** * Does the menu have links * @return bool true if there are any links false if not */ public function hasLink(){ return (bool)count($this->_links); } } ?>
<?php /** * A single navigtion menu * @author Jon Johnson <jon.johnson@ucsf.edu> * @license http://jazzee.org/license.txt * @package foundation * @subpackage navigation */ class Navigation_Menu { /** * The title for this menu * @var string */ public $title; /** * holds the links * @var array */ private $_links = array(); /** * Create a new link object * @param array $attributes * @return Navigation_Link */ public function newLink($attributes = array()){ $link = new Navigation_Link; foreach($attributes as $key=>$value){ $link->$key = $value; } $this->_links[] = $link; return $link; } /** * Get the links * return array */ public function getLinks(){ return $this->_links; } /** * Does the menu have links * @return bool true if there are any links false if not */ public function hasLink(){ return (bool)count($this->_links); } } ?>
Revert "Show tampering warning *only* when data has been tampered with :ninja:" The position was intentional. it should be loud until we pull out the fake part of this options method.
import backbone from 'backbone'; import AllocationSource from 'models/AllocationSource'; import globals from 'globals'; import _ from 'underscore'; import allocationSources from 'mockdata/allocationSources.json'; import mockSync from 'utilities/mockSync'; export default backbone.Collection.extend({ model: AllocationSource, url: globals.API_V2_ROOT + "/allocation_sources", parse: function (response) { console.warn("We are tampering with data until the api settles"); // Ensure the api returns values for these fields let defaults = { compute_used: 100, compute_allowed: 1000, name: "dummy" }; let results = response.results.map(source => { Object.keys(defaults).forEach(f => { if (!source[f]) { source[f] = defaults[f]; } }); return source; }); return results; }, sync: globals.USE_MOCK_DATA ? mockSync(allocationSources) : Backbone.sync });
import backbone from 'backbone'; import AllocationSource from 'models/AllocationSource'; import globals from 'globals'; import _ from 'underscore'; import allocationSources from 'mockdata/allocationSources.json'; import mockSync from 'utilities/mockSync'; export default backbone.Collection.extend({ model: AllocationSource, url: globals.API_V2_ROOT + "/allocation_sources", parse: function (response) { // Ensure the api returns values for these fields let defaults = { compute_used: 100, compute_allowed: 1000, name: "dummy" }; let results = response.results.map(source => { Object.keys(defaults).forEach(f => { if (!source[f]) { console.warn("We are tampering with data "+f+" until the api settles"); source[f] = defaults[f]; } }); return source; }); return results; }, sync: globals.USE_MOCK_DATA ? mockSync(allocationSources) : Backbone.sync });
Fix bytes problem on python 3.
# Copyright (c) Calico Development Team. # Distributed under the terms of the Modified BSD License. # http://calicoproject.org/ from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: retval = retval.decode('utf-8') self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
# Copyright (c) Calico Development Team. # Distributed under the terms of the Modified BSD License. # http://calicoproject.org/ from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
Use native path separators on Windows
import path from 'path'; import CompositeGitStrategy from '../composite-git-strategy'; import {fsStat, toNativePathSep} from '../helpers'; /** * Locate the nearest git working directory above a given starting point, caching results. */ export default class WorkdirCache { constructor(maxSize = 1000) { this.maxSize = maxSize; this.known = new Map(); } async find(startPath) { const cached = this.known.get(startPath); if (cached !== undefined) { return cached; } const workDir = await this.revParse(startPath); if (this.known.size >= this.maxSize) { this.known.clear(); } this.known.set(startPath, workDir); return workDir; } invalidate() { this.known.clear(); } async revParse(startPath) { try { const startDir = (await fsStat(startPath)).isDirectory() ? startPath : path.dirname(startPath); const workDir = await CompositeGitStrategy.create(startDir).exec(['rev-parse', '--show-toplevel']); return toNativePathSep(workDir.trim()); } catch (e) { return null; } } }
import path from 'path'; import CompositeGitStrategy from '../composite-git-strategy'; import {fsStat} from '../helpers'; /** * Locate the nearest git working directory above a given starting point, caching results. */ export default class WorkdirCache { constructor(maxSize = 1000) { this.maxSize = maxSize; this.known = new Map(); } async find(startPath) { const cached = this.known.get(startPath); if (cached !== undefined) { return cached; } const workDir = await this.revParse(startPath); if (this.known.size >= this.maxSize) { this.known.clear(); } this.known.set(startPath, workDir); return workDir; } invalidate() { this.known.clear(); } async revParse(startPath) { try { const startDir = (await fsStat(startPath)).isDirectory() ? startPath : path.dirname(startPath); const workDir = await CompositeGitStrategy.create(startDir).exec(['rev-parse', '--show-toplevel']); return workDir.trim(); } catch (e) { return null; } } }
Make sourceError optional in CallProcessingError
/** Errors @description defines custom errors used for the middleware @exports {class} APIError **/ /** @class APIError @desc given when API response gives error outside of 200 range @param {number} status HTTP Status given in response @param {string} statusText message given along with the error @param {object} response **/ export class APIError extends Error { constructor(status, statusText, response) { super(); this.name = 'APIError'; this.status = status; this.statusText = statusText; this.response = response; this.message = `${status} - ${statusText}`; } } /** @class CallProcessingError @desc given when an error occurs while processing the remote call action @param {string} msg @param {string} processStep the part of the call process that threw the error @param {error} sourceError (optional) **/ export class CallProcessingError extends Error { constructor(msg, processStep, sourceError) { super(); this.name = 'CallProcessingError'; this.processStep = processStep; this.sourceError = sourceError; this.message = sourceError ? `${msg}\nOriginal Error: ${sourceError}` : msg; } }
/** Errors @description defines custom errors used for the middleware @exports {class} APIError **/ /** @class APIError @desc given when API response gives error outside of 200 range @param {number} status HTTP Status given in response @param {string} statusText message given along with the error @param {object} response **/ export class APIError extends Error { constructor(status, statusText, response) { super(); this.name = 'APIError'; this.status = status; this.statusText = statusText; this.response = response; this.message = `${status} - ${statusText}`; } } /** @class CallProcessingError @desc given when an error occurs while processing the remote call action @param {string} msg @param {string} processStep the part of the call process that threw the error **/ export class CallProcessingError extends Error { constructor(msg, sourceError, processStep) { super(); this.name = 'CallProcessingError'; this.processStep = processStep; this.sourceError = sourceError; this.message = `${msg}\nOriginal Error: ${sourceError}`; } }
Remove extra space in usage message text
#!/usr/bin/env python3 import argparse from qlmdm import set_gpg from qlmdm.server import patch_hosts set_gpg('server') def parse_args(): parser = argparse.ArgumentParser(description='Queue a patch for one or ' 'more hosts') parser.add_argument('--host', action='append', help='Host(s) on which to ' 'execute command (default is all)') parser.add_argument('--mode', type=lambda m: int(m, 8), help='Mode for ' 'patched file (specify in octal, default 0755)') parser.add_argument('target_path', help='Relative path of file on ' 'destination systems') parser.add_argument('source_file', help='Local file containing patch ' 'content') args = parser.parse_args() return args def main(): args = parse_args() kwargs = {} if args.mode: kwargs['patch_mode'] = args.mode kwargs['patch_content'] = open(args.source_file, 'rb').read() kwargs['hosts'] = args.host if args.host else None patch_hosts(args.target_path, **kwargs) if __name__ == '__main__': main()
#!/usr/bin/env python3 import argparse from qlmdm import set_gpg from qlmdm.server import patch_hosts set_gpg('server') def parse_args(): parser = argparse.ArgumentParser(description='Queue a patch for one or ' 'more hosts') parser.add_argument('--host', action='append', help='Host(s) on which to ' 'execute command (default is all)') parser.add_argument('--mode', type=lambda m: int(m, 8), help='Mode for ' 'patched file (specify in octal, default 0755)') parser.add_argument('target_path', help='Relative path of file on ' 'destination systems') parser.add_argument('source_file', help='Local file containing patch ' 'content') args = parser.parse_args() return args def main(): args = parse_args() kwargs = {} if args.mode: kwargs['patch_mode'] = args.mode kwargs['patch_content'] = open(args.source_file, 'rb').read() kwargs['hosts'] = args.host if args.host else None patch_hosts(args.target_path, **kwargs) if __name__ == '__main__': main()
Add missing python import to utility script BUG= R=lrn@google.com Review URL: https://codereview.chromium.org//1226963005.
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import os import shutil import sys import subprocess import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import shutil import sys import subprocess import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())