text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Split too long funcall chain
package alita import ( "bufio" "fmt" "io" "strings" ) type Aligner struct { w io.Writer Margin *Margin Delimiter *Delimiter Padding *Padding lines [][]string } func NewAligner(w io.Writer) *Aligner { return &Aligner{ w: w, Margin: NewMargin(), Delimiter: NewDelimiter(), Padding: NewPadding(), } } func (a *Aligner) appendLine(s string) { sp := a.Delimiter.Split(s) a.lines = append(a.lines, sp) a.Padding.UpdateWidth(sp) } func (a *Aligner) ReadAll(r io.Reader) error { s := bufio.NewScanner(r) for s.Scan() { a.appendLine(s.Text()) } return s.Err() } func (a *Aligner) format(sp []string) string { return strings.TrimSpace(a.Margin.Join(a.Padding.Format(sp))) } func (a *Aligner) Flush() error { for _, sp := range a.lines { _, err := fmt.Fprintln(a.w, a.format(sp)) if err != nil { return err } } return nil }
package alita import ( "bufio" "fmt" "io" "strings" ) type Aligner struct { w io.Writer Margin *Margin Delimiter *Delimiter Padding *Padding lines [][]string } func NewAligner(w io.Writer) *Aligner { return &Aligner{ w: w, Margin: NewMargin(), Delimiter: NewDelimiter(), Padding: NewPadding(), } } func (a *Aligner) appendLine(s string) { sp := a.Delimiter.Split(s) a.lines = append(a.lines, sp) a.Padding.UpdateWidth(sp) } func (a *Aligner) ReadAll(r io.Reader) error { s := bufio.NewScanner(r) for s.Scan() { a.appendLine(s.Text()) } return s.Err() } func (a *Aligner) Flush() error { for _, sp := range a.lines { s := strings.TrimSpace(a.Margin.Join(a.Padding.Format(sp))) _, err := fmt.Fprintln(a.w, s) if err != nil { return err } } return nil }
Enable touch events on old React versions
'use strict'; var require = typeof require === 'undefined' ? function() {} : require; var React = window.React || require('react'); var ReactDom = window.ReactDOM || require('react-dom') || React; var ElementPan = React.createFactory(window.reactElementPan || require('react-element-pan')); if (React.initializeTouchEvents) { React.initializeTouchEvents(true); } // Simple image demo ReactDom.render( new ElementPan({ startX: 771, startY: 360 }, React.DOM.img({ src: 'img/beer.jpg' }) ), document.getElementById('image-demo')); // Huge SVG demo ReactDom.render( new ElementPan({ startX: 1771, startY: 1360 }, React.DOM.img({ src: 'img/metro.svg' }) ), document.getElementById('map-demo')); // Slightly more complicated DOM-element demo var i = 20, themDivs = []; while (--i) { themDivs.push(React.DOM.div({ key: i, style: { width: i * 30, lineHeight: (i * 10) + 'px' } }, 'Smaller...')); } ReactDom.render( new ElementPan(null, themDivs), document.getElementById('html-demo') );
'use strict'; var require = typeof require === 'undefined' ? function() {} : require; var React = window.React || require('react'); var ReactDom = window.ReactDOM || require('react-dom') || React; var ElementPan = React.createFactory(window.reactElementPan || require('react-element-pan')); // Simple image demo ReactDom.render( new ElementPan({ startX: 771, startY: 360 }, React.DOM.img({ src: 'img/beer.jpg' }) ), document.getElementById('image-demo')); // Huge SVG demo ReactDom.render( new ElementPan({ startX: 1771, startY: 1360 }, React.DOM.img({ src: 'img/metro.svg' }) ), document.getElementById('map-demo')); // Slightly more complicated DOM-element demo var i = 20, themDivs = []; while (--i) { themDivs.push(React.DOM.div({ key: i, style: { width: i * 30, lineHeight: (i * 10) + 'px' } }, 'Smaller...')); } ReactDom.render( new ElementPan(null, themDivs), document.getElementById('html-demo') );
Update deprecated excel kwarg in pandas
import pandas as pd def _params_dict_to_dataframe(d): s = pd.Series(d) s.index.name = 'parameters' f = pd.DataFrame({'values': s}) return f def write_excel(filename, **kwargs): """Write data tables to an Excel file, using kwarg names as sheet names. Parameters ---------- filename : str The filename to write to. kwargs : dict Mapping from sheet names to data. """ writer = pd.ExcelWriter(filename) for sheet_name, obj in kwargs.items(): if isinstance(obj, dict): obj = _params_dict_to_dataframe(obj) if isinstance(obj, pd.DataFrame): obj.to_excel(writer, sheetname=sheet_name) writer.save() writer.close()
import pandas as pd def _params_dict_to_dataframe(d): s = pd.Series(d) s.index.name = 'parameters' f = pd.DataFrame({'values': s}) return f def write_excel(filename, **kwargs): """Write data tables to an Excel file, using kwarg names as sheet names. Parameters ---------- filename : str The filename to write to. kwargs : dict Mapping from sheet names to data. """ writer = pd.ExcelWriter(filename) for sheet_name, obj in kwargs.items(): if isinstance(obj, dict): obj = _params_dict_to_dataframe(obj) if isinstance(obj, pd.DataFrame): obj.to_excel(writer, sheet_name=sheet_name) writer.save() writer.close()
Remove useless import of Entity
import fp from 'mostly-func'; // 返回值定制 export default function responder () { return function (hook) { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } let metadata = {}; let data = hook.result; let message = ''; if (hook.result && hook.result.data) { metadata = hook.result.metadata || fp.omit(['data'], hook.result); data = hook.result.data; message = hook.result.message || ''; } hook.result = { status: 0, message: message, metadata: metadata, errors: [], data: data }; return hook; }; }
import Entity from 'mostly-entity'; import fp from 'mostly-func'; // 返回值定制 export default function responder () { return function (hook) { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } let metadata = {}; let data = hook.result; let message = ''; if (hook.result && hook.result.data) { metadata = hook.result.metadata || fp.omit(['data'], hook.result); data = hook.result.data; message = hook.result.message || ''; } hook.result = { status: 0, message: message, metadata: metadata, errors: [], data: data }; return hook; }; }
Add the simplest of simple `alert` error handling
"use strict"; var saveRow = require('../templates/save_row.html')(); module.exports = { events: { 'click .save-item': '_handleSave' }, render: function () { this.$el.append(saveRow) }, toggleLoaders: function (state) { this.$('.save-item').prop('disabled', state); this.$('.loader').toggle(state); }, _handleSave: function () { if (this.saveItem) { this.saveItem(); } else { this.defaultSave(); } }, handleError: function (errorObj) { alert(window.JSON.stringify(errorObj)); }, defaultSave: function () { var that = this; this.toggleLoaders(true); this.model.save() .always(this.toggleLoaders.bind(this, false)) .done(function () { window.location.href = that.model.url().replace('\/api\/', '/'); }) .fail(function (jqXHR, textStatus, error) { that.handleError(jqXHR.responseJSON); }); } }
"use strict"; var saveRow = require('../templates/save_row.html')(); module.exports = { events: { 'click .save-item': '_handleSave' }, render: function () { this.$el.append(saveRow) }, toggleLoaders: function (state) { this.$('.save-item').prop('disabled', state); this.$('.loader').toggle(state); }, _handleSave: function () { if (this.saveItem) { this.saveItem(); } else { this.defaultSave(); } }, defaultSave: function () { var that = this; this.toggleLoaders(true); this.model.save() .always(this.toggleLoaders.bind(this, false)) .done(function () { window.location.href = that.model.url().replace('\/api\/', '/'); }); } }
Add import for constants_from_enum to be able to use @gin.constants_from_enum PiperOrigin-RevId: 198401971
# coding=utf-8 # Copyright 2018 The Gin-Config 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. """Init file for Gin.""" from gin.config import bind_parameter from gin.config import clear_config from gin.config import config_is_locked from gin.config import config_scope from gin.config import configurable from gin.config import constant from gin.config import constants_from_enum from gin.config import current_scope from gin.config import current_scope_str from gin.config import enter_interactive_mode from gin.config import exit_interactive_mode from gin.config import external_configurable from gin.config import finalize from gin.config import operative_config_str from gin.config import parse_config from gin.config import parse_config_file from gin.config import parse_config_files_and_bindings from gin.config import query_parameter from gin.config import REQUIRED from gin.config import unlock_config
# coding=utf-8 # Copyright 2018 The Gin-Config 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. """Init file for Gin.""" from gin.config import bind_parameter from gin.config import clear_config from gin.config import config_is_locked from gin.config import config_scope from gin.config import configurable from gin.config import constant from gin.config import current_scope from gin.config import current_scope_str from gin.config import enter_interactive_mode from gin.config import exit_interactive_mode from gin.config import external_configurable from gin.config import finalize from gin.config import operative_config_str from gin.config import parse_config from gin.config import parse_config_file from gin.config import parse_config_files_and_bindings from gin.config import query_parameter from gin.config import REQUIRED from gin.config import unlock_config
Define handler for tracking log files
import sys import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class TrackingLogHandler(PatternMatchingEventHandler): def on_created(self, event): print event.__repr__() print event.event_type, event.is_directory, event.src_path if __name__ == "__main__": if len(sys.argv) > 1: path = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingLogHandler(['*.log'], ['*.log-errors'], case_sensitive=True) observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class TrackingEventHandler(FileSystemEventHandler): def on_created(self, event): pass def on_moved(self, event): pass if __name__ == "__main__": if len(sys.argv) > 1: args = sys.argv[1] else: raise ValueError('Missing path to directory to monitor!!!') event_handler = TrackingEventHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
Allow negative numbers in the GEOS string The regular expression for parsing the GEOS string did not accept negative numbers. This means if you selected a location in most parts of the world the retrieve would fail and the map would center around the default location. Add optional hypen symbol to the GEOS regular expression.
import re geos_ptrn = re.compile( "^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$" ) def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_ptrn.match(value) if not result: return None return { 'srid': result.group(1), 'x': result.group(2), 'y': result.group(3), }
import re geos_ptrn = re.compile( "^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$" ) def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_ptrn.match(value) if not result: return None return { 'srid': result.group(1), 'x': result.group(2), 'y': result.group(3), }
Set targe class on csv document
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def __init__(self, path, target=None): super(CSVDatasource, self).__init__(path) self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: if self.target is not None: index = header.index(self.target) target = row[index] del row[index] row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
Hide logout message on login
(function() { 'use strict'; var app = angular.module('radar.store'); function unauthorizedResponseFactory($q, session, notificationService, $state, $rootScope) { var notification = null; // Hide logout notification on login $rootScope.$on('sessions.login', function() { if (notification !== null) { notification.remove(); notification = null; } }); return function(promise) { return promise['catch'](function(response) { // API endpoint requires login (token may have expired) if (response.status === 401) { session.logout(); if (notification === null) { notification = notificationService.info({message: 'You have been logged out.', timeout: 0}); } $state.go('login'); } return $q.reject(response); }); }; } unauthorizedResponseFactory.$inject = [ '$q', 'authService', 'notificationService', '$state', '$rootScope' ]; app.factory('unauthorizedResponse', unauthorizedResponseFactory); app.config(['adapterProvider', function(adapterProvider) { adapterProvider.afterResponse('unauthorizedResponse'); }]); })();
(function() { 'use strict'; var app = angular.module('radar.store'); function unauthorizedResponseFactory($q, session, notificationService, $state) { return function(promise) { return promise['catch'](function(response) { // API endpoint requires login (token may have expired) if (response.status === 401) { session.logout(); notificationService.info({message: 'You have been logged out.', timeout: 0}); $state.go('login'); } return $q.reject(response); }); }; } unauthorizedResponseFactory.$inject = [ '$q', 'authService', 'notificationService', '$state' ]; app.factory('unauthorizedResponse', unauthorizedResponseFactory); app.config(['adapterProvider', function(adapterProvider) { adapterProvider.afterResponse('unauthorizedResponse'); }]); })();
Add preRemove callbcok for user to change email
<?php namespace NyroDev\NyroCmsBundle\Model\Entity; use NyroDev\NyroCmsBundle\Model\User as UserModel; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * User. * * @ORM\Table(name="user") * @ORM\Entity(repositoryClass="NyroDev\NyroCmsBundle\Repository\Orm\UserRepository") * @Gedmo\Loggable(logEntryClass="NyroDev\NyroCmsBundle\Model\Entity\Log\UserLog") * @Gedmo\SoftDeleteable(fieldName="deleted", timeAware=false) * @ORM\HasLifecycleCallbacks */ class User extends UserModel { /** * @ORM\ManyToMany(targetEntity="UserRole", cascade={"persist"}) * @ORM\JoinTable(name="user_user_role") */ protected $userRoles; /** * @ORM\PreRemove() */ public function preRemove() { $this->setEmail('_deleted_'.time().$this->getEmail()); $this->setPasswordKey(null); } }
<?php namespace NyroDev\NyroCmsBundle\Model\Entity; use NyroDev\NyroCmsBundle\Model\User as UserModel; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * User. * * @ORM\Table(name="user") * @ORM\Entity(repositoryClass="NyroDev\NyroCmsBundle\Repository\Orm\UserRepository") * @Gedmo\Loggable(logEntryClass="NyroDev\NyroCmsBundle\Model\Entity\Log\UserLog") * @Gedmo\SoftDeleteable(fieldName="deleted", timeAware=false) */ class User extends UserModel { /** * @ORM\ManyToMany(targetEntity="UserRole", cascade={"persist"}) * @ORM\JoinTable(name="user_user_role") */ protected $userRoles; }
Fix navigation bar title display.
const product = require('../../utils/product.js') Page({ data: { toastAddProduct: true, title: '', id: 0, quantity: 1, product: {} }, onLoad (params) { var id = params.id var product = wx.getStorageSync('products').find(function(i){ return i.id === id }) this.setData({ id: id, product: product, title: product.name }) }, onReady() { wx.setNavigationBarTitle({ title: this.data.title }) }, bindAddToCart (e) { var that = this var cartItems = wx.getStorageSync('cartItems') || [] var exist = cartItems.find(function(ele){ return ele.id === that.data.id }) if (exist) { exist.quantity = parseInt(exist.quantity) + 1 } else { cartItems.push({ id: this.data.id, quantity: this.data.quantity, product: this.data.product }) } this.setData({ toastAddProduct:false }); wx.setStorage({ key: 'cartItems', data: cartItems }) }, bindQuantityInput (e) { this.setData({'quantity': e.detail.value}) }, toastChange: function(){ this.setData({ toastAddProduct:true }); } })
const product = require('../../utils/product.js') Page({ data: { toastAddProduct: true, title: '', id: 0, quantity: 1, product: {} }, onLoad (params) { var id = params.id var product = wx.getStorageSync('products').find(function(i){ return i.id === id }) this.setData({ id:id, product:product }) }, onReady () { wx.setNavigationBarTitle({ title: this.data.title }) }, bindAddToCart (e) { var that = this var cartItems = wx.getStorageSync('cartItems') || [] var exist = cartItems.find(function(ele){ return ele.id === that.data.id }) if (exist) { exist.quantity = parseInt(exist.quantity) + 1 } else { cartItems.push({ id: this.data.id, quantity: this.data.quantity, product: this.data.product }) } this.setData({ toastAddProduct:false }); wx.setStorage({ key: 'cartItems', data: cartItems }) }, bindQuantityInput (e) { this.setData({'quantity': e.detail.value}) }, toastChange: function(){ this.setData({ toastAddProduct:true }); } })
Add 'addSynset' and 'getSynset' method declarations.
package com.github.semres; import org.eclipse.rdf4j.repository.Repository; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; public class Database { private List<SynsetSerializer> synsetSerializers; private Repository repository; private String baseIri = "http://example.org/"; public Database(List<Class> serializerClasses, Repository repository) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { List<SynsetSerializer> synsetSerializers = new ArrayList<>(); for (Class serializerClass: serializerClasses) { SynsetSerializer loadedSynsetSerializer = (SynsetSerializer) serializerClass.getConstructor(Repository.class, String.class).newInstance(repository, baseIri); synsetSerializers.add(loadedSynsetSerializer); } this.synsetSerializers = synsetSerializers; this.repository = repository; } public void addSynset(Synset synset) { } public Synset getSynset(String id) { return null; } private String getSynsetClass(String synsetId) { return null; } }
package com.github.semres; import org.eclipse.rdf4j.repository.Repository; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; public class Database { private List<SynsetSerializer> synsetSerializers; private Repository repository; private String baseIri = "http://example.org/"; public Database(List<Class> serializerClasses, Repository repository) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { List<SynsetSerializer> synsetSerializers = new ArrayList<>(); for (Class serializerClass: serializerClasses) { SynsetSerializer loadedSynsetSerializer = (SynsetSerializer) serializerClass.getConstructor(Repository.class, String.class).newInstance(repository, baseIri); synsetSerializers.add(loadedSynsetSerializer); } this.synsetSerializers = synsetSerializers; this.repository = repository; } }
dist/docker: Fix typo in "--overprovisioned" help text Reported by Mathias Bogaert (@analytically). Message-Id: <13c4d4f57d8c59965d44b353c9e1b869295d4df3@scylladb.com>
import argparse def parse(): parser = argparse.ArgumentParser() parser.add_argument('--developer-mode', default='1', choices=['0', '1'], dest='developerMode') parser.add_argument('--seeds', default=None, help="specify seeds - if left empty will use container's own IP") parser.add_argument('--cpuset', default=None, help="e.g. --cpuset 0-3 for the first four CPUs") parser.add_argument('--smp', default=None, help="e.g --smp 2 to use two CPUs") parser.add_argument('--memory', default=None, help="e.g. --memory 1G to use 1 GB of RAM") parser.add_argument('--overprovisioned', default='0', choices=['0', '1'], help="run in overprovisioned environment") parser.add_argument('--broadcast-address', default=None, dest='broadcastAddress') parser.add_argument('--broadcast-rpc-address', default=None, dest='broadcastRpcAddress') return parser.parse_args()
import argparse def parse(): parser = argparse.ArgumentParser() parser.add_argument('--developer-mode', default='1', choices=['0', '1'], dest='developerMode') parser.add_argument('--seeds', default=None, help="specify seeds - if left empty will use container's own IP") parser.add_argument('--cpuset', default=None, help="e.g. --cpuset 0-3 for the first four CPUs") parser.add_argument('--smp', default=None, help="e.g --smp 2 to use two CPUs") parser.add_argument('--memory', default=None, help="e.g. --memory 1G to use 1 GB of RAM") parser.add_argument('--overprovisioned', default='0', choices=['0', '1'], help="run in overprovisined environment") parser.add_argument('--broadcast-address', default=None, dest='broadcastAddress') parser.add_argument('--broadcast-rpc-address', default=None, dest='broadcastRpcAddress') return parser.parse_args()
Revert "id removed from the form" This reverts commit 73764a51bae2973524a823df89495e4334ce14a2.
@push('js') <script src="{{ asset('components/ckeditor4/ckeditor.js') }}"></script> <script src="{{ asset('components/ckeditor4/config-full.js') }}"></script> @endpush @component('core::admin._buttons-form', ['model' => $model]) @endcomponent {!! BootForm::hidden('id') !!} <file-manager></file-manager> <file-field type="image" field="image_id" data="{{ $model->image }}"></file-field> <files-field :init-files="{{ $model->files }}"></files-field> <div class="row"> <div class="col-sm-6"> {!! BootForm::date(__('Date'), 'date')->value(old('date') ? : $model->present()->dateOrNow('date'))->addClass('datepicker')->required() !!} </div> </div> @include('core::form._title-and-slug') <div class="form-group"> {!! TranslatableBootForm::hidden('status')->value(0) !!} {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!} </div> {!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!} {!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor-full') !!}
@push('js') <script src="{{ asset('components/ckeditor4/ckeditor.js') }}"></script> <script src="{{ asset('components/ckeditor4/config-full.js') }}"></script> @endpush @component('core::admin._buttons-form', ['model' => $model]) @endcomponent <file-manager></file-manager> <file-field type="image" field="image_id" data="{{ $model->image }}"></file-field> <files-field :init-files="{{ $model->files }}"></files-field> <div class="row"> <div class="col-sm-6"> {!! BootForm::date(__('Date'), 'date')->value(old('date') ? : $model->present()->dateOrNow('date'))->addClass('datepicker')->required() !!} </div> </div> @include('core::form._title-and-slug') <div class="form-group"> {!! TranslatableBootForm::hidden('status')->value(0) !!} {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!} </div> {!! TranslatableBootForm::textarea(__('Summary'), 'summary')->rows(4) !!} {!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor-full') !!}
Allow steps to be placed in subdirectories
var Yadda = require('yadda'), config = require('./configure'), language = Yadda.localisation[upperCaseFirstLetter(config.language)], fs = require('fs'), glob = require('glob'), path = require('path'), chai = require('chai'); module.exports = (function () { var library = language.library(), dictionary = new Yadda.Dictionary(), stepsFiles = path.join(__dirname, '..', 'steps', '**', '*.js'), steps = glob.sync(stepsFiles); /** * define regex helpers */ dictionary.define('string', '([^"]*)?'); /** * define step library */ steps.forEach(function (step) { require(step).call(library, dictionary); }); return library; })(); function upperCaseFirstLetter(word) { return word.slice(0, 1).toUpperCase() + word.slice(1); }
var Yadda = require('yadda'), config = require('./configure'), language = Yadda.localisation[upperCaseFirstLetter(config.language)], fs = require('fs'), path = require('path'), chai = require('chai'); module.exports = (function () { var library = language.library(), dictionary = new Yadda.Dictionary(), stepsFiles = path.join(__dirname, '..', 'steps'), steps = fs.readdirSync(stepsFiles); /** * define regex helpers */ dictionary.define('string', '([^"]*)?'); /** * define step library */ steps.forEach(function (step) { require(path.join(stepsFiles, step)).call(library, dictionary); }); return library; })(); function upperCaseFirstLetter(word) { return word.slice(0, 1).toUpperCase() + word.slice(1); }
Use find_packages to ensure template library gets installed
from setuptools import setup, find_packages setup( name='twitter-text-py', version='1.0.3', description='A library for auto-converting URLs, mentions, hashtags, lists, etc. in Twitter text. Also does tweet validation and search term highlighting.', author='Daniel Ryan', author_email='dryan@dryan.com', url='http://github.com/dryan/twitter-text-py', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], include_package_data=True, install_requires=['setuptools'], license = "BSD" )
from setuptools import setup setup( name='twitter-text-py', version='1.0.3', description='A library for auto-converting URLs, mentions, hashtags, lists, etc. in Twitter text. Also does tweet validation and search term highlighting.', author='Daniel Ryan', author_email='dryan@dryan.com', url='http://github.com/dryan/twitter-text-py', packages=['twitter_text'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], include_package_data=True, install_requires=['setuptools'], license = "BSD" )
Set the navbar to reload, no matter the url.
/* * @flow */ import React from 'react'; export default function Navbar() { return ( <nav className="navbar navbar-default navbar-fixed-top navbar-inverse"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/" onClick={(e) => { event.preventDefault(); window.location.reload(); }}> Bonsai - Trim your dependency trees </a> </div> <ul className="nav navbar-nav navbar-right"> <li> <a className="navbar-link" href="https://pinterest.github.io/bonsai/"> Docs </a> </li> <li> <a className="navbar-link" href="https://github.com/pinterest/bonsai"> Github </a> </li> </ul> </div> </nav> ); }
/* * @flow */ import React from 'react'; export default function Navbar() { return ( <nav className="navbar navbar-default navbar-fixed-top navbar-inverse"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/"> Bonsai - Trim your dependency trees </a> </div> <ul className="nav navbar-nav navbar-right"> <li> <a className="navbar-link" href="https://pinterest.github.io/bonsai/"> Docs </a> </li> <li> <a className="navbar-link" href="https://github.com/pinterest/bonsai"> Github </a> </li> </ul> </div> </nav> ); }
Fix syntax error for PHP 5.3
<?php namespace Concise\Console; use Concise\Services\SyntaxRenderer; use DateTime; class TestColors { public function renderAll() { $renderer = new SyntaxRenderer(); $lines = array( $renderer->render('? is null', array(null)), $renderer->render('? does not equal ?', array(true, false)), $renderer->render('? has key ? with value ?', array(array("foo" => 123), 'foo', 123)), $renderer->render('? is instance of ?', array(new DateTime(), 'DateTime')), $renderer->render('? equals ? within ?', array(1.57, 1.5, 0.5)), $renderer->render('? is instance of ?', array(function () {}, 'Closure')), ); return "Some assertion examples:\n " . implode("\n ", $lines) . "\n\n"; } }
<?php namespace Concise\Console; use Concise\Services\SyntaxRenderer; use DateTime; class TestColors { public function renderAll() { $renderer = new SyntaxRenderer(); $lines = array( $renderer->render('? is null', array(null)), $renderer->render('? does not equal ?', array(true, false)), $renderer->render('? has key ? with value ?', array(["foo" => 123], 'foo', 123)), $renderer->render('? is instance of ?', array(new DateTime(), 'DateTime')), $renderer->render('? equals ? within ?', array(1.57, 1.5, 0.5)), $renderer->render('? is instance of ?', array(function () {}, 'Closure')), ); return "Some assertion examples:\n " . implode("\n ", $lines) . "\n\n"; } }
Use fractional seconds to compare
package org.jboss.msc.bench; import java.util.concurrent.CountDownLatch; import org.jboss.msc.registry.ServiceDefinition; import org.jboss.msc.registry.ServiceRegistrationBatchBuilder; import org.jboss.msc.registry.ServiceRegistry; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.TimingServiceListener; public class NoDepBench { public static void main(String[] args) throws Exception { final int totalServiceDefinitions = Integer.parseInt(args[0]); ServiceRegistrationBatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); final CountDownLatch latch = new CountDownLatch(1); final TimingServiceListener listener = new TimingServiceListener(new TimingServiceListener.FinishListener() { public void done(final TimingServiceListener timingServiceListener) { latch.countDown(); } }); for (int i = 0; i < totalServiceDefinitions; i++) { batch.add(ServiceDefinition.build(ServiceName.of("test" + i), Service.NULL_VALUE).addListener(listener).create()); } batch.install(); listener.finishBatch(); latch.await(); System.out.println(totalServiceDefinitions + " : " + listener.getElapsedTime() / 1000.0); } }
package org.jboss.msc.bench; import java.util.concurrent.CountDownLatch; import org.jboss.msc.registry.ServiceDefinition; import org.jboss.msc.registry.ServiceRegistrationBatchBuilder; import org.jboss.msc.registry.ServiceRegistry; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.TimingServiceListener; public class NoDepBench { public static void main(String[] args) throws Exception { final int totalServiceDefinitions = Integer.parseInt(args[0]); ServiceRegistrationBatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); final CountDownLatch latch = new CountDownLatch(1); final TimingServiceListener listener = new TimingServiceListener(new TimingServiceListener.FinishListener() { public void done(final TimingServiceListener timingServiceListener) { latch.countDown(); } }); for (int i = 0; i < totalServiceDefinitions; i++) { batch.add(ServiceDefinition.build(ServiceName.of("test" + i), Service.NULL_VALUE).addListener(listener).create()); } batch.install(); listener.finishBatch(); latch.await(); System.out.println(totalServiceDefinitions + " : " + listener.getElapsedTime() + "ms"); } }
Add support for CSS requires, and support to output json when required
var loaderUtils = require('loader-utils'); var sizeOf = require('image-size'); var fs = require('fs'); var path = require('path'); module.exports = function(content) { this.cacheable && this.cacheable(true); if(!this.emitFile) throw new Error('emitFile is required from module system'); this.addDependency(this.resourcePath); var query = loaderUtils.parseQuery(this.query); var filename = "[name].[ext]"; if (this.options.output.imageFilename) { filename = this.options.output.imageFilename } // query.name overrides imageFilename if ('string' === typeof query.name) { filename = query.name; } var url = loaderUtils.interpolateName(this, filename, { context: query.context || this.options.context, content: content, regExp: query.regExp }); var image = sizeOf(this.resourcePath); image.src = this.options.output.publicPath ? path.join(this.options.output.publicPath, url) : url; image.bytes = fs.statSync(this.resourcePath).size; this.emitFile(url, content); var output = JSON.stringify(image); if (query.json) { return output; } // For requires from CSS when used with webpack css-loader, // outputting an Object doesn't make sense, // So overriding the toString method to output just the URL return 'module.exports = ' + output + ';' + 'module.exports.toString = function() {' + 'return ' + JSON.stringify(image.src) + '}'; }; module.exports.raw = true;
var sizeOf = require('image-size'); var loaderUtils = require('loader-utils'); module.exports = function(content) { this.cacheable && this.cacheable(); if(!this.emitFile) throw new Error('emitFile is required from module system'); this.addDependency(this.resourcePath); var query = loaderUtils.parseQuery(this.query); var filename = "[name].[ext]"; if ('string' === typeof query.name) { filename = query.name; } else if (this.options.output.imageFilename) { filename = this.options.output.imageFilename } var url = loaderUtils.interpolateName(this, filename, { context: query.context || this.options.context, content: content, regExp: query.regExp }); var dimensions = sizeOf(content); dimensions.src = this.options.output.publicPath ? this.options.output.publicPath + url : url; this.emitFile(url, content); return 'module.exports = ' + JSON.stringify(dimensions); }; module.exports.raw = true;
Update now that ints aren't nullable
package service import ( "strconv" "github.com/rancher/norman/types" "github.com/rancher/norman/types/convert" v3 "github.com/rancher/types/client/project/v3" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/intstr" ) func New(store types.Store) types.Store { return &Store{ store, } } type Store struct { types.Store } func (p *Store) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) { formatData(data) data, err := p.Store.Create(apiContext, schema, data) return data, err } func formatData(data map[string]interface{}) { var ports []interface{} servicePort := v3.ServicePort{ Port: 42, TargetPort: intstr.Parse(strconv.FormatInt(42, 10)), Protocol: "TCP", Name: "default", } m, err := convert.EncodeToMap(servicePort) if err != nil { logrus.Warnf("Failed to transform service port to map: %v", err) return } ports = append(ports, m) data["ports"] = ports }
package service import ( "strconv" "github.com/rancher/norman/types" "github.com/rancher/norman/types/convert" v3 "github.com/rancher/types/client/project/v3" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/intstr" ) func New(store types.Store) types.Store { return &Store{ store, } } type Store struct { types.Store } func (p *Store) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) { formatData(data) data, err := p.Store.Create(apiContext, schema, data) return data, err } func formatData(data map[string]interface{}) { var ports []interface{} port := int64(42) servicePort := v3.ServicePort{ Port: &port, TargetPort: intstr.Parse(strconv.FormatInt(42, 10)), Protocol: "TCP", Name: "default", } m, err := convert.EncodeToMap(servicePort) if err != nil { logrus.Warnf("Failed to transform service port to map: %v", err) return } ports = append(ports, m) data["ports"] = ports }
Update BoardgameListComponent to accept more input
import React, { Component, PropTypes } from 'react'; export default class BoardgameListItem extends Component { static propTypes = { name: PropTypes.string.isRequired, year: PropTypes.number, thumbnail: PropTypes.string, score: PropTypes.number } render() { const { name, year, thumbnail, score } = this.props; return ( <div className="media"> <div className="media-left media-middle"> {thumbnail ? <img src={thumbnail} alt={name} className="media-object" /> : <img src="http://placehold.it/80x80" alt={name} className="media-object" /> } </div> <div className="media-body"> <h4 className="media-heading">{name}</h4> <p><em>{year}</em>, {score}</p> </div> </div> ); } }
import React, { Component, PropTypes } from 'react'; export default class BoardgameListItem extends Component { static propTypes = { name: PropTypes.string.isRequired, year: PropTypes.string } render() { const { name, year } = this.props; return ( <div className="media"> <div className="media-left media-middle"> <img src="http://placehold.it/80x80" alt={name} className="media-object" /> </div> <div className="media-body"> <h4 className="media-heading">{name}</h4> <p><em>{year}</em></p> </div> </div> ); } }
Use array for search columns
<?php namespace WP_CLI\Fetchers; use WP_User; /** * Fetch a WordPress user based on one of its attributes. */ class User extends Base { /** * The message to display when an item is not found. * * @var string */ protected $msg = "Invalid user ID, email or login: '%s'"; /** * Get a user object by one of its identifying attributes. * * @param string $arg The raw CLI argument. * @return WP_User|false The item if found; false otherwise. */ public function get( $arg ) { if ( is_numeric( $arg ) ) { $users = get_users( [ 'include' => [ (int) $arg ] ] ); } elseif ( is_email( $arg ) ) { $users = get_users( [ 'search' => $arg, 'search_columns' => [ 'user_email' ], ] ); // Logins can be emails. if ( ! $user ) { $users = get_users( [ 'login' => $arg ] ); } } else { $users = get_users( [ 'login' => $arg ] ); } return is_array( $users ) ? $users[0] : false; } }
<?php namespace WP_CLI\Fetchers; use WP_User; /** * Fetch a WordPress user based on one of its attributes. */ class User extends Base { /** * The message to display when an item is not found. * * @var string */ protected $msg = "Invalid user ID, email or login: '%s'"; /** * Get a user object by one of its identifying attributes. * * @param string $arg The raw CLI argument. * @return WP_User|false The item if found; false otherwise. */ public function get( $arg ) { if ( is_numeric( $arg ) ) { $users = get_users( [ 'include' => [ (int) $arg ] ] ); } elseif ( is_email( $arg ) ) { $users = get_users( [ 'search' => $arg, 'search_columns' => 'user_email', ] ); // Logins can be emails. if ( ! $user ) { $users = get_users( [ 'login' => $arg ] ); } } else { $users = get_users( [ 'login' => $arg ] ); } return is_array( $users ) ? $users[0] : false; } }
Use HTTPS url for MathJax script
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')) MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js' MATHJAX_WEB_URL = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js' PYGMENTS_STYLE = 'default' def get_pygments_stylesheet(selector, style=None): if style is None: style = PYGMENTS_STYLE if style == '': return '' try: from pygments.formatters import HtmlFormatter except ImportError: return '' else: return HtmlFormatter(style=style).get_style_defs(selector) + '\n' def get_mathjax_url(webenv): if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv: return MATHJAX_LOCAL_URL else: return MATHJAX_WEB_URL
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')) MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js' MATHJAX_WEB_URL = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js' PYGMENTS_STYLE = 'default' def get_pygments_stylesheet(selector, style=None): if style is None: style = PYGMENTS_STYLE if style == '': return '' try: from pygments.formatters import HtmlFormatter except ImportError: return '' else: return HtmlFormatter(style=style).get_style_defs(selector) + '\n' def get_mathjax_url(webenv): if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv: return MATHJAX_LOCAL_URL else: return MATHJAX_WEB_URL
Check NCCL existence in test decorators
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) assert 0 == comm.rank_id() comm.destroy() @attr.gpu @unittest.skipUnless(cuda.nccl_enabled and cuda.nccl.get_version() >= 2400, "Using old NCCL") def test_abort(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) comm.abort() @attr.gpu @unittest.skipUnless(cuda.nccl_enabled and cuda.nccl.get_version() >= 2400, "Using old NCCL") def test_check_async_error(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) comm.check_async_error() comm.destroy()
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) assert 0 == comm.rank_id() comm.destroy() @attr.gpu @unittest.skipUnless(cuda.nccl.get_version() >= 2400, "Using old NCCL") def test_abort(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) comm.abort() @attr.gpu @unittest.skipUnless(cuda.nccl.get_version() >= 2400, "Using old NCCL") def test_check_async_error(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) comm.check_async_error() comm.destroy()
Fix variabel naems in go unique chars.
package uniq_chars import "fmt" func IsAllUniqueChars (strings ...string) bool { //Save Time fmt.Println(strings) //Iterate all runes and keep track of each we've seen O(n) //MAP {runeVal: seen before} charCounts := make(map[rune] bool) for _, string := range strings { for _, letterRune := range string { if (charCounts[letterRune] == true /*&& letterRune != ' '*/) { return false; } else { charCounts[letterRune] = true; } } } return true; } func IsAllUniqChars (strings ...string) bool { //Save Space //for each string/char, check all other strings/chars for replica that // is NOT THIS INSTANCE lol //for each string for thisStringIndex, thisString := range strings { //for each rune in the string for thisRuneIndex, thisRune := range thisString { //check each string for compStringIndex, compString := range strings { //for this rune for compRuneIndex, compRune := range compString { if (!(thisStringIndex == compStringIndex && thisRuneIndex == compRuneIndex) && thisRune == compRune){ return false } } } } } return true; }
package uniq_chars import "fmt" func IsAllUniqueChars (strings ...string) bool { //Save Time fmt.Println(strings) //Iterate all runes and keep track of each we've seen O(n) //MAP {runeVal: seen before} charCounts := make(map[rune] bool) for i, e := range strings { for _, letterRune := range e { if (charCounts[letterRune] == true /*&& letterRune != ' '*/) { return false; } else { charCounts[letterRune] = true; } } } return true; } func IsAllUniqChars (strings ...string) bool { //Save Space //for each string/char, check all other strings/chars for replica that // is NOT THIS INSTANCE lol //for each string for thisStringIdex, thisString := range strings { //for each rune in the string for thisRuneIndex, thisRune := range thisString { //check each string for compStringIndex, compString := range strings { //for this rune for compRuneIndex, compRune := range compString { if (!(thisStringIdex == compStringIndex && thisRuneIndex == compRuneIndex) && thisRune == compRune){ return false } } } } } return true; }
Call npm command line instead of using module.
module.exports = function(grunt) { var fs = require("fs"); var path = require("path"); var SubProcess = require("../../utils/subprocess"); grunt.registerMultiTask("npm-install", "Runs npm install.", function() { var options = this.options({ dest: "./out" }); // Only install npm if modules are not installed in src. var skipInstall = fs.existsSync(path.join(options.dest, "node_modules")); if (skipInstall) { grunt.log.writeln("Skipping npm install."); grunt.log.writeln( "A 'node_modules' directory was found." ); grunt.log.writeln( "If the tests fail due to dependencies issues try delating it and" ); grunt.log.writeln("let me install the dependencies from scretch."); return; } // Call npm install from the target directory. var npm = new SubProcess(grunt.log, { args: ["install"], cmd: "npm", cwd: options.dest }); var done = this.async(); npm.spawn().then(function() { done(); }).fail(function(code) { done(new Error(code)); }); }); };
module.exports = function(grunt) { var path = require("path"); grunt.registerMultiTask("npm-install", "Runs npm install.", function() { var done = this.async(); var fs = require("fs"); var npm = require("npm"); var options = this.options({ dest: "./out" }); // Only install npm if modules are not installed in src. var skipInstall = fs.existsSync(path.join(options.dest, "node_modules")); if (skipInstall) { grunt.log.writeln("Skipping npm install."); grunt.log.writeln( "A 'node_modules' directory was found."); grunt.log.writeln( "If the tests fail due to dependencies issues try delating it and"); grunt.log.writeln("let me install the dependencies from scretch."); return done(); } npm.load({ prefix: options.dest }, function(err) { if (err) { return done(err); } npm.commands.install(function (err, data) { done(err); }); npm.on("log", grunt.log.write.bind(grunt.log)); }); }); };
Revert to "Updated daily" msg.
'use strict'; var app = require('../../util/app'); var viewLocals = require('../../middleware/view-locals'); var siteNav = require('../../middleware/site-navigation'); var battlegroundData = require('../data/').battlegroundData; var forecastData = require('../data/').forecastData; var parties = require('uk-political-parties'); var debug = require('debug')('projections-index'); var filters = require('../../util/filters'); function* home(next) { var battlegrounds = yield battlegroundData(); var forecast = yield forecastData('seats'); var updated = forecast.updated; debug(forecast); forecast = forecast.data.map(function(d){ d.Party = parties.electionForecastToCode(d.Party); return d; }); yield this.render('projections-index', { // jshint ignore:line page: { title: 'The 4 key UK general election battles', summary: 'Four different types of local contest will shape the most uncertain UK general election in memory', dateModified: updated instanceof Date ? 'Updated daily. Last updated ' + filters.ftdate(updated) : '' }, groups: battlegrounds, overview: forecast }); yield next; } function main() { return app() .use(siteNav()) .use(viewLocals()) .router() // forecast home page .get('home', '/', home); } module.exports = main; if (!module.parent) main().listen(process.env.PORT || 5000);
'use strict'; var app = require('../../util/app'); var viewLocals = require('../../middleware/view-locals'); var siteNav = require('../../middleware/site-navigation'); var battlegroundData = require('../data/').battlegroundData; var forecastData = require('../data/').forecastData; var parties = require('uk-political-parties'); var debug = require('debug')('projections-index'); var filters = require('../../util/filters'); function* home(next) { var battlegrounds = yield battlegroundData(); var forecast = yield forecastData('seats'); var updated = forecast.updated; debug(forecast); forecast = forecast.data.map(function(d){ d.Party = parties.electionForecastToCode(d.Party); return d; }); yield this.render('projections-index', { // jshint ignore:line page: { title: 'The 4 key UK general election battles', summary: 'Four different types of local contest will shape the most uncertain UK general election in memory', dateModified: updated instanceof Date ? 'Last updated ' + filters.ftdate(updated) : '' }, groups: battlegrounds, overview: forecast }); yield next; } function main() { return app() .use(siteNav()) .use(viewLocals()) .router() // forecast home page .get('home', '/', home); } module.exports = main; if (!module.parent) main().listen(process.env.PORT || 5000);
Remove duplicate check on redux.reducer
import { each } from 'lodash'; import mergeConfigs from '../bin/merge-configs'; function validateConfig(config) { const errors = []; if (!config) { errors.push('==> ERROR: No configuration supplied.'); } if (config.server) { if (!config.server.host) { errors.push('==> ERROR: No host parameter supplied.'); } if (!config.server.port) { errors.push('==> ERROR: No port parameter supplied.'); } } if (!config.routes) { errors.push('==> ERROR: Must supply routes.'); } if (!config.redux.reducers) { errors.push('==> ERROR: Must supply redux configuration.'); } // TODO: check for more return errors; } export default (projectConfig) => { // since typically the dev server is logging this out too projectConfig.verbose = false; const config = mergeConfigs(projectConfig); // add user defined globals for serverside access each(config.globals, (value, key) => { global[key] = JSON.stringify(value); }); const errors = validateConfig(config); if (errors.length > 0) { each(errors, (error) => { console.error(error); }); throw new Error('Configuration errors for universal-redux. Stopping.'); } else { console.log('universal-redux configuration is valid.'); } return config; };
import { each } from 'lodash'; import mergeConfigs from '../bin/merge-configs'; function validateConfig(config) { const errors = []; if (!config) { errors.push('==> ERROR: No configuration supplied.'); } if (config.server) { if (!config.server.host) { errors.push('==> ERROR: No host parameter supplied.'); } if (!config.server.port) { errors.push('==> ERROR: No port parameter supplied.'); } } if (!config.routes) { errors.push('==> ERROR: Must supply routes.'); } if (!config.redux.reducers) { errors.push('==> ERROR: Must supply redux configuration.'); } else if (!config.redux.reducers) { errors.push('==> ERROR: Must supply reducers.'); } // TODO: check for more return errors; } export default (projectConfig) => { // since typically the dev server is logging this out too projectConfig.verbose = false; const config = mergeConfigs(projectConfig); // add user defined globals for serverside access each(config.globals, (value, key) => { global[key] = JSON.stringify(value); }); const errors = validateConfig(config); if (errors.length > 0) { each(errors, (error) => { console.error(error); }); throw new Error('Configuration errors for universal-redux. Stopping.'); } else { console.log('universal-redux configuration is valid.'); } return config; };
Add nullable to corecontentlistner methods parameters
package it.near.sdk.Utils; import android.content.Intent; import android.support.annotation.Nullable; import it.near.sdk.Reactions.Content.Content; import it.near.sdk.Reactions.Coupon.Coupon; import it.near.sdk.Reactions.CustomJSON.CustomJSON; import it.near.sdk.Reactions.Feedback.Feedback; import it.near.sdk.Reactions.Poll.Poll; import it.near.sdk.Reactions.SimpleNotification.SimpleNotification; /** * Interface for being notified of core content types. * * @author cattaneostefano */ public interface CoreContentsListener { void getPollNotification(@Nullable Intent intent, Poll notification, String recipeId); void getContentNotification(@Nullable Intent intent, Content notification, String recipeId); void getCouponNotification(@Nullable Intent intent, Coupon notification, String recipeId); void getCustomJSONNotification(@Nullable Intent intent, CustomJSON notification, String recipeId); void getSimpleNotification(@Nullable Intent intent, SimpleNotification s_notif, String recipeId); void getFeedbackNotification(@Nullable Intent intent, Feedback s_notif, String recipeId); }
package it.near.sdk.Utils; import android.content.Intent; import it.near.sdk.Reactions.Content.Content; import it.near.sdk.Reactions.Coupon.Coupon; import it.near.sdk.Reactions.CustomJSON.CustomJSON; import it.near.sdk.Reactions.Feedback.Feedback; import it.near.sdk.Reactions.Poll.Poll; import it.near.sdk.Reactions.SimpleNotification.SimpleNotification; /** * Interface for being notified of core content types. * * @author cattaneostefano */ public interface CoreContentsListener { void getPollNotification(Intent intent, Poll notification, String recipeId); void getContentNotification(Intent intent, Content notification, String recipeId); void getCouponNotification(Intent intent, Coupon notification, String recipeId); void getCustomJSONNotification(Intent intent, CustomJSON notification, String recipeId); void getSimpleNotification(Intent intent, SimpleNotification s_notif, String recipeId); void getFeedbackNotification(Intent intent, Feedback s_notif, String recipeId); }
Change russian language string to "ru_RU"
'use strict'; angular.module('yaru22.angular-timeago').config(function(timeAgoSettings) { timeAgoSettings.strings['ru_RU'] = { prefixAgo: null, prefixFromNow: null, suffixAgo: 'назад', suffixFromNow: null, seconds: 'меньше минуты', minute: 'около минуты', minutes: '%d мин.', hour: 'около часа', hours: 'около %d час.', day: 'день', days: '%d дн.', month: 'около месяца', months: '%d мес.', year: 'около года', years: '%d г.', numbers: [] }; });
'use strict'; angular.module('yaru22.angular-timeago').config(function(timeAgoSettings) { timeAgoSettings.strings['ru'] = { prefixAgo: null, prefixFromNow: null, suffixAgo: 'назад', suffixFromNow: null, seconds: 'меньше минуты', minute: 'около минуты', minutes: '%d мин.', hour: 'около часа', hours: 'около %d час.', day: 'день', days: '%d дн.', month: 'около месяца', months: '%d мес.', year: 'около года', years: '%d г.', numbers: [] }; });
Change webserver-ext status to beta.
package org.develnext.jphp.ext.webserver; import org.develnext.jphp.ext.webserver.classes.PWebRequest; import org.develnext.jphp.ext.webserver.classes.PWebResponse; import org.develnext.jphp.ext.webserver.classes.PWebServer; import php.runtime.env.CompileScope; import php.runtime.ext.support.Extension; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebServerExtension extends Extension { public static final String NS = "php\\webserver"; @Override public Status getStatus() { return Status.BETA; } @Override public void onRegister(CompileScope scope) { registerClass(scope, PWebServer.class); registerWrapperClass(scope, HttpServletRequest.class, PWebRequest.class); registerWrapperClass(scope, HttpServletResponse.class, PWebResponse.class); } }
package org.develnext.jphp.ext.webserver; import org.develnext.jphp.ext.webserver.classes.PWebRequest; import org.develnext.jphp.ext.webserver.classes.PWebResponse; import org.develnext.jphp.ext.webserver.classes.PWebServer; import php.runtime.env.CompileScope; import php.runtime.ext.support.Extension; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebServerExtension extends Extension { public static final String NS = "php\\webserver"; @Override public Status getStatus() { return Status.EXPERIMENTAL; } @Override public void onRegister(CompileScope scope) { registerClass(scope, PWebServer.class); registerWrapperClass(scope, HttpServletRequest.class, PWebRequest.class); registerWrapperClass(scope, HttpServletResponse.class, PWebResponse.class); } }
Send X-Requested-With header if app is extension
define([ 'jquery', 'underscore', 'backbone', 'helpers/app' ], function ($, _, Backbone, AppHelper) { var Search = Backbone.Collection.extend ({ query: '', url: function () { return AppHelper.urlPrefix + 'autocomplete/query?q=' + escape (this.query); }, parse: function (resp) { var data = []; _.each (resp.Titles, function (title) { data.push ({'title': title}); }); _.each (resp.Nicks, function (title) { data.push ({'title': '@' + title}); }); return data; }, fetch: function (options) { options = options || {}; if (AppHelper.isExtension) options.headers = { 'X-Requested-With': 'XMLHttpRequest' }; return Backbone.Collection.prototype.fetch.call (this, options); } }); return Search; });
define([ 'jquery', 'underscore', 'backbone', 'helpers/app' ], function ($, _, Backbone, AppHelper) { var Search = Backbone.Collection.extend ({ query: '', url: function () { return AppHelper.urlPrefix + 'autocomplete/query?q=' + escape (this.query); }, parse: function (resp) { var data = []; _.each (resp.Titles, function (title) { data.push ({'title': title}); }); _.each (resp.Nicks, function (title) { data.push ({'title': '@' + title}); }); return data; }, fetch: function (options) { options = options || {}; options.headers = { 'X-Requested-With': 'XMLHttpRequest' }; return Backbone.Collection.prototype.fetch.call (this, options); } }); return Search; });
Update public keyword regular expression.
'use strict'; const matchPublic = /^\s*public\s*(.*)$/; class Controller { constructor() { this.commands = []; } addCommand( name ) { const Command = require( './command/' + name ); const instance = new Command( this ); this.commands.push( instance ); } handleRequest( request ) { const values = matchPublic.exec( request.text ); let isPublic = false; if ( values ) { request.text = values[ 1 ]; isPublic = true; } for ( let command of this.commands ) { const response = command.handleRequest( request ); if ( response ) { if ( isPublic ) { response.response_type = 'in_channel'; } return response; } } return { 'text': 'Incorrect command.\n' + 'Use `' + request.command + ' help` for help.' }; } } module.exports = Controller;
'use strict'; const matchPublic = /^\s*public\s*(\S*)$/; class Controller { constructor() { this.commands = []; } addCommand( name ) { const Command = require( './command/' + name ); const instance = new Command( this ); this.commands.push( instance ); } handleRequest( request ) { const values = matchPublic.exec( request.text ); let isPublic = false; if ( values ) { request.text = values[ 1 ]; isPublic = true; } for ( let command of this.commands ) { const response = command.handleRequest( request ); if ( response ) { if ( isPublic ) { response.response_type = 'in_channel'; } return response; } } return { 'text': 'Incorrect command.\n' + 'Use `' + request.command + ' help` for help.' }; } } module.exports = Controller;
Add Triangle to shape tests
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75) @pytest.mark.shape class TestTriangle(TestCase, BaseShapeTest): """Tests for the :code:`Triangle` shape.""" def setUp(self): self.shape = Triangle((1,.5),(.2,1),(.4,.5))
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75)
Revert "chore: disable sauce tests for now" This reverts commit 28a0a9db5263bb5408507f520b6fe6aa7404b13b.
const options = { frameworks: ['kocha', 'browserify'], files: [ 'packages/karma-kocha/__tests__/*.js' ], preprocessors: { 'packages/karma-kocha/__tests__/*.js': ['browserify'] }, browserify: { debug: true }, reporters: ['progress'], browsers: ['Chrome'], singleRun: true, plugins: [ require.resolve('./packages/karma-kocha'), 'karma-browserify', 'karma-chrome-launcher' ] } if (process.env.CI) { // Sauce Labs settings const customLaunchers = require('./karma.custom-launchers.js') options.plugins.push('karma-sauce-launcher') options.customLaunchers = customLaunchers options.browsers = Object.keys(options.customLaunchers) options.reporters.push('saucelabs') options.sauceLabs = { testName: 'kocha-ci' } } module.exports = config => config.set(options)
const options = { frameworks: ['kocha', 'browserify'], files: [ 'packages/karma-kocha/__tests__/*.js' ], preprocessors: { 'packages/karma-kocha/__tests__/*.js': ['browserify'] }, browserify: { debug: true }, reporters: ['progress'], browsers: ['Chrome'], singleRun: true, plugins: [ require.resolve('./packages/karma-kocha'), 'karma-browserify', 'karma-chrome-launcher' ] } if (false && process.env.CI) { // Sauce Labs settings const customLaunchers = require('./karma.custom-launchers.js') options.plugins.push('karma-sauce-launcher') options.customLaunchers = customLaunchers options.browsers = Object.keys(options.customLaunchers) options.reporters.push('saucelabs') options.sauceLabs = { testName: 'kocha-ci' } } module.exports = config => config.set(options)
Update the PyPI version to 0.2.20.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.20', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.19', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Add new fxn to null out chars in str range
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; var nullOutChars = function(str, start, end, nullChar) { return str.slice(0, start) + nullChar.repeat(end - start) + str.slice(end); } module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex; module.exports.nullOutChars = nullOutChars;
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex;
Remove reference to non-existent js file.
<!DOCTYPE html> <html lang="en"> <head> <title><?=$page_title || "Simple Paste" ?> by EpochWolf</title> <meta charset="utf-8"> <meta http_equiv="X-UA-Compatible" content="IE=edge;chrome=1"> <meta name="author" content="epochwolf"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/site.css" rel="stylesheet" media="screen"></link> <link href="/favicon.ico" rel="icon"></link> </head> <body> <div id="wrap"> <header id="header"> <h1><a href="/">Simple Paste</a><? if(isset($page_title)){ ?> &mdash; <?=$page_title ?><? } ?></h1> </header> <section id="contents">
<!DOCTYPE html> <html lang="en"> <head> <title><?=$page_title || "Simple Paste" ?> by EpochWolf</title> <meta charset="utf-8"> <meta http_equiv="X-UA-Compatible" content="IE=edge;chrome=1"> <meta name="author" content="epochwolf"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/site.css" rel="stylesheet" media="screen"></link> <link href="/favicon.ico" rel="icon"></link> <script src="/site.js"></script> </head> <body> <div id="wrap"> <header id="header"> <h1><a href="/">Simple Paste</a><? if(isset($page_title)){ ?> &mdash; <?=$page_title ?><? } ?></h1> </header> <section id="contents">
Add notice in the example of servers-side scripting with Lua.
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require 'SharedConfigurations.php'; // This example will not work with versions of Redis < 2.6. // // Additionally to the EVAL command defined in the current development profile, the new // Predis\Commands\ScriptedCommand base class can be used to build an higher abstraction // for our "scripted" commands so that they will appear just like any other command on // the client-side. This is a quick example used to implement INCREX. use Predis\Commands\ScriptedCommand; class IncrementExistingKey extends ScriptedCommand { public function getKeysCount() { return 1; } public function getScript() { return <<<LUA local cmd = redis.call if cmd('exists', KEYS[1]) == 1 then return cmd('incr', KEYS[1]) end LUA; } } $client = new Predis\Client($single_server, 'dev'); $client->getProfile()->defineCommand('increx', 'IncrementExistingKey'); $client->set('foo', 10); var_dump($client->increx('foo')); // int(11) var_dump($client->increx('bar')); // NULL
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require 'SharedConfigurations.php'; // Additionally to the EVAL command defined in the current development profile, the new // Predis\Commands\ScriptedCommand base class can be used to build an higher abstraction // for our "scripted" commands so that they will appear just like any other command on // the client-side. This is a quick example used to implement INCREX. use Predis\Commands\ScriptedCommand; class IncrementExistingKey extends ScriptedCommand { public function getKeysCount() { return 1; } public function getScript() { return <<<LUA local cmd = redis.call if cmd('exists', KEYS[1]) == 1 then return cmd('incr', KEYS[1]) end LUA; } } $client = new Predis\Client($single_server, 'dev'); $client->getProfile()->defineCommand('increx', 'IncrementExistingKey'); $client->set('foo', 10); var_dump($client->increx('foo')); // int(11) var_dump($client->increx('bar')); // NULL
Switch order of login post-processing To try to close re-submit window? See #4784
'use strict'; app.directive('loginForm', [ '$route', 'modelService', 'routerService', '$timeout', function ($route, models, router, $timeout) { return { restrict: 'E', templateUrl: 'party/loginForm.html', link: function ($scope) { var form = $scope.loginForm; form.data = {}; form.submit = function () { form.$setSubmitted(); models.Login.login(form.data).then(function () { form.validator.server({}); if ($route.current.controller === 'party/login') router.back(); else $route.reload(); form.$setPristine(); }, function (res) { form.validator.server(res, true); form.$setUnsubmitted(); }); }; form.validator.client({}, true); $timeout(function(){angular.element('#loginEmail').focus();},100); } }; } ]);
'use strict'; app.directive('loginForm', [ '$route', 'modelService', 'routerService', '$timeout', function ($route, models, router, $timeout) { return { restrict: 'E', templateUrl: 'party/loginForm.html', link: function ($scope) { var form = $scope.loginForm; form.data = {}; form.submit = function () { form.$setSubmitted(); models.Login.login(form.data).then(function () { form.validator.server({}); form.$setPristine(); if ($route.current.controller === 'party/login') router.back(); else $route.reload(); }, function (res) { form.$setUnsubmitted(); form.validator.server(res, true); }); }; form.validator.client({}, true); $timeout(function(){angular.element('#loginEmail').focus();},300); } }; } ]);
Add the documentation to the web site.
# Template makedist.py file # Set WEBSITE to the name of the web site that this package will be # deposited in. The URL will always be: # http://$WEBSITE/$PACKAGE/ WEBSITE = 'untroubled.org' # If LISTSUB is set, makedist will add a note regarding mailing list # subscription. LISTSUB = 'bgware-subscribe@lists.em.ca' LISTURL = 'http://lists.em.ca/?list=bgware' # Set EXTRAS to a list of any extra files that should go into the # base directory in the destination site. EXTRAS = [ 'ANNOUNCEMENT', 'ChangeLog', 'NEWS', 'README', 'TODO', 'doc/html', ] # Set RPMUPLOAD to a list of additional hostname/path destinations to # which to upload the source and binary RPMs. RPMUPLOAD = [ #( 'incoming.redhat.com', 'libc6' ), ] # Set LISTS to the mailing list(s) to send the announcement to LISTS = [ 'bgware@lists.em.ca', ] # Run any extra commands to prepare the source tree (such as making # documentation) here.
# Template makedist.py file # Set WEBSITE to the name of the web site that this package will be # deposited in. The URL will always be: # http://$WEBSITE/$PACKAGE/ WEBSITE = 'untroubled.org' # If LISTSUB is set, makedist will add a note regarding mailing list # subscription. LISTSUB = 'bgware-subscribe@lists.em.ca' LISTURL = 'http://lists.em.ca/?list=bgware' # Set EXTRAS to a list of any extra files that should go into the # base directory in the destination site. EXTRAS = [ 'ANNOUNCEMENT', 'ChangeLog', 'NEWS', 'README', 'TODO', ] # Set RPMUPLOAD to a list of additional hostname/path destinations to # which to upload the source and binary RPMs. RPMUPLOAD = [ #( 'incoming.redhat.com', 'libc6' ), ] # Set LISTS to the mailing list(s) to send the announcement to LISTS = [ 'bgware@lists.em.ca', ] # Run any extra commands to prepare the source tree (such as making # documentation) here.
Update for 1.6.0 - TODO: add Windows
from setuptools import setup setup( name = 'brunnhilde', version = '1.6.0', url = 'https://github.com/timothyryanwalsh/brunnhilde', author = 'Tim Walsh', author_email = 'timothyryanwalsh@gmail.com', py_modules = ['brunnhilde'], scripts = ['brunnhilde.py'], description = 'A Siegfried-based digital archives reporting tool for directories and disk images', keywords = 'archives reporting characterization identification diskimages', platforms = ['POSIX'], test_suite='test', classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: MacOS', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Topic :: Communications :: File Sharing', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Database', 'Topic :: System :: Archiving', 'Topic :: System :: Filesystems', 'Topic :: Utilities' ], )
from setuptools import setup setup( name = 'brunnhilde', version = '1.5.3', url = 'https://github.com/timothyryanwalsh/brunnhilde', author = 'Tim Walsh', author_email = 'timothyryanwalsh@gmail.com', py_modules = ['brunnhilde'], scripts = ['brunnhilde.py'], description = 'A Siegfried-based digital archives reporting tool for directories and disk images', keywords = 'archives reporting characterization identification diskimages', platforms = ['POSIX'], test_suite='test', classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: MacOS', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Topic :: Communications :: File Sharing', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Database', 'Topic :: System :: Archiving', 'Topic :: System :: Filesystems', 'Topic :: Utilities' ], )
[TACHYON-1559] Fix checkstyle errors originating out of changes
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.client; import org.junit.Test; import org.junit.Assert; /** * Tests {@link ClientUtils}. */ public final class ClientUtilsTest { /** * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative. */ @Test public void getRandomNonNegativeLongTest() throws Exception { Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0); } }
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.client; import junit.framework.Assert; import org.junit.Test; /** * Tests {@link ClientUtils}. */ public final class ClientUtilsTest { /** * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative, allowing for zero. */ @Test public void getRandomNonNegativeLongTest() throws Exception { Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0); } }
Use a constant for the 'HASHBROWN_SWITCH_DEFAULTS' settings key so it is easier to re-use.
from django.conf import settings from .models import Switch SETTINGS_KEY = 'HASHBROWN_SWITCH_DEFAULTS' def is_active(label, user=None): defaults = getattr(settings, SETTINGS_KEY, {}) globally_active = defaults[label].get( 'globally_active', False) if label in defaults else False description = defaults[label].get( 'description', '') if label in defaults else '' switch, created = Switch.objects.get_or_create( label=label, defaults={ 'globally_active': globally_active, 'description': description, }) if created: return switch.globally_active if switch.globally_active or ( user and user.available_switches.filter(pk=switch.pk).exists() ): return True return False
from django.conf import settings from .models import Switch def is_active(label, user=None): defaults = getattr(settings, 'HASHBROWN_SWITCH_DEFAULTS', {}) globally_active = defaults[label].get( 'globally_active', False) if label in defaults else False description = defaults[label].get( 'description', '') if label in defaults else '' switch, created = Switch.objects.get_or_create( label=label, defaults={ 'globally_active': globally_active, 'description': description, }) if created: return switch.globally_active if switch.globally_active or ( user and user.available_switches.filter(pk=switch.pk).exists() ): return True return False
Python: Refactor PyYAML tests a bit
import yaml # Unsafe: yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput # Safe yaml.load(payload, yaml.SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML # load_all variants yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
import yaml from yaml import SafeLoader yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
Add _all__ to the module.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import abc import six from st2common.runners.utils import get_logger_for_python_runner_action __all__ = [ 'Action' ] @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import abc import six from st2common.runners.utils import get_logger_for_python_runner_action @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
Fix name of register mime encoder function
// Copyright © 2009--2013 The Web.go Authors // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package web import ( "encoding/json" "encoding/xml" "io" ) // Encode arbitrary data to a response type Encoder interface { Encode(data interface{}) error } type MimeEncoder func(w io.Writer) Encoder var encoders = map[string]MimeEncoder{ "application/json": encodeJSON, "application/xml": encodeXML, "text/xml": encodeXML, } // Register a new mimetype and how it should be encoded func RegisterMimeEncoder(mimetype string, enc MimeEncoder) { encoders[mimetype] = enc } func encodeJSON(w io.Writer) Encoder { return Encoder(json.NewEncoder(w)) } func encodeXML(w io.Writer) Encoder { return Encoder(xml.NewEncoder(w)) }
// Copyright © 2009--2013 The Web.go Authors // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package web import ( "encoding/json" "encoding/xml" "io" ) // Encode arbitrary data to a response type Encoder interface { Encode(data interface{}) error } type MimeEncoder func(w io.Writer) Encoder var encoders = map[string]MimeEncoder{ "application/json": encodeJSON, "application/xml": encodeXML, "text/xml": encodeXML, } // Register a new mimetype and how it should be encoded func RegisterMimeParser(mimetype string, enc MimeEncoder) { encoders[mimetype] = enc } func encodeJSON(w io.Writer) Encoder { return Encoder(json.NewEncoder(w)) } func encodeXML(w io.Writer) Encoder { return Encoder(xml.NewEncoder(w)) }
Fix the tests by mocking the response
from talks.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' DEBUG = True RAVEN_CONFIG = {} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) API_OX_PLACES_URL = '/static/mock/oxpoints.json' API_OX_DATES_URL = API_OX_PLACES_URL # faking the response for dates TOPICS_URL = '/static/mock/topics.json?' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'oxpoints': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'topics': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, } DEBUG = True TEMPLATE_DEBUG = DEBUG
from talks.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' DEBUG = True RAVEN_CONFIG = {} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) API_OX_PLACES_URL = '/static/mock/oxpoints.json' TOPICS_URL = '/static/mock/topics.json?' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'oxpoints': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'topics': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, } DEBUG = True TEMPLATE_DEBUG = DEBUG
Add tests for all builtins
import pytest import sncosmo from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS from sncosmo.magsystems import _MAGSYSTEMS from sncosmo.models import _SOURCES bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()] bandpass_interpolators = [i['name'] for i in _BANDPASS_INTERPOLATORS.get_loaders_metadata()] magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()] sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()] @pytest.mark.might_download @pytest.mark.parametrize("name", bandpasses) def test_builtin_bandpass(name): sncosmo.get_bandpass(name) @pytest.mark.might_download @pytest.mark.parametrize("name", bandpass_interpolators) def test_builtin_bandpass_interpolator(name): interpolator = _BANDPASS_INTERPOLATORS.retrieve(name) interpolator.at(interpolator.minpos()) @pytest.mark.might_download @pytest.mark.parametrize("name,version", sources) def test_builtin_source(name, version): sncosmo.get_source(name, version) @pytest.mark.might_download @pytest.mark.parametrize("name", magsystems) def test_builtin_magsystem(name): sncosmo.get_magsystem(name)
import pytest import sncosmo @pytest.mark.might_download def test_hst_bands(): """ check that the HST and JWST bands are accessible """ for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m', 'f115w']: # jwst nircam sncosmo.get_bandpass(bandname) @pytest.mark.might_download def test_jwst_miri_bands(): for bandname in ['f1130w']: sncosmo.get_bandpass(bandname) @pytest.mark.might_download def test_ztf_bandpass(): bp = sncosmo.get_bandpass('ztfg') @pytest.mark.might_download def test_roman_bandpass(): sncosmo.get_bandpass('f062') sncosmo.get_bandpass('f087') sncosmo.get_bandpass('f106') sncosmo.get_bandpass('f129') sncosmo.get_bandpass('f158') sncosmo.get_bandpass('f184') sncosmo.get_bandpass('f213') sncosmo.get_bandpass('f146')
Fix ChildPages_Teaser for invisible page
<?php class Kwc_List_ChildPages_Teaser_Generator extends Kwf_Component_Generator_Table { protected $_hasNumericIds = false; protected $_idColumn = 'child_id'; protected $_useComponentId = true; protected function _formatConfig($parentData, $row) { $ret = parent::_formatConfig($parentData, $row); $ret['targetPage'] = Kwf_Component_Data_Root::getInstance() ->getComponentByDbId($row->target_page_id, array('subroot'=>$parentData, 'limit'=>1, 'ignoreVisible'=>true)); if (!$ret['targetPage']) return null; //can happen if page was deleted but entry still exists return $ret; } public function getDuplicateProgressSteps($source) { return 0; } public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null) { //don't duplicate children of this generator *here* because we don't know the new child ids yet //as they depend on the new pages (that might not yet exist at this point) return null; } }
<?php class Kwc_List_ChildPages_Teaser_Generator extends Kwf_Component_Generator_Table { protected $_hasNumericIds = false; protected $_idColumn = 'child_id'; protected $_useComponentId = true; protected function _formatConfig($parentData, $row) { $ret = parent::_formatConfig($parentData, $row); $ret['targetPage'] = Kwf_Component_Data_Root::getInstance() ->getComponentByDbId($row->target_page_id, array('subroot'=>$parentData, 'limit'=>1)); if (!$ret['targetPage']) return null; //can happen if page was deleted but entry still exists return $ret; } public function getDuplicateProgressSteps($source) { return 0; } public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null) { //don't duplicate children of this generator *here* because we don't know the new child ids yet //as they depend on the new pages (that might not yet exist at this point) return null; } }
Add option that fixes slow Selenium webdriver startup on systems with low entropy (e.g. VMs).
exports.config = { capabilities: {'browserName': 'chrome'}, /*multiCapabilities: [ {'browserName': 'chrome'}, {'browserName': 'firefox'}, {'browserName': 'opera'}, {'browserName': 'safari'} ],*/ framework: 'jasmine2', jasmineNodeOpts: { showColors: true }, seleniumPort: 4840, /* Due to issues with slow Selenium startup due to RNG, see http://stackoverflow.com/questions/14058111/selenium-server-doesnt-bind-to-socket-after-being-killed-with-sigterm. */ seleniumArgs: ["-Djava.security.egd=file:/dev/./urandom"], onPrepare: function() { browser.driver.manage().window().setSize(1440, 800); browser.get('http://localhost:8000/#'); }, suites: { login: './login/*.test.js', header: './common/*.test.js', case: './cases/*.test.js', users: './users/*.test.js' } };
exports.config = { capabilities: {'browserName': 'chrome'}, /*multiCapabilities: [ {'browserName': 'chrome'}, {'browserName': 'firefox'}, {'browserName': 'opera'}, {'browserName': 'safari'} ],*/ framework: 'jasmine2', jasmineNodeOpts: { showColors: true }, seleniumPort: 4840, onPrepare: function() { browser.driver.manage().window().setSize(1440, 800); browser.get('http://localhost:8000/#'); }, suites: { login: './login/*.test.js', header: './common/*.test.js', case: './cases/*.test.js', users: './users/*.test.js' } };
[studio-hints] Fix position of toggleSidecarButton in the navbar
/* eslint-disable prefer-template */ import React from 'react' import { isSidecarOpenSetting, toggleSidecarOpenState } from 'part:@sanity/default-layout/sidecar-datastore' import Button from 'part:@sanity/components/buttons/default' import HelpCircleIcon from 'part:@sanity/base/help-circle-icon' export default class ToggleSidecarButton extends React.PureComponent { state = { isOpen: true } componentDidMount() { this.subscription = isSidecarOpenSetting.listen().subscribe(isOpen => { this.setState({isOpen: isOpen !== false}) }) } componentWillUnmount() { if (this.subscription) { this.subscription.unsubscribe() } } render() { const {isOpen} = this.state return ( <Button aria-label="Toggle sidecar" aria-pressed={isOpen} icon={HelpCircleIcon} kind="simple" onClick={toggleSidecarOpenState} selected={isOpen} tone="navbar" padding="small" /> ) } }
/* eslint-disable prefer-template */ import React from 'react' import { isSidecarOpenSetting, toggleSidecarOpenState } from 'part:@sanity/default-layout/sidecar-datastore' import Button from 'part:@sanity/components/buttons/default' import HelpCircleIcon from 'part:@sanity/base/help-circle-icon' export default class ToggleSidecarButton extends React.PureComponent { state = { isOpen: true } componentDidMount() { this.subscription = isSidecarOpenSetting.listen().subscribe(isOpen => { this.setState({isOpen: isOpen !== false}) }) } componentWillUnmount() { if (this.subscription) { this.subscription.unsubscribe() } } render() { const {isOpen} = this.state return ( <Button aria-label="Toggle sidecar" aria-pressed={isOpen} icon={HelpCircleIcon} kind="simple" onClick={toggleSidecarOpenState} selected={isOpen} tone="navbar" /> ) } }
Check for 2.8, not 1.8
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ Compatibility for various versions of supporting libraries """ import gtk import gobject # We don't want to get the loud deprecation warnings from PyGtk for using # gobject.type_register() if we don't need it def type_register(type): (major, minor, patch) = gtk.pygtk_version if(major <= 2 and minor < 8): gobject.type_register(type) elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties__') or hasattr(type, '__gsignals__'))): gobject.type_register(type)
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ Compatibility for various versions of supporting libraries """ import gtk import gobject # We don't want to get the loud deprecation warnings from PyGtk for using # gobject.type_register() if we don't need it def type_register(type): (major, minor, patch) = gtk.pygtk_version if(major <= 1 and minor < 8): gobject.type_register(type) elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties__') or hasattr(type, '__gsignals__'))): gobject.type_register(type)
Store the dictItem keys in a map to avoid searching the dict for objects with matching keys (this cut performance tests from 5000ms to 150ms)
'use strict'; var markovDictionaryBuilder = (function() { function buildDict(wordSet, chainSize) { console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize); var map = []; var dict = []; for (var i = 0, len = wordSet.length - chainSize; i < len; i++) { var end = i + parseFloat(chainSize); var workingSet = wordSet.slice(i, end+1); var k = workingSet.slice(0, workingSet.length-1); var n = workingSet.slice(-1); var dictItem = { 'key' : k.join('/').toLowerCase(), 'words' : k, 'next' : n }; var mi = map[dictItem.key]; if (typeof(mi) === 'undefined') { map[dictItem.key] = dict.length; dict.push(dictItem); } else { dict[mi].next.push(dictItem.next[0]); } } return dict; } return { buildDict : buildDict }; })();
'use strict'; var markovDictionaryBuilder = (function() { function buildDict(wordSet, chainSize) { console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize); var dict = []; for (var i = 0, len = wordSet.length - chainSize; i < len; i++) { var end = i + parseFloat(chainSize); var workingSet = wordSet.slice(i, end+1); var k = workingSet.slice(0, workingSet.length-1); var n = [workingSet.slice(-1)]; var dictItem = { 'key' : k.join('/').toLowerCase(), 'words' : k, 'next' : n }; var match = getDictItemByKey(dict, dictItem.key); if (match !== null) { var index = dict.indexOf(match); dict[index].next.push(dictItem.next[0]); } else { dict.push(dictItem); } } //console.log(dict); return dict; } function getDictItemByKey(dict, key) { for (var i = 0, len = dict.length; i < len; i++) { if (dict[i].key === key) return dict[i]; } return null; } return { buildDict : buildDict }; })();
Fix spacing in demo for FileUpload.
package to.etc.domuidemo.pages.overview.allcomponents; import to.etc.domui.component.layout.ContentPanel; import to.etc.domui.component.upload.FileUpload2; import to.etc.domui.component.upload.FileUploadMultiple; import to.etc.domui.component2.form4.FormBuilder; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.HTag; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 14-11-17. */ public class FileUploadFragment extends Div { @Override public void createContent() throws Exception { add(new HTag(2, "File upload component").css("ui-header")); ContentPanel cp = new ContentPanel(); add(cp); FormBuilder fb = new FormBuilder(cp); FileUpload2 u1 = new FileUpload2("png", "jpg", "gif", "jpeg"); fb.label("Select an image").item(u1); FileUploadMultiple u2 = new FileUploadMultiple("png", "jpg", "gif", "jpeg"); fb.label("Select multiple").item(u2); //FileUpload u2 = new FileUpload("png", "jpg", "gif", "jpeg"); //fb.label("OLD").item(u2); } }
package to.etc.domuidemo.pages.overview.allcomponents; import to.etc.domui.component.upload.FileUpload2; import to.etc.domui.component.upload.FileUploadMultiple; import to.etc.domui.component2.form4.FormBuilder; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.HTag; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 14-11-17. */ public class FileUploadFragment extends Div { @Override public void createContent() throws Exception { add(new HTag(2, "File upload component").css("ui-header")); FormBuilder fb = new FormBuilder(this); FileUpload2 u1 = new FileUpload2("png", "jpg", "gif", "jpeg"); fb.label("Select an image").item(u1); FileUploadMultiple u2 = new FileUploadMultiple("png", "jpg", "gif", "jpeg"); fb.label("Select multiple").item(u2); //FileUpload u2 = new FileUpload("png", "jpg", "gif", "jpeg"); //fb.label("OLD").item(u2); } }
Set 10.11.0 as minimum macOS version in the .app bundle
""" This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup from glob import glob import syncplay APP = ['syncplayClient.py'] DATA_FILES = [ ('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')), ] OPTIONS = { 'iconfile':'resources/icon.icns', 'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'}, 'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'}, 'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'], 'plist': { 'CFBundleName':'Syncplay', 'CFBundleShortVersionString':syncplay.version, 'CFBundleIdentifier':'pl.syncplay.Syncplay', 'LSMinimumSystemVersion':'10.11.0', 'NSHumanReadableCopyright': '@ 2018 Syncplay All Rights Reserved' } } setup( app=APP, name='Syncplay', data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
""" This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup from glob import glob import syncplay APP = ['syncplayClient.py'] DATA_FILES = [ ('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')), ] OPTIONS = { 'iconfile':'resources/icon.icns', 'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'}, 'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'}, 'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'], 'plist': { 'CFBundleName':'Syncplay', 'CFBundleShortVersionString':syncplay.version, 'CFBundleIdentifier':'pl.syncplay.Syncplay', 'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved' } } setup( app=APP, name='Syncplay', data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
Switch to local JS/CSS assets - bump version.
from setuptools import setup, find_packages setup( name='wagtailcodeblock', version="0.2.3", description='Wagtail Code Block provides PrismJS syntax highlighting in Wagtail.', long_description='A work-in-progress alpha of a Wagtail Streamfield block for source code with real-time syntax highlighting.', author='Tim Allen', author_email='tallen@wharton.upenn.edu', url='https://github.com/FlipperPA/wagtailcodeblock', include_package_data=True, packages=find_packages(), zip_safe=False, install_requires=[ 'wagtail>=1.8', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
from setuptools import setup, find_packages setup( name='wagtailcodeblock', version="0.2.2", description='Wagtail Code Block provides PrismJS syntax highlighting in Wagtail.', long_description='A work-in-progress alpha of a Wagtail Streamfield block for source code with real-time syntax highlighting.', author='Tim Allen', author_email='tallen@wharton.upenn.edu', url='https://github.com/FlipperPA/wagtailcodeblock', include_package_data=True, packages=find_packages(), zip_safe=False, install_requires=[ 'wagtail>=1.8', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Make sure to load the current module, not some other global one.
#!/usr/bin/env node /** Provide mdb-aggregate, a MongoDB style aggregation pipeline, to NodeJS. Copyright (C) 2014 Charles J. Ezell III This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; //Default to json encoding for the pipeline and data. The user can override //this with --format. var mdb_conduit = require("./index.js"), argv = ["mdb-conduit", "--format", "json-json"], conduit_main = mdb_conduit._conduit_main; //The first two args are usually node and the name of the script, drop them. Array.prototype.push.apply(argv, process.argv.slice(2)); setImmediate(conduit_main, argv, process.env);
#!/usr/bin/env node /** Provide mdb-aggregate, a MongoDB style aggregation pipeline, to NodeJS. Copyright (C) 2014 Charles J. Ezell III This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; //Default to json encoding for the pipeline and data. The user can override //this with --format. var mdb_conduit = require("mdb-conduit"), argv = ["mdb-conduit", "--format", "json-json"], conduit_main = mdb_conduit._conduit_main; //The first two args are usually node and the name of the script, drop them. Array.prototype.push.apply(argv, process.argv.slice(2)); setImmediate(conduit_main, argv, process.env);
Add target to open in a new tab
import React from 'react'; import styled from 'styled-components'; import generalInfos from '../../globals/data/general-info'; const Infos = styled.section` text-align: center; margin: 0.67em 0; `; const Name = styled.h1` font-size: 2.5rem; @media (max-width: 600px) { font-size: 2.2rem; } `; const Info = styled.a` margin: 0.1rem 0; display: inline-block; @media print { color: black; font-style: none; text-decoration: none; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; `; const getProperHref = (type, link) => { if (type === 'email') { return `mailto:${link}`; } else if (type === 'phone') { return `tel:${link}`; } else { return link; } }; const InfoWrapper = () => { return ( <Infos> <Name>Raul de Melo</Name> <InfoContainer> {generalInfos.map(({ id, label, type, link }) => { return ( <Info key={id} href={getProperHref(type, link)} target="_blank"> {label} </Info> ); })} </InfoContainer> </Infos> ); }; export default InfoWrapper;
import React from 'react'; import styled from 'styled-components'; import generalInfos from '../../globals/data/general-info'; const Infos = styled.section` text-align: center; margin: 0.67em 0; `; const Name = styled.h1` font-size: 2.5rem; @media (max-width: 600px) { font-size: 2.2rem; } `; const Info = styled.a` margin: 0.1rem 0; display: inline-block; @media print { color: black; font-style: none; text-decoration: none; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; `; const getProperHref = (type, link) => { if (type === 'email') { return `mailto:${link}`; } else if (type === 'phone') { return `tel:${link}`; } else { return link; } }; const InfoWrapper = () => { return ( <Infos> <Name>Raul de Melo</Name> <InfoContainer> {generalInfos.map(({ id, label, type, link }) => { return ( <Info key={id} href={getProperHref(type, link)}> {label} </Info> ); })} </InfoContainer> </Infos> ); }; export default InfoWrapper;
Make batch less, because sqlite cannot handle big batches
from django.core.management import BaseCommand from django_pyowm.models import Location from pyowm.webapi25.location import Location as LocationEntity from weather_api.weather.singletons import owm class Command(BaseCommand): help = 'Save all locations from file to database' def handle(self, *args, **options): if Location.objects.exists(): self.stderr.write('You can save locations only to empty table') return city_registry = owm.city_id_registry() locations = [] for line in city_registry._get_all_lines(): tokens = line.strip().split(',') try: location_entity = LocationEntity(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4]) location = Location.from_entity(location_entity) locations.append(location) except ValueError: pass Location.objects.bulk_create(locations, 500) self.stdout.write(self.style.SUCCESS('{} locations saved to database'.format(len(locations))))
from django.core.management import BaseCommand from django_pyowm.models import Location from pyowm.webapi25.location import Location as LocationEntity from weather_api.weather.singletons import owm class Command(BaseCommand): help = 'Save all locations from file to database' def handle(self, *args, **options): if Location.objects.exists(): self.stderr.write('You can save locations only to empty table') return city_registry = owm.city_id_registry() locations = [] for line in city_registry._get_all_lines(): tokens = line.strip().split(',') try: location_entity = LocationEntity(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4]) location = Location.from_entity(location_entity) locations.append(location) except ValueError: pass Location.objects.bulk_create(locations, 10000) self.stdout.write(self.style.SUCCESS('{} locations saved to database'.format(len(locations))))
Change NB timeout to 2 minutes, was 10 seconds
/* Copyright 2017 Telstra Open Source * * 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.openkilda.northbound.messaging; public interface MessageConsumer<T> { /** * Kafka message queue poll timeout. */ int POLL_TIMEOUT = 120 * 1000; /** * Kafka message queue poll pause. */ int POLL_PAUSE = 100; /** * Polls Kafka message queue. * * @param correlationId correlation id * @return received message */ T poll(final String correlationId); /** * Clears message queue. */ void clear(); }
/* Copyright 2017 Telstra Open Source * * 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.openkilda.northbound.messaging; public interface MessageConsumer<T> { /** * Kafka message queue poll timeout. */ int POLL_TIMEOUT = 10 * 1000; /** * Kafka message queue poll pause. */ int POLL_PAUSE = 100; /** * Polls Kafka message queue. * * @param correlationId correlation id * @return received message */ T poll(final String correlationId); /** * Clears message queue. */ void clear(); }
Set `include css: true` option for Stylus
module.exports = function(gulp, config) { return function(done) { if(!config.styles) return done() var c = require('better-console') c.info('~ styles') var cssmin = require('gulp-cssmin') var gulpFilter = require('gulp-filter') var nib = require('nib') var path = require('path') var plumber = require('gulp-plumber') var sass = require('gulp-sass') var sourcemaps = require('gulp-sourcemaps') var stylus = require('gulp-stylus') var filterStylus = gulpFilter('**/*.styl') var filterSass = gulpFilter('**/*.scss') var task = gulp.src(config.styles, { base: config.src_folder }) .pipe(plumber({ errorHandler: require('../helpers/error_handler') })) // Stylus part .pipe(filterStylus) .pipe(stylus({ use: nib(), define: { debug: config.devmode }, sourcemap: config.devmode ? { inline: true } : false, "include css": true })) .pipe(filterStylus.restore()) // Sass part .pipe(filterSass) .pipe(sass()) .pipe(filterSass.restore()) // Minimalization if(!config.devmode) { task = task.pipe(cssmin()) } return task.pipe(gulp.dest(config.dist_folder)) } }
module.exports = function(gulp, config) { return function(done) { if(!config.styles) return done() var c = require('better-console') c.info('~ styles') var cssmin = require('gulp-cssmin') var gulpFilter = require('gulp-filter') var nib = require('nib') var path = require('path') var plumber = require('gulp-plumber') var sass = require('gulp-sass') var sourcemaps = require('gulp-sourcemaps') var stylus = require('gulp-stylus') var filterStylus = gulpFilter('**/*.styl') var filterSass = gulpFilter('**/*.scss') var task = gulp.src(config.styles, { base: config.src_folder }) .pipe(plumber({ errorHandler: require('../helpers/error_handler') })) // Stylus part .pipe(filterStylus) .pipe(stylus({ use: nib(), define: { debug: config.devmode }, sourcemap: config.devmode ? { inline: true } : false })) .pipe(filterStylus.restore()) // Sass part .pipe(filterSass) .pipe(sass()) .pipe(filterSass.restore()) // Minimalization if(!config.devmode) { task = task.pipe(cssmin()) } return task.pipe(gulp.dest(config.dist_folder)) } }
Use custom endpoint url in AWS_HOST_URL variable
from django.conf import settings AWS_ACCESS_KEY_ID = getattr(settings, 'AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = getattr(settings, 'AWS_SECRET_ACCESS_KEY') AWS_STATIC_BUCKET_NAME = getattr(settings, 'AWS_STATIC_BUCKET_NAME') AWS_MEDIA_ACCESS_KEY_ID = getattr( settings, 'AWS_MEDIA_ACCESS_KEY_ID', AWS_ACCESS_KEY_ID) AWS_MEDIA_SECRET_ACCESS_KEY = getattr( settings, 'AWS_MEDIA_SECRET_ACCESS_KEY', AWS_SECRET_ACCESS_KEY) AWS_MEDIA_BUCKET_NAME = getattr(settings, 'AWS_MEDIA_BUCKET_NAME') AWS_S3_ENDPOINT_URL = getattr( settings, 'AWS_S3_ENDPOINT_URL', 's3.amazonaws.com') AWS_HOST_URL = 'https://%%(bucket_name)s.%s/' % AWS_S3_ENDPOINT_URL AWS_POLICY = 'public-read' IGNORE_FILES = getattr(settings, 'OFFSITE_STORAGE_IGNORE_FILES', ['*.less', '*.scss', '*.txt', 'components'])
from django.conf import settings AWS_ACCESS_KEY_ID = getattr(settings, 'AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = getattr(settings, 'AWS_SECRET_ACCESS_KEY') AWS_STATIC_BUCKET_NAME = getattr(settings, 'AWS_STATIC_BUCKET_NAME') AWS_MEDIA_ACCESS_KEY_ID = getattr( settings, 'AWS_MEDIA_ACCESS_KEY_ID', AWS_ACCESS_KEY_ID) AWS_MEDIA_SECRET_ACCESS_KEY = getattr( settings, 'AWS_MEDIA_SECRET_ACCESS_KEY', AWS_SECRET_ACCESS_KEY) AWS_MEDIA_BUCKET_NAME = getattr(settings, 'AWS_MEDIA_BUCKET_NAME') AWS_S3_ENDPOINT_URL = getattr( settings, 'AWS_S3_ENDPOINT_URL', 's3.amazonaws.com') AWS_HOST_URL = 'https://%(bucket_name)s.s3.amazonaws.com/' AWS_POLICY = 'public-read' IGNORE_FILES = getattr(settings, 'OFFSITE_STORAGE_IGNORE_FILES', ['*.less', '*.scss', '*.txt', 'components'])
Remove Contexts for now so we don't step in to dependency hell
define(['underscore', 'jquery'], function(_, $) { return function(app) { app.components.before('initialize', function() { "use strict"; if (this.require && this.require.paths) { var dfd = $.Deferred(); var requireConfig = this.require; var localRequire = require.config(_.extend(requireConfig, { // context: 'context-' + this.ref, baseUrl: this.options.require.packages[0].location })); localRequire(_.keys(this.require.paths), function(deps) { dfd.resolve(); }, function (err) { dfd.reject(err); }); this.require = localRequire; return dfd.promise(); } }); }; });
define(['underscore', 'jquery'], function(_, $) { return function(app) { app.components.before('initialize', function() { "use strict"; if (this.require && this.require.paths) { var dfd = $.Deferred(); var requireConfig = this.require; var localRequire = require.config(_.extend(requireConfig, { context: 'context-' + this.ref, baseUrl: this.options.require.packages[0].location })); localRequire(_.keys(this.require.paths), function(deps) { dfd.resolve(); }, function (err) { dfd.reject(err); }); this.require = localRequire; return dfd.promise(); } }); }; });
Use find_packages instead of listing them manually.
# coding: utf-8 from setuptools import find_packages, setup # lets prepare our initial setup setup_dict = {'name': 'PYSCSI', 'version': '1.0', 'license': 'LGPLv2.1', 'author': 'Ronnie Sahlberg', 'author_email': 'ronniesahlberg@gmail.com', 'description': 'Module for calling SCSI devices from Python', 'packages': find_packages(), 'python_requires': '~=3.7', 'extras_require': {'sgio': ['cython-sgio'], 'iscsi': ['cython-iscsi'], }, } setup(**setup_dict)
# coding: utf-8 from setuptools import setup # lets prepare our initial setup setup_dict = {'name': 'PYSCSI', 'version': '1.0', 'license': 'LGPLv2.1', 'author': 'Ronnie Sahlberg', 'author_email': 'ronniesahlberg@gmail.com', 'description': 'Module for calling SCSI devices from Python', 'packages': ['pyscsi', 'pyscsi.pyscsi', 'pyscsi.pyiscsi', 'pyscsi.utils'], 'python_requires': '~=3.7', 'extras_require': {'sgio': ['cython-sgio'], 'iscsi': ['cython-iscsi'], }, } setup(**setup_dict)
Add link to geolocation example into sitemap
import Ember from "ember"; export default Ember.Controller.extend({ sitemap: { nodes: [ { link: "index", title: "Home" }, { title: "Admin panel", children: [ { link: "suggestionTypes", title: "Suggestion Types" }, { link: "users", title: "Application Users" } ] }, { link: "suggestions.new", title: "Добавить предложение" }, { title: "Разное", children: [ { link: "geolocation", title: "Геолокация" } ] } ] } });
import Ember from 'ember'; export default Ember.Controller.extend({ sitemap: { nodes: [ { link: 'index', title: 'Home', children: null }, { link: null, title: 'Admin panel', children: [ { link: 'suggestionTypes', title: 'Suggestion Types', children: null }, { link: 'users', title: 'Application Users', children: null } ] }, { link: 'suggestions.new', title: 'Добавить предложение', children: null } ] } });
Remove an import that deprecated and unused
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from tabledata import DataError, InvalidHeaderNameError, InvalidTableNameError from .__version__ import __author__, __copyright__, __email__, __license__, __version__ from ._constant import PatternMatch from ._logger import logger, set_log_level, set_logger from .csv.core import CsvTableFileLoader, CsvTableTextLoader from .error import ( APIError, HTTPError, InvalidFilePathError, LoaderNotFoundError, OpenError, PathError, ProxyError, PypandocImportError, UrlError, ValidationError, ) from .html.core import HtmlTableFileLoader, HtmlTableTextLoader from .json.core import JsonTableDictLoader, JsonTableFileLoader, JsonTableTextLoader from .jsonlines.core import JsonLinesTableFileLoader, JsonLinesTableTextLoader from .loadermanager import TableFileLoader, TableUrlLoader from .ltsv.core import LtsvTableFileLoader, LtsvTableTextLoader from .markdown.core import MarkdownTableFileLoader, MarkdownTableTextLoader from .mediawiki.core import MediaWikiTableFileLoader, MediaWikiTableTextLoader from .spreadsheet.excelloader import ExcelTableFileLoader from .spreadsheet.gsloader import GoogleSheetsTableLoader from .sqlite.core import SqliteFileLoader from .tsv.core import TsvTableFileLoader, TsvTableTextLoader
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from tabledata import ( DataError, EmptyDataError, InvalidDataError, InvalidHeaderNameError, InvalidTableNameError, ) from .__version__ import __author__, __copyright__, __email__, __license__, __version__ from ._constant import PatternMatch from ._logger import logger, set_log_level, set_logger from .csv.core import CsvTableFileLoader, CsvTableTextLoader from .error import ( APIError, HTTPError, InvalidFilePathError, LoaderNotFoundError, OpenError, PathError, ProxyError, PypandocImportError, UrlError, ValidationError, ) from .html.core import HtmlTableFileLoader, HtmlTableTextLoader from .json.core import JsonTableDictLoader, JsonTableFileLoader, JsonTableTextLoader from .jsonlines.core import JsonLinesTableFileLoader, JsonLinesTableTextLoader from .loadermanager import TableFileLoader, TableUrlLoader from .ltsv.core import LtsvTableFileLoader, LtsvTableTextLoader from .markdown.core import MarkdownTableFileLoader, MarkdownTableTextLoader from .mediawiki.core import MediaWikiTableFileLoader, MediaWikiTableTextLoader from .spreadsheet.excelloader import ExcelTableFileLoader from .spreadsheet.gsloader import GoogleSheetsTableLoader from .sqlite.core import SqliteFileLoader from .tsv.core import TsvTableFileLoader, TsvTableTextLoader
Fix raw md content rendering
# -*- coding: utf-8 -*- from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
# -*- coding: utf-8 -*- from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_file_path, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
Update import to correct path for Django 1.4->1.6 compatibility
from django.utils.functional import Promise from django.utils.encoding import force_unicode def resolve_promise(o): if isinstance(o, dict): for k, v in o.items(): o[k] = resolve_promise(v) elif isinstance(o, (list, tuple)): o = [resolve_promise(x) for x in o] elif isinstance(o, Promise): try: o = force_unicode(o) except: # Item could be a lazy tuple or list try: o = [resolve_promise(x) for x in o] except: raise Exception('Unable to resolve lazy object %s' % o) elif callable(o): o = o() return o
from django.utils.functional import Promise from django.utils.translation import force_unicode def resolve_promise(o): if isinstance(o, dict): for k, v in o.items(): o[k] = resolve_promise(v) elif isinstance(o, (list, tuple)): o = [resolve_promise(x) for x in o] elif isinstance(o, Promise): try: o = force_unicode(o) except: # Item could be a lazy tuple or list try: o = [resolve_promise(x) for x in o] except: raise Exception('Unable to resolve lazy object %s' % o) elif callable(o): o = o() return o
Clean up data table value-based row classes
<?php namespace ATPViz\Widget; class DataTable extends \ATPViz\Widget\AbstractWidget { public function __construct() { parent::__construct(); $this->setTemplate('atp-viz/widget/dataTable.phtml'); } public function getClasses($row) { $classes = array(); if(isset($this->classFields)) { foreach($this->classFields as $field) { $value = $row[$field]; $method = "get{$field}Class"; if(method_exists($this, $method)) $value = $this->$method($value); $class = str_replace(array("/", " "), "-", trim("{$field}-{$value}")); while(strpos($class, "--") !== false) $class = str_replace("--", "-", $class); $classes[] = $class; } } return implode(" ", $classes); } public function getSampleData() { return array( 'columns' => array('First Column', 'Second Column', 'Third Column'), 'data' => array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ) ); } }
<?php namespace ATPViz\Widget; class DataTable extends \ATPViz\Widget\AbstractWidget { public function __construct() { parent::__construct(); $this->setTemplate('atp-viz/widget/dataTable.phtml'); } public function getClasses($row) { $classes = array(); if(isset($this->classFields)) { foreach($this->classFields as $field) { $value = $row[$field]; $method = "get{$field}Class"; if(method_exists($this, $method)) $value = $this->$method($value); $classes[] = str_replace(" ", "-", "{$field}-{$value}"); } } return implode(" ", $classes); } public function getSampleData() { return array( 'columns' => array('First Column', 'Second Column', 'Third Column'), 'data' => array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ) ); } }
[FIX] module_auto_update: Rollback cursor if param exists Without this patch, when upgrading after you have stored the deprecated features parameter, the cursor became broken and no more migrations could happen. You got this error: Traceback (most recent call last): File "/usr/local/bin/odoo", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/opt/odoo/custom/src/odoo/odoo.py", line 160, in <module> main() File "/opt/odoo/custom/src/odoo/odoo.py", line 157, in main openerp.cli.main() File "/opt/odoo/custom/src/odoo/openerp/cli/command.py", line 64, in main o.run(args) File "/opt/odoo/custom/src/odoo/openerp/cli/shell.py", line 65, in run self.shell(openerp.tools.config['db_name']) File "/opt/odoo/custom/src/odoo/openerp/cli/shell.py", line 52, in shell registry = openerp.modules.registry.RegistryManager.get(dbname) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 355, in get update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 386, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 335, in load_modules force, status, report, loaded_modules, update_module) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 239, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/opt/odoo/custom/src/odoo/openerp/modules/loading.py", line 136, in load_module_graph registry.setup_models(cr, partial=True) File "/opt/odoo/custom/src/odoo/openerp/modules/registry.py", line 186, in setup_models cr.execute('select model, transient from ir_model where state=%s', ('manual',)) File "/opt/odoo/custom/src/odoo/openerp/sql_db.py", line 154, in wrapper return f(self, *args, **kwargs) File "/opt/odoo/custom/src/odoo/openerp/sql_db.py", line 233, in execute res = self._obj.execute(query, params) psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block Now you can safely migrate, be that parameter pre-created or not.
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def migrate(cr, version): """Autoenable deprecated behavior.""" try: with cr.savepoint(): cr.execute( """INSERT INTO ir_config_parameter (key, value) VALUES (%s, '1')""", (PARAM_DEPRECATED,) ) _logger.warn("Deprecated features have been autoenabled, see " "addon's README to know how to upgrade to the new " "supported autoupdate mechanism.") except IntegrityError: _logger.info("Deprecated features setting exists, not autoenabling")
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def migrate(cr, version): """Autoenable deprecated behavior.""" try: cr.execute( "INSERT INTO ir_config_parameter (key, value) VALUES (%s, '1')", (PARAM_DEPRECATED,) ) _logger.warn("Deprecated features have been autoenabled, see " "addon's README to know how to upgrade to the new " "supported autoupdate mechanism.") except IntegrityError: _logger.info("Deprecated features setting exists, not autoenabling")
Set urls for bucketlist items endpoints
from flask_restful import Api from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import app, db from app.auth import Register, Login from app.bucketlist_api import BucketLists, BucketListSingle from app.bucketlist_items import BucketListItems, BucketListItemSingle migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) api = Api(app) api.add_resource(Register, '/auth/register') api.add_resource(Login, '/auth/login') api.add_resource(BucketLists, '/bucketlists') api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>') api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items') api.add_resource(BucketListItemSingle, '/bucketlists/<int:bucketlist_id>/items/<int:item_id>') if __name__ == '__main__': manager.run()
from flask_restful import Api from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import app from app import db from app.auth import Register, Login from app.bucketlist_api import BucketList, BucketListEntry from app.bucketlist_items import BucketListItems, BucketListItemSingle migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) api = Api(app) api.add_resource(Register, '/auth/register') api.add_resource(Login, '/auth/login') api.add_resource(BucketList, '/bucketlists') api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>') api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items') api.add_resource(BucketListItemSingle, '/bucketlists/<int:bucketlist_id>/items/<int:item_id>') if __name__ == '__main__': manager.run()
Fix preflight fn to match request path against preflight config path, not the other way around
/** * Module dependencies. */ var _ = require('lodash'); var pathToRegexp = require('path-to-regexp'); /** * @optional {Dictionary} _routeCorsConfig * * @optional {Boolean} isOptionsRoute * if set, use the `access-control-request-method` header * as the method when looking up the route's CORS configuration * * @return {Function} * A configured middleware function which sets the appropriate headers. */ module.exports = function setPreflightConfig(preflightConfigs, defaultConfig) { return function (req, cb) { var path = req.path; var method = (req.headers['access-control-request-method'] || '').toLowerCase() || 'default'; var regex = pathToRegexp(path, []); var corsConfig = _.reduce(preflightConfigs, function(memo, configs, preflightConfigPath) { if (memo) {return memo;} var regex = pathToRegexp(preflightConfigPath, []); if (path.match(regex) && (configs[method] || configs.default)) { return (configs[method] || configs.default); } }, null); if (!corsConfig) { return cb(null, { origin: false }); } return cb(null, _.extend({}, defaultConfig, corsConfig)); }; };
/** * Module dependencies. */ var _ = require('lodash'); var pathToRegexp = require('path-to-regexp'); /** * @optional {Dictionary} _routeCorsConfig * * @optional {Boolean} isOptionsRoute * if set, use the `access-control-request-method` header * as the method when looking up the route's CORS configuration * * @return {Function} * A configured middleware function which sets the appropriate headers. */ module.exports = function setPreflightConfig(preflightConfigs, defaultConfig) { return function (req, cb) { // console.log(preflightConfigs); var path = req.path; var method = (req.headers['access-control-request-method'] || '').toLowerCase() || 'default'; var regex = pathToRegexp(path, []); var corsConfig = _.reduce(preflightConfigs, function(memo, configs, path) { if (memo) {return memo;} if (path.match(regex) && (configs[method] || configs.default)) { return (configs[method] || configs.default); } }, null); // console.log(corsConfig); if (!corsConfig) { return cb(null, { origin: false }); } return cb(null, _.extend({}, defaultConfig, corsConfig)); }; };
Set parameter name for flag
package main import ( "flag" "fmt" "os" "github.com/glaslos/tlsh" ) var ( // VERSION is set by the makefile VERSION = "v0.0.0" // BUILDDATE is set by the makefile BUILDDATE = "" ) func main() { var file = flag.String("f", "", "path to the `file` to be hashed") var raw = flag.Bool("r", false, "set to get only the hash") var version = flag.Bool("version", false, "print version") flag.Parse() if *version { fmt.Printf("%s %s\n", VERSION, BUILDDATE) return } if *file == "" { fmt.Fprintf(os.Stderr, "Usage of %s [-f <file>]\n\n", os.Args[0]) flag.PrintDefaults() fmt.Println() return } hash, err := tlsh.Hash(*file) if err != nil { fmt.Println(err) return } if *raw { fmt.Println(hash) } else { fmt.Printf("%s %s\n", hash, *file) } }
package main import ( "flag" "fmt" "os" "github.com/glaslos/tlsh" ) var ( // VERSION is set by the makefile VERSION = "v0.0.0" // BUILDDATE is set by the makefile BUILDDATE = "" ) func main() { var file = flag.String("f", "", "path to the file to be hashed") var raw = flag.Bool("r", false, "set to get only the hash") var version = flag.Bool("version", false, "print version") flag.Parse() if *version { fmt.Printf("%s %s\n", VERSION, BUILDDATE) return } if *file == "" { fmt.Fprintf(os.Stderr, "Usage of %s [-f <file>]\n\n", os.Args[0]) flag.PrintDefaults() fmt.Println() return } hash, err := tlsh.Hash(*file) if err != nil { fmt.Println(err) return } if *raw { fmt.Println(hash) } else { fmt.Printf("%s %s\n", hash, *file) } }
Stop the host on window unload
const { getQueryStringParam, substanceGlobals, platform } = window.substance const { StencilaDesktopApp } = window.stencila const ipc = require('electron').ipcRenderer const darServer = require('dar-server') const { FSStorageClient } = darServer const url = require('url') const path = require('path') const remote = require('electron').remote const { shell } = remote const host = require('stencila-node').host // HACK: we should find a better solution to intercept window.open calls // (e.g. as done by LinkComponent) window.open = function(url /*, frameName, features*/) { shell.openExternal(url) } window.addEventListener('load', () => { substanceGlobals.DEBUG_RENDERING = platform.devtools // Starts the stencila/node Host and connect it // to the internal host via the STENCILA_HOSTS // variable. There are probably better ways to do this // but this works, providing integration with limited changes elsewhere host.start().then(() => { window.STENCILA_HOSTS = host.urls[0] + '|' + host.key StencilaDesktopApp.mount({ archiveId: getQueryStringParam('archiveDir'), ipc, url, path, shell, FSStorageClient, __dirname }, window.document.body) }) }) window.addEventListener('beforeunload', () => { // Stop the host (and any peer hosts that it has spawned) host.stop() })
const { getQueryStringParam, substanceGlobals, platform } = window.substance const { StencilaDesktopApp } = window.stencila const ipc = require('electron').ipcRenderer const darServer = require('dar-server') const { FSStorageClient } = darServer const url = require('url') const path = require('path') const remote = require('electron').remote const { shell } = remote const host = require('stencila-node').host // HACK: we should find a better solution to intercept window.open calls // (e.g. as done by LinkComponent) window.open = function(url /*, frameName, features*/) { shell.openExternal(url) } window.addEventListener('load', () => { substanceGlobals.DEBUG_RENDERING = platform.devtools // Starts the stencila/node Host and connect it // to the internal host via the STENCILA_HOSTS // variable. There are probably better ways to do this // but this works, providing integration with limited changes elsewhere host.start().then(() => { window.STENCILA_HOSTS = host.urls[0] + '|' + host.key StencilaDesktopApp.mount({ archiveId: getQueryStringParam('archiveDir'), ipc, url, path, shell, FSStorageClient, __dirname }, window.document.body) }) })
Fix bug in ticker widget width set
/** * Shows arbitrary text in a news ticker-like fashion. * * The widget is designed to have a very small height in comparison to its width. This can be * achieved by increasing the granularity of the widget sizes in the config, e.g. by setting the * `dim[1]` of the grid to a high value and scaling accordingly the heights of the existing * widgets. * * Expects data from sources as simple strings. */ Dashboard.TickerWidget = Dashboard.Widget.extend({ sourceData: "", templateName: 'ticker_widget', classNames: ['widget', 'widget-ticker'], widgetView: function() { var widget = this; return this._super().reopen({ didInsertElement: function() { var scaleFactor = 0.7; var widgetHeight = this.$().height(); var fontSize = widgetHeight * scaleFactor; var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) / DashboardConfig.dim[0] - DashboardConfig.widgetMargins; var widgetWidth = widgetUnitWidth * widget.get('sizex') + DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5; this.$().css('font-size', fontSize + 'px'); this.$().css('max-width', widgetWidth + 'px'); } }); }.property() });
/** * Shows arbitrary text in a news ticker-like fashion. * * The widget is designed to have a very small height in comparison to its width. This can be * achieved by increasing the granularity of the widget sizes in the config, e.g. by setting the * `dim[1]` of the grid to a high value and scaling accordingly the heights of the existing * widgets. * * Expects data from sources as simple strings. */ Dashboard.TickerWidget = Dashboard.Widget.extend({ sourceData: "", templateName: 'ticker_widget', classNames: ['widget', 'widget-ticker'], widgetView: function() { var widget = this; return this._super().reopen({ didInsertElement: function() { var scaleFactor = 0.7; var widgetHeight = this.$().height(); var fontSize = widgetHeight * scaleFactor; var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) / DashboardConfig.dim[0] - DashboardConfig.widgetMargins; var widgetWidth = widgetUnitWidth * widget.get('sizex') + DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5; this.$().css('font-size', fontSize + 'px'); this.$('.marquee').css('max-width', widgetWidth + 'px'); } }); }.property() });
Refactor region utils a bit and add a method
import assert from 'assert' const TYPE_TO_PREFIX = { municipality: 'K', borough: 'B', county: 'F', commerceRegion: 'N' } const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIX).reduce((acc, key) => { acc[TYPE_TO_PREFIX[key]] = key return acc }, {}) const REGION_TYPE_TO_ID_FIELD_MAPPING = { municipality: 'kommuneNr', county: 'fylkeNr', commerceRegion: 'naringsregionNr' } module.exports = { split: region => { return [ region.substring(0, 1).toUpperCase(), region.substring(1) ] }, prefixify: region => { assert(TYPE_TO_PREFIX[region.type], `No prefix registered for region type ${region.type}`) return TYPE_TO_PREFIX[region.type] + region.code }, getHeaderKey: region => { assert(REGION_TYPE_TO_ID_FIELD_MAPPING[region.type], `No mapping from region type ${region.type} to header key found`) return REGION_TYPE_TO_ID_FIELD_MAPPING[region.type] }, typeForPrefix: prefix => { return PREFIX_TO_TYPE[prefix.toUpperCase()] } }
import assert from 'assert' const TYPE_TO_PREFIXES = { municipality: 'K', borough: 'B', county: 'F', commerceRegion: 'N' } // we might need this reverse mapping at some point later //const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIXES).reduce((acc, key) => { // acc[TYPE_TO_PREFIXES[key]] = key // return acc //}, {}) const REGION_TYPE_TO_ID_FIELD_MAPPING = { municipality: 'kommuneNr', county: 'fylkeNr', commerceRegion: 'naringsregionNr' } export function split(region) { return [ region.substring(0, 1).toUpperCase(), region.substring(1) ] } export function prefixify(region) { assert(TYPE_TO_PREFIXES[region.type], `No prefix registered for region type ${region.type}`) return TYPE_TO_PREFIXES[region.type] + region.code } export function getHeaderKey(region) { assert(REGION_TYPE_TO_ID_FIELD_MAPPING[region.type], `No mapping from region type ${region.type} to header key found`) return REGION_TYPE_TO_ID_FIELD_MAPPING[region.type] }
Use search.rnacentral.org as the sequence search endpoint
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute 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. """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' # minimum query sequence length MIN_LENGTH = 10 # maximum query sequence length MAX_LENGTH = 10000
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute 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. """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally # SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' # minimum query sequence length MIN_LENGTH = 10 # maximum query sequence length MAX_LENGTH = 10000
Revert "Added ip address in order to access the debug toolbar" This reverts commit 59832b211b7ddefe84f723bac08849a4feda0798.
<?php use Symfony\Component\Debug\Debug; $filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); if (php_sapi_name() === 'cli-server' && is_file($filename)) { return false; } // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } require_once __DIR__.'/../vendor/autoload.php'; Debug::enable(); $app = require __DIR__.'/../src/app.php'; require __DIR__.'/../config/dev.php'; require __DIR__.'/../src/controllers.php'; $app->run();
<?php use Symfony\Component\Debug\Debug; $filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); if (php_sapi_name() === 'cli-server' && is_file($filename)) { return false; } // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '83.86.115.104', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } require_once __DIR__.'/../vendor/autoload.php'; Debug::enable(); $app = require __DIR__.'/../src/app.php'; require __DIR__.'/../config/dev.php'; require __DIR__.'/../src/controllers.php'; $app->run();
chore: Update to Inheritance Inversion HOC
// core import React, { PropTypes, Component } from 'react'; import { BackAndroid } from 'react-native'; // utils import isAndroid from '../utils/isAndroid.js'; export default function hardwareBackPress(MyComponent) { if (isAndroid()) { return class EnhancedComponent extends MyComponent { static contextTypes = { backAndroid: PropTypes.object, }; componentDidMount() { const { backAndroid } = this.context; if (this.handleHardwareBackPress) { backAndroid.onHardwareBackPress(this.handleHardwareBackPress); } if (super.componentDidMount) { super.componentDidMount(); } } componentWillUnmount() { const { backAndroid } = this.context; if (this.handleHardwareBackPress) { backAndroid.offHardwareBackPress(this.handleHardwareBackPress); } if (super.componentWillUnmount) { super.componentWillUnmount(); } } render() { return super.render(); } } } return MyComponent; }
// core import React, { PropTypes, Component } from 'react'; import { BackAndroid } from 'react-native'; // utils import isAndroid from '../utils/isAndroid.js'; export default function hardwareBackPress(MyComponent) { if (isAndroid()) { class EnhancedComponent extends Component { static contextTypes = { backAndroid: PropTypes.object, }; componentDidMount() { const { backAndroid } = this.context; const { handleHardwareBackPress } = this.refs.child; if (handleHardwareBackPress) { backAndroid.onHardwareBackPress(handleHardwareBackPress); } } componentWillUnmount() { const { backAndroid } = this.context; const { handleHardwareBackPress } = this.refs.child; if (handleHardwareBackPress) { backAndroid.offHardwareBackPress(handleHardwareBackPress); } } render() { return ( <MyComponent ref="child" {...this.props} /> ); } } return EnhancedComponent; } return MyComponent; }
Increase apk size limit to 4.5MB
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Check APK file size for limit from os import path, listdir, stat from sys import exit SIZE_LIMIT = 4500000 PATH = path.join(path.dirname(path.abspath(__file__)), '../../app/build/outputs/apk/') files = [] try: files = [f for f in listdir(PATH) if path.isfile(path.join(PATH, f)) and f.endswith('.apk') and "release" in f] except OSError as e: if e.errno == 2: print("Directory is missing, build apk first!") exit(1) print("Unknown error: {err}".format(err=str(e))) exit(2) for apk_file in files: file_size = stat(path.join(PATH, apk_file)).st_size if file_size > SIZE_LIMIT: print(" * [TOOBIG] {filename} ({filesize} > {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT )) exit(27) print(" * [OKAY] {filename} ({filesize} <= {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT ))
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Check APK file size for limit from os import path, listdir, stat from sys import exit SIZE_LIMIT = 4194304 PATH = path.join(path.dirname(path.abspath(__file__)), '../../app/build/outputs/apk/') files = [] try: files = [f for f in listdir(PATH) if path.isfile(path.join(PATH, f)) and f.endswith('.apk') and "release" in f] except OSError as e: if e.errno == 2: print("Directory is missing, build apk first!") exit(1) print("Unknown error: {err}".format(err=str(e))) exit(2) for apk_file in files: file_size = stat(path.join(PATH, apk_file)).st_size if file_size > SIZE_LIMIT: print(" * [TOOBIG] {filename} ({filesize} > {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT )) exit(27) print(" * [OKAY] {filename} ({filesize} <= {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT ))
Remove extra double quote from docstring The extra " was visible on http://docs.openstack.org/developer/python-swiftclient/swiftclient.html Change-Id: I7d61c8259a4f13464c11ae7e3fa28eb3a58e4baa
# -*- encoding: utf-8 -*- # Copyright (c) 2012 Rackspace # flake8: noqa # 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. """ OpenStack Swift Python client binding. """ from .client import * # At setup.py time, we haven't installed anything yet, so there # is nothing that is able to set this version property. Squelching # that exception here should be fine- if there are problems with # pkg_resources in a real install, that will manifest itself as # an error still try: from swiftclient import version __version__ = version.version_string except Exception: pass
# -*- encoding: utf-8 -*- # Copyright (c) 2012 Rackspace # flake8: noqa # 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. """" OpenStack Swift Python client binding. """ from .client import * # At setup.py time, we haven't installed anything yet, so there # is nothing that is able to set this version property. Squelching # that exception here should be fine- if there are problems with # pkg_resources in a real install, that will manifest itself as # an error still try: from swiftclient import version __version__ = version.version_string except Exception: pass
Fix job timer during build.
/* eslint-disable no-console */ const writeLine = (line) => console.log(line); /* eslint-enable no-console */ const runTask = async (task) => { const startTime = Date.now(); writeLine(`Starting ${task.name}`); return new Promise(task) .catch((err) => { writeLine(err); process.exit(1); }) .then(() => writeLine(`Finished ${task.name} in ${Date.now() - startTime}ms`)); }; const runJobSeries = async (tasks) => tasks.reduce(async (previous, next) => { await previous; return runTask(next); }, Promise.resolve()); const build = (availableJobs) => { const startTime = Date.now(); const jobName = Object.keys(availableJobs).includes(process.argv[2]) ? process.argv[2] : 'default'; writeLine(`Running job ${jobName}`); runJobSeries(availableJobs[jobName]) .then(() => writeLine(`Done in ${Date.now() - startTime}ms`)); }; module.exports = build;
/* eslint-disable no-console */ const writeLine = (line) => console.log(line); /* eslint-enable no-console */ const runTask = async (task) => { const startTime = Date.now(); writeLine(`Starting ${task.name}`); await new Promise(task) .catch((err) => { writeLine(err); process.exit(1); }) .then(() => writeLine(`Finished ${task.name} in ${Date.now() - startTime}ms`)); }; const runJobSeries = (tasks) => { tasks.reduce(async (previous, next) => { await previous; return runTask(next); }, Promise.resolve()); }; const build = (availableJobs) => { const startTime = Date.now(); const jobName = Object.keys(availableJobs).includes(process.argv[2]) ? process.argv[2] : 'default'; writeLine(`Running job ${jobName}`); runJobSeries(availableJobs[jobName]); writeLine(`Done in ${Date.now() - startTime}ms`); }; module.exports = build;
Fix long_description, bump to 2.0.1
#!/usr/bin/env python import pathlib from setuptools import setup here = pathlib.Path(__file__).parent.resolve() long_description = (here / "README.rst").read_text(encoding='utf-8') setup( name='od', version='2.0.1', description='Shorthand syntax for building OrderedDicts', long_description=long_description, long_description_content_type='text/x-rst', license='MIT', url='https://github.com/epsy/od', author='Yann Kaiser', author_email='kaiser.yann@gmail.com', py_modules=('od', 'test_od'), extras_require={ 'test': ['repeated_test'], }, keywords=[ 'OrderedDict', 'od', 'syntactic sugar', ], classifiers=[ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], )
#!/usr/bin/env python from setuptools import setup setup( name='od', version='2.0.0', description='Shorthand syntax for building OrderedDicts', license='MIT', url='https://github.com/epsy/od', author='Yann Kaiser', author_email='kaiser.yann@gmail.com', py_modules=('od', 'test_od'), extras_require={ 'test': ['repeated_test'], }, keywords=[ 'OrderedDict', 'od', 'syntactic sugar', ], classifiers=[ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], )
Update Arch package to 2.7
# # Biicode Arch Linux package settings. # # Check PKGBUILD_template docs for those settings and # what they mean. # def settings(): return { "version": "2.7", "release_number": "1", "arch_deps": ["cmake>=3.0.2", "zlib", "glibc", "sqlite", "wget", "python2-pmw" ], "debian_deps": ["zlib1g", "libc-bin", "libsqlite3-0", "wget", "lib32z1", "python-tk" ] } if __name__ == '__main__': print(settings())
# # Biicode Arch Linux package settings. # # Check PKGBUILD_template docs for those settings and # what they mean. # def settings(): return { "version": "2.6.1", "release_number": "1", "arch_deps": ["cmake>=3.0.2", "zlib", "glibc", "sqlite", "wget", "python2-pmw" ], "debian_deps": ["zlib1g", "libc-bin", "libsqlite3-0", "wget", "lib32z1", "python-tk" ] } if __name__ == '__main__': print(settings())
Add TASK_QUEUED to default notifier events
from __future__ import absolute_import __all__ = ['Notifier', 'NotifierEvent'] class NotifierEvent(object): TASK_STARTED = 0 TASK_FINISHED = 1 TASK_QUEUED = 2 class Notifier(object): DEFAULT_EVENTS = [ NotifierEvent.TASK_QUEUED, NotifierEvent.TASK_STARTED, NotifierEvent.TASK_FINISHED, ] def get_default_options(self): return { # TODO(dcramer): we want to support events, but we need validators # before that can happen to avoid magical constants # 'events': {}, } def get_options(self): return {} def send(self, task, config, event): raise NotImplementedError def should_send(self, task, config, event): return event in config.get('events', self.DEFAULT_EVENTS)
from __future__ import absolute_import __all__ = ['Notifier', 'NotifierEvent'] class NotifierEvent(object): TASK_STARTED = 0 TASK_FINISHED = 1 TASK_QUEUED = 2 class Notifier(object): DEFAULT_EVENTS = [NotifierEvent.TASK_STARTED, NotifierEvent.TASK_FINISHED] def get_default_options(self): return { # TODO(dcramer): we want to support events, but we need validators # before that can happen to avoid magical constants # 'events': {}, } def get_options(self): return {} def send(self, task, config, event): raise NotImplementedError def should_send(self, task, config, event): return event in config.get('events', self.DEFAULT_EVENTS)
:bug: Make output path relative of file path
'use strict' const FS = require('fs') const Path = require('path') const Base = require('./base') class GenericPlugin extends Base { constructor() { super() this.registerTag(['Compiler-Include'], function(name, value) { return new Promise(function(resolve, reject) { FS.readFile(value, function (err, data) { if (err) reject(err) else resolve(data.toString()) }) }) }) this.registerTag(['Compiler-Output'], function(name, value, options) { options.Output = Path.resolve(options.internal.file.directory, value) }) this.registerTag(['Compiler-Compress', 'Compiler-Uglify'], function(name, value, options) { options.Uglify = value === 'true' }) this.registerTag(['Compiler-Babel', 'Compiler-Transpile'], function(name, value, options) { options.Babel = value === 'true' }) } compile(contents, options) { return this.executeTags(contents, options) } } module.exports = GenericPlugin
'use strict' const FS = require('fs') const Base = require('./base') class GenericPlugin extends Base { constructor() { super() this.registerTag(['Compiler-Include'], function(name, value) { return new Promise(function(resolve, reject) { FS.readFile(value, function (err, data) { if (err) reject(err) else resolve(data.toString()) }) }) }) this.registerTag(['Compiler-Output'], function(name, value, options) { options.Output = value }) this.registerTag(['Compiler-Compress', 'Compiler-Uglify'], function(name, value, options) { options.Uglify = value === 'true' }) this.registerTag(['Compiler-Babel', 'Compiler-Transpile'], function(name, value, options) { options.Babel = value === 'true' }) } compile(contents, options) { return this.executeTags(contents, options) } } module.exports = GenericPlugin
Handle error responses from API
const path = require('path') const { posterImagePath } = require('../../config') const request = require('../shared/request') const BASE_URL = 'https://us-central1-test-firebase-functions-82b96.cloudfunctions.net/getMovieMetadata' module.exports = { // External API. // Pass in the title of the movie. // Returns a promise with metadata on success. fetchMovieMetadata: function fetchMovieMetadata (movieFile) { return fetchMovieDataInternal(movieFile) } } // TODO: Television Series Handling // Look for 'Season' and a number in the parent directory (but not title) and use this to // prioritize type=series over movies. Could also look for patterns like: S4Ep01 in title? const dataValidator = (data) => { if (data.error) { throw new Error(data.message) } } function fetchMovieDataInternal (movieFile) { const url = encodeURI(`${BASE_URL}?file=${movieFile}`) return request.getJSON(url, dataValidator) .then((metadata) => { metadata.fileInfo = [{ location: movieFile, query: metadata.successQuery }] if (metadata.imgUrl) { const { ext } = path.parse(metadata.imgUrl) metadata.imgFile = path.join(posterImagePath, `${metadata.imdbID}${ext}`) } else { metadata.imgFile = '' } return metadata }) }
const path = require('path') const { posterImagePath } = require('../../config') const request = require('../shared/request') const BASE_URL = 'https://us-central1-test-firebase-functions-82b96.cloudfunctions.net/getMovieMetadata' module.exports = { // External API. // Pass in the title of the movie. // Returns a promise with metadata on success. fetchMovieMetadata: function fetchMovieMetadata (movieFile) { return fetchMovieDataInternal(movieFile) } } // TODO: Television Series Handling // Look for 'Season' and a number in the parent directory (but not title) and use this to // prioritize type=series over movies. Could also look for patterns like: S4Ep01 in title? function fetchMovieDataInternal (movieFile) { const url = encodeURI(`${BASE_URL}?file=${movieFile}`) return request.getJSON(url) .then((metadata) => { metadata.fileInfo = [{ location: movieFile, query: metadata.successQuery }] if (metadata.imgUrl) { const { ext } = path.parse(metadata.imgUrl) metadata.imgFile = path.join(posterImagePath, `${metadata.imdbID}${ext}`) } else { metadata.imgFile = '' } return metadata }) }
Fix function object has no attribute __func__ Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add in _reverse) self.assertTrue(SList.remove in _reverse)
from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add.__func__ in _reverse) self.assertTrue(SList.remove.__func__ in _reverse)
Add support for trwikivoyage to Pywikibot Bug: T271263 Change-Id: I96597f57522147d26e9b0a86f89c67ca8959c5a2
"""Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2020 # # Distributed under the terms of the MIT license. # # The new Wikivoyage family that is hosted at Wikimedia from pywikibot import family class Family(family.SubdomainFamily, family.WikimediaFamily): """Family class for Wikivoyage.""" name = 'wikivoyage' languages_by_size = [ 'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he', 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', 'tr', ] category_redirect_templates = { '_default': (), 'bn': ('বিষয়শ্রেণী পুনর্নির্দেশ',), 'zh': ('分类重定向',), } # Global bot allowed languages on # https://meta.wikimedia.org/wiki/BPI#Current_implementation # & https://meta.wikimedia.org/wiki/Special:WikiSets/2 cross_allowed = [ 'bn', 'el', 'en', 'es', 'fa', 'fi', 'hi', 'ps', 'ru', ]
"""Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2020 # # Distributed under the terms of the MIT license. # # The new Wikivoyage family that is hosted at Wikimedia from pywikibot import family class Family(family.SubdomainFamily, family.WikimediaFamily): """Family class for Wikivoyage.""" name = 'wikivoyage' languages_by_size = [ 'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he', 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', ] category_redirect_templates = { '_default': (), 'bn': ('বিষয়শ্রেণী পুনর্নির্দেশ',), 'zh': ('分类重定向',), } # Global bot allowed languages on # https://meta.wikimedia.org/wiki/BPI#Current_implementation # & https://meta.wikimedia.org/wiki/Special:WikiSets/2 cross_allowed = [ 'bn', 'el', 'en', 'es', 'fa', 'fi', 'hi', 'ps', 'ru', ]
Revert "commiting failing dummytest to test CI-setup" This reverts commit eaac3ef8430d0a0c02ebaed82e1e8d27889124a6.
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # Skarphed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Skarphed. # If not, see http://www.gnu.org/licenses/. ########################################################### from skd_test import CoreTestCase class TestPermissionFunctions(CoreTestCase): def setUp(self): CoreTestCase.setUp(self) def test_bla(self): self.assertEqual(1,1) def tearDown(self): CoreTestCase.tearDown(self)
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # Skarphed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Skarphed. # If not, see http://www.gnu.org/licenses/. ########################################################### from skd_test import CoreTestCase class TestPermissionFunctions(CoreTestCase): def setUp(self): CoreTestCase.setUp(self) def test_bla(self): self.assertEqual(0,1) def tearDown(self): CoreTestCase.tearDown(self)
requireLineFeedAtFileEnd: Test to ensure IIFE case still reports Ref #1568
var Checker = require('../../../lib/checker'); var assert = require('assert'); describe('rules/require-line-feed-at-file-end', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); checker.configure({ requireLineFeedAtFileEnd: true }); }); it('should report no line feed at file end', function() { assert(checker.checkString('var x;').getErrorCount() === 1); }); it('should report no line feed at file end if end with comment', function() { assert(checker.checkString('var x;\n//foo').getErrorCount() === 1); }); it('should not report existing line feed at file end', function() { assert(checker.checkString('var x;\n').isEmpty()); }); it('should not report existing line feed at file end with preceeding comment', function() { assert(checker.checkString('var x;\n//foo\n').isEmpty()); }); it('should report on an IIFE with no line feed at EOF', function() { assert.equal(checker.checkString('(function() {\nconsole.log(\'Hello World\');\n})();').getErrorCount(), 1); }); });
var Checker = require('../../../lib/checker'); var assert = require('assert'); describe('rules/require-line-feed-at-file-end', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); }); it('should report no line feed at file end', function() { checker.configure({ requireLineFeedAtFileEnd: true }); assert(checker.checkString('var x;').getErrorCount() === 1); }); it('should report no line feed at file end if end with comment', function() { checker.configure({ requireLineFeedAtFileEnd: true }); assert(checker.checkString('var x;\n//foo').getErrorCount() === 1); }); it('should not report existing line feed at file end', function() { checker.configure({ requireLineFeedAtFileEnd: true }); assert(checker.checkString('var x;\n').isEmpty()); }); it('should not report existing line feed at file end with preceeding comment', function() { checker.configure({ requireLineFeedAtFileEnd: true }); assert(checker.checkString('var x;\n//foo\n').isEmpty()); }); });
Fix null case for event details
from database.dict_converters.converter_base import ConverterBase class EventDetailsConverter(ConverterBase): SUBVERSIONS = { # Increment every time a change to the dict is made 3: 0, } @classmethod def convert(cls, event_details, dict_version): CONVERTERS = { 3: cls.eventDetailsConverter_v3, } return CONVERTERS[dict_version](event_details) @classmethod def eventDetailsConverter_v3(cls, event_details): event_details_dict = { 'alliances': event_details.alliance_selections if event_details else None, 'district_points': event_details.district_points if event_details else None, 'rankings': event_details.renderable_rankings if event_details else None, 'stats': event_details.matchstats if event_details else None, } return event_details_dict
from database.dict_converters.converter_base import ConverterBase class EventDetailsConverter(ConverterBase): SUBVERSIONS = { # Increment every time a change to the dict is made 3: 0, } @classmethod def convert(cls, event_details, dict_version): CONVERTERS = { 3: cls.eventDetailsConverter_v3, } return CONVERTERS[dict_version](event_details) @classmethod def eventDetailsConverter_v3(cls, event_details): event_details_dict = { 'alliances': event_details.alliance_selections, 'district_points': event_details.district_points, 'rankings': event_details.renderable_rankings, 'stats': event_details.matchstats, } return event_details_dict
Fix thinko in file mode test.
package termite import ( "io/ioutil" "os" "syscall" "testing" ) func TestFileAttrReadFrom(t *testing.T) { dir, _ := ioutil.TempDir("", "termite") ioutil.WriteFile(dir+"/file.txt", []byte{42}, 0644) attr := FileAttr{FileInfo: &os.FileInfo{Mode: syscall.S_IFDIR}} attr.ReadFromFs(dir) if attr.NameModeMap == nil { t.Fatalf("should have NameModeMap: %v", attr) } m := attr.NameModeMap["file.txt"] if !m.IsRegular() { t.Fatalf("unexpected mode: %o, want IsRegular()", m) } } func TestFileMode(t *testing.T) { sock := FileMode(syscall.S_IFSOCK) if sock.IsDirectory() { t.Error("Socket should not be directory") } }
package termite import ( "io/ioutil" "os" "syscall" "testing" ) func TestFileAttrReadFrom(t *testing.T) { dir, _ := ioutil.TempDir("", "termite") ioutil.WriteFile(dir+"/file.txt", []byte{42}, 0644) attr := FileAttr{FileInfo: &os.FileInfo{Mode: syscall.S_IFDIR}} attr.ReadFromFs(dir) if attr.NameModeMap == nil { t.Fatalf("should have NameModeMap: %v", attr) } if attr.NameModeMap["file.txt"].IsRegular() { t.Fatalf("unexpected mode: %v", attr.NameModeMap["file.txt"]) } } func TestFileMode(t *testing.T) { sock := FileMode(syscall.S_IFSOCK) if sock.IsDirectory() { t.Error("Socket should not be directory") } }
Exclude optimized folder from optimization :D
({ appDir: "../../", dir : "../../optimized", mainConfigFile : "config.js", baseUrl: "static", generateSourceMaps: true, removeCombined : true, keepBuildDir : true, optimize: 'uglify2', skipDirOptimize : true, fileExclusionRegExp: /^optimized/, preserveLicenseComments : false, modules: [ { name: "js/main", } ], paths: { //use the minified version instead of minifying it by ourself //since otherwise we would still include some debug code. //By using the minified version, we make sure, that we get the //development build. "react": "bower_components/react/react.min" } })
({ appDir: "../../", dir : "../../optimized", mainConfigFile : "config.js", baseUrl: "static", generateSourceMaps: true, removeCombined : true, keepBuildDir : true, optimize: 'uglify2', skipDirOptimize : true, preserveLicenseComments : false, modules: [ { name: "js/main", } ], paths: { //use the minified version instead of minifying it by ourself //since otherwise we would still include some debug code. //By using the minified version, we make sure, that we get the //development build. "react": "bower_components/react/react.min" } })
Solve issue of blank/undefined answers.
module.exports = function(question, callback) { var apiai = require('apiai'); var app = apiai("76ccb7c7acea4a6884834f6687475222", "8b3e68f16ac6430cb8c40d49c315aa7a"); var request = app.textRequest(question); request.on('response', function(response) { var kantSucks = require('./deontologyYo')(response); if(kantSucks == 0) if(response.result.metadata.speech) callback(response.result.metadata.speech) else callback("Unfortunately, I'm not smart enough to answer that question yet.") else if(kantSucks == 1) if(response.result.metadata.speech && response.result.metadata.speech != "undefined") callback("I'll check with that after I pass through my utility ethic function. Heres what I would say otherwise: " + response.result.metadata.speech); else callback(kantSucks) }); request.on('error', function(error) { callback(error); }); request.end() };
module.exports = function(question, callback) { var apiai = require('apiai'); var app = apiai("76ccb7c7acea4a6884834f6687475222", "8b3e68f16ac6430cb8c40d49c315aa7a"); var request = app.textRequest(question); request.on('response', function(response) { var kantSucks = require('./deontologyYo')(response); if(kantSucks == 0) if(response.result.metadata.speech) callback(response.result.metadata.speech) else callback("Unfortunately, I'm not smart enough to answer that question yet.") else if(kantSucks == 1) if(response.result.metadata.speech) callback("I'll check with that after I pass through my utility ethic function. Heres what I would say otherwise: " + response.result.metadata.speech); else callback(kantSucks) }); request.on('error', function(error) { callback(error); }); request.end() };
Revert "Allow passing config as lazy-evaluated function" This reverts commit 1819cf67d3f24ebe055b4c54b4e037a6621b3734.
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { const config = mergeConfig(defaultConfig, options) return postcss([ generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) module.exports = plugin
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { if (_.isFunction(options)) { options = options() } const config = mergeConfig(defaultConfig, options) return postcss([ generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) module.exports = plugin
Add ScrollableDropdown import to ipywidgets
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout