text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix Karma for new naming
'use strict'; module.exports = function(config) { config.set({ basePath: '.', frameworks: ['mocha', 'chai'], autoWatch: true, singleRun: false, browsers: ['Chrome'], autoWatchBatchDelay: 300, webpack: configureWebpack(), files: [ './node_modules/angular/angular.js', './node_modules/angular-mocks/angular-mocks.js', './src/mdc.js', './src/**/*.spec.js', ], preprocessors: { './src/mdc.js': ['webpack'], './src/**/*.spec.js': ['babel'], }, reporters: ['mocha'], mochaReporter: { output: 'autowatch', }, browserConsoleLogOptions: { level: 'debug', format: '%b %T: %m', terminal: false, }, }); function configureWebpack() { const webpackConfig = require('./webpack.config'); webpackConfig.entry = undefined; return webpackConfig; } };
'use strict'; module.exports = function(config) { config.set({ basePath: '.', frameworks: ['mocha', 'chai'], autoWatch: true, singleRun: false, browsers: ['Chrome'], autoWatchBatchDelay: 300, webpack: configureWebpack(), files: [ './node_modules/angular/angular.js', './node_modules/angular-mocks/angular-mocks.js', './src/all.js', './src/**/*.spec.js', ], preprocessors: { './src/all.js': ['webpack'], './src/**/*.spec.js': ['babel'], }, reporters: ['mocha'], mochaReporter: { output: 'autowatch', }, browserConsoleLogOptions: { level: 'debug', format: '%b %T: %m', terminal: false, }, }); function configureWebpack() { const webpackConfig = require('./webpack.config'); webpackConfig.entry = undefined; return webpackConfig; } };
Add functionality for pathway owner to choose 3 projects then be redirected to pathway
'use strict' angular.module('pathwayApp') .controller('ProjectController', function ($scope, $http, $stateParams, $state) { $http({method: 'GET', url: '/api/pathways/' + $stateParams.pathway_id + '/projects/' + $stateParams.id }).success(function(data, status){ $scope.project = data }) $scope.projects = $http({method: 'GET', url: '/api/projects' }).success(function(data, status){ $scope.allProjects = data }) $scope.create = function() { $http({method: 'POST', url: '/api/projects', data: {project: $scope.project } }).success(function(data, status){ console.log("hello from create()") $state.go('home') }).error(function(data){ console.log(data) }) } var projects = 0 $scope.addProject = function(project, donated_weight) { $http({method: 'POST', url: '/api/pathways/' + $stateParams.id + '/projects', data: {projects: project, weight: donated_weight } }).success(function(data, status){ projects += 1 if (projects == 3) {$state.go('showPathway', {'id': data.pathway_id })} }).error(function(data){ console.log(data) }) } });
'use strict' angular.module('pathwayApp') .controller('ProjectController', function ($scope, $http, $stateParams, $state) { $http({method: 'GET', url: '/api/pathways/' + $stateParams.pathway_id + '/projects/' + $stateParams.id }).success(function(data, status){ $scope.project = data }) $scope.projects = $http({method: 'GET', url: '/api/projects' }).success(function(data, status){ $scope.allProjects = data }) $scope.create = function() { $http({method: 'POST', url: '/api/projects', data: {project: $scope.project } }).success(function(data, status){ console.log("hello from create()") $state.go('home') }).error(function(data){ console.log(data) }) } $scope.addProject = function(project, donated_weight) { $http({method: 'POST', url: '/api/pathways/' + $stateParams.id + '/projects', data: {projects: project, weight: donated_weight } }).success(function(data, status){ console.log("hello from create()") $state.go('home') }).error(function(data){ console.log(data) }) } });
Add missing fire command for non-compound generators.
<?php namespace R\Hive\Commands; use Illuminate\Console\GeneratorCommand; class HiveGeneratorCommand extends GeneratorCommand { protected $compound = null; protected function getPath($name) { $name = str_replace($this->laravel->getNamespace(), '', $name); // Add the class type to the file name. return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php'; } protected function getStub() { return; } public function fire() { if ($this->compound !== null) { if (parent::fire() !== false) { if ($this->option($this->compound)) { $name = $this->argument('name'); $this->call("hive:{$this->compound}", ['name' => $name]); } } } else { parent::fire(); } } }
<?php namespace R\Hive\Commands; use Illuminate\Console\GeneratorCommand; class HiveGeneratorCommand extends GeneratorCommand { protected $compound = null; protected function getPath($name) { $name = str_replace($this->laravel->getNamespace(), '', $name); // Add the class type to the file name. return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php'; } protected function getStub() { return; } public function fire() { if ($this->compound !== null) { if (parent::fire() !== false) { if ($this->option($this->compound)) { $name = $this->argument('name'); $this->call("hive:{$this->compound}", ['name' => $name]); } } } } }
Disable dragging sections for now.
import Ember from 'ember'; import layout from '../templates/components/karbon-sortable-item'; export default Ember.Component.extend({ tagName: 'li', classNames: ['spacer'], classNameBindings: ['handleClass', 'isSection:section', 'isNested:nested'], attributeBindings: ['draggable', 'pkid:data-pkid'], handleClass: 'droppable', // temporary draggable: Ember.computed.not('data.isSection'), isSection: Ember.computed.alias('data.isSection'), isNested: Ember.computed.alias('data.isChild'), pkid: Ember.computed.alias('data.id'), layout, didInsertElement() { // We don't need to pass any data (yet), but FF won't drag unless this is set this.$().attr('ondragstart', "event.dataTransfer.setData('text/plain', 'text')"); }, /* click() { const data = this.get('data'); if (data.get('isSection')) { this.get('toggleSection')(data); return false; } } */ });
import Ember from 'ember'; import layout from '../templates/components/karbon-sortable-item'; export default Ember.Component.extend({ tagName: 'li', classNames: ['spacer'], classNameBindings: ['handleClass', 'isSection:section', 'isNested:nested'], attributeBindings: ['draggable', 'pkid:data-pkid'], handleClass: 'droppable', draggable: 'true', isSection: Ember.computed.alias('data.isSection'), isNested: Ember.computed.alias('data.isChild'), pkid: Ember.computed.alias('data.id'), layout, didInsertElement() { // We don't need to pass any data (yet), but FF won't drag unless this is set this.$().attr('ondragstart', "event.dataTransfer.setData('text/plain', 'text')"); }, click() { const data = this.get('data'); if (data.get('isSection')) { this.get('toggleSection')(data); return false; } } });
Make text a list in the index.
import six from datetime import datetime, date from collections import Mapping, Iterable from jsonmapping.transforms import transliterate IGNORE_FIELDS = ['$schema', '$sources', '$latin', '$text', '$attrcount', '$linkcount', 'id'] def latinize(text): """ Transliterate text to latin. """ if text is None or not len(text): return text return transliterate(text).lower() def extract_text(data): """ Get all the instances of text from a given object, recursively. """ if isinstance(data, Mapping): values = [] for k, v in data.items(): if k in IGNORE_FIELDS: continue values.append(v) data = values if isinstance(data, (date, datetime)): data = data.isoformat() elif isinstance(data, (int, float)): data = six.text_type(data) if isinstance(data, six.string_types): return [data] if isinstance(data, Iterable): values = [] for d in data: values.extend(extract_text(d)) return values
import six from datetime import datetime, date from collections import Mapping, Iterable from jsonmapping.transforms import transliterate IGNORE_FIELDS = ['$schema', '$sources', '$latin', '$text', '$attrcount', '$linkcount', 'id'] def latinize(text): """ Transliterate text to latin. """ if text is None or not len(text): return text return transliterate(text).lower() def extract_text(data, sep=' : '): """ Get all the instances of text from a given object, recursively. """ if isinstance(data, Mapping): values = [] for k, v in data.items(): if k in IGNORE_FIELDS: continue values.append(v) data = values if isinstance(data, (date, datetime)): data = data.isoformat() elif isinstance(data, (int, float)): data = six.text_type(data) if isinstance(data, six.string_types): return data if isinstance(data, Iterable): text = [extract_text(d, sep=sep) for d in data] return sep.join([t for t in text if t is not None])
Remove Kalite until Arabic language is available
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'mediacenter', }, { 'id': 'library', } ]
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = []
stream: Add default config and config schema
from __future__ import unicode_literals import mopidy from mopidy import ext from mopidy.utils import config, formatting default_config = """ [ext.stream] # If the stream extension should be enabled or not enabled = true # Whitelist of URI schemas to support streaming from protocols = http https mms rtmp rtmps rtsp """ __doc__ = """A backend for playing music for streaming music. This backend will handle streaming of URIs in :attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are installed. **Issues:** https://github.com/mopidy/mopidy/issues?labels=Stream+backend **Dependencies:** - None **Default config:** .. code-block:: ini %(config)s """ % {'config': formatting.indent(default_config)} class Extension(ext.Extension): name = 'Mopidy-Stream' version = mopidy.__version__ def get_default_config(self): return default_config def get_config_schema(self): schema = config.ExtensionConfigSchema() schema['protocols'] = config.List() return schema def validate_environment(self): pass def get_backend_classes(self): from .actor import StreamBackend return [StreamBackend]
from __future__ import unicode_literals import mopidy from mopidy import ext __doc__ = """A backend for playing music for streaming music. This backend will handle streaming of URIs in :attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are installed. **Issues:** https://github.com/mopidy/mopidy/issues?labels=Stream+backend **Dependencies:** - None **Settings:** - :attr:`mopidy.settings.STREAM_PROTOCOLS` """ class Extension(ext.Extension): name = 'Mopidy-Stream' version = mopidy.__version__ def get_default_config(self): return '[ext.stream]' def validate_config(self, config): pass def validate_environment(self): pass def get_backend_classes(self): from .actor import StreamBackend return [StreamBackend]
Fix defaultConfig() method (add return)
import fs from 'fs' import path from 'path' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import substituteResetAtRule from './lib/substituteResetAtRule' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteFocusableAtRules from './lib/substituteFocusableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (config) => { if (_.isUndefined(config)) { config = require('../defaultConfig') } if (_.isString(config)) { config = require(path.resolve(config)) } return postcss([ substituteResetAtRule(config), evaluateTailwindFunctions(config), generateUtilities(config), substituteHoverableAtRules(config), substituteFocusableAtRules(config), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) plugin.defaultConfig = function () { return _.cloneDeep(require('../defaultConfig')) } module.exports = plugin
import fs from 'fs' import path from 'path' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import substituteResetAtRule from './lib/substituteResetAtRule' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteFocusableAtRules from './lib/substituteFocusableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (config) => { if (_.isUndefined(config)) { config = require('../defaultConfig') } if (_.isString(config)) { config = require(path.resolve(config)) } return postcss([ substituteResetAtRule(config), evaluateTailwindFunctions(config), generateUtilities(config), substituteHoverableAtRules(config), substituteFocusableAtRules(config), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) plugin.defaultConfig = function () { _.cloneDeep(require('../defaultConfig')) } module.exports = plugin
Update repo entrypoint and remote_update stub.
""" Problem repository management for the shell manager. """ import spur, gzip from shutil import copy2 from os.path import join def update_repo(args): """ Main entrypoint for repo update operations. """ if args.repo_type == "local": local_update(args.repository, args.package_paths) else: remote_update(args.repository, args.package_paths) def remote_update(repo_ui, deb_paths=[]): """ Pushes packages to a remote deb repository. Args: repo_uri: location of the repository. deb_paths: list of problem deb paths to copy. """ pass def local_update(repo_path, deb_paths=[]): """ Updates a local deb repository by copying debs and running scanpackages. Args: repo_path: the path to the local repository. dep_paths: list of problem deb paths to copy. """ [copy2(deb_path, repo_path) for deb_path in deb_paths] shell = spur.LocalShell() result = shell.run(["dpkg-scanpackages", ".", "/dev/null"], cwd=repo_path) packages_path = join(repo_path, "Packages.gz") with gzip.open(packages_path, "wb") as packages: packages.write(result.output) print("Updated problem repository.")
""" Problem repository management for the shell manager. """ import spur, gzip from shutil import copy2 from os.path import join def local_update(repo_path, deb_paths=[]): """ Updates a local deb repository by copying debs and running scanpackages. Args: repo_path: the path to the local repository. dep_paths: list of problem deb paths to copy. """ [copy2(deb_path, repo_path) for deb_path in deb_paths] shell = spur.LocalShell() result = shell.run(["dpkg-scanpackages", ".", "/dev/null"], cwd=repo_path) packages_path = join(repo_path, "Packages.gz") with gzip.open(packages_path, "wb") as packages: packages.write(result.output) print("Updated problem repository.")
Use of circle() instead of oval()
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) circle(self.x, self.y, self.radius) # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
Set mining characteristics for meme ore.
package net.darkmorford.btweagles.block; import net.darkmorford.btweagles.BetterThanWeagles; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockMemeOre extends Block { public BlockMemeOre() { super(Material.ROCK); setRegistryName(BetterThanWeagles.MODID, "meme_ore"); setUnlocalizedName("meme_ore"); setCreativeTab(BetterThanWeagles.tabBTWeagles); setHardness(1.5F); setResistance(1000.0F); setHarvestLevel("pickaxe", 2); } @SideOnly(Side.CLIENT) public void initModel() { ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory")); } }
package net.darkmorford.btweagles.block; import net.darkmorford.btweagles.BetterThanWeagles; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockMemeOre extends Block { public BlockMemeOre() { super(Material.ROCK); setRegistryName(BetterThanWeagles.MODID, "meme_ore"); setUnlocalizedName("meme_ore"); setCreativeTab(BetterThanWeagles.tabBTWeagles); } @SideOnly(Side.CLIENT) public void initModel() { ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory")); } }
Add 'map' to asset extensions Otherwise react will attempt to route it
'use strict'; const config = { browserPort: 3000, UIPort: 3001, scripts: { src: './app/js/**/*.js', dest: './build/js/', test: './tests/**/*.js', gulp: './gulp/**/*.js' }, images: { src: './app/images/**/*.{jpeg,jpg,png,gif}', dest: './build/images/' }, styles: { src: './app/styles/**/*.scss', dest: './build/css/' }, sourceDir: './app/', buildDir: './build/', testFiles: './tests/**/*.{js,jsx}', assetExtensions: [ 'js', 'css', 'map', 'png', 'jpe?g', 'gif', 'svg', 'eot', 'otf', 'ttc', 'ttf', 'woff2?' ] }; export default config;
'use strict'; const config = { browserPort: 3000, UIPort: 3001, scripts: { src: './app/js/**/*.js', dest: './build/js/', test: './tests/**/*.js', gulp: './gulp/**/*.js' }, images: { src: './app/images/**/*.{jpeg,jpg,png,gif}', dest: './build/images/' }, styles: { src: './app/styles/**/*.scss', dest: './build/css/' }, sourceDir: './app/', buildDir: './build/', testFiles: './tests/**/*.{js,jsx}', assetExtensions: [ 'js', 'css', 'png', 'jpe?g', 'gif', 'svg', 'eot', 'otf', 'ttc', 'ttf', 'woff2?' ] }; export default config;
Check if installs or starcount is undefined
function calcWidth(name) { return 250 + name.length * 6.305555555555555; } WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', version, pubDate, starCount, installYear; var payload = res.data[0]; if (! res.data.length) { name = payload.name; version = payload.latestVersion.version; pubDate = moment(payload.latestVersion.published.$date).format('MMM Do YYYY'); starCount = payload.starCount || 0; installYear = payload['installs-per-year'] || 0; } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = calcWidth(name); var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
function calcWidth(name) { return 250 + name.length * 6.305555555555555; } WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', version, pubDate, startCount, installYear; var payload = res.data[0]; if (res.data.length !== 0) { name = payload.name; version = payload.latestVersion.version; pubDate = moment(payload.latestVersion.published.$date) .format('MMM Do YYYY'); starCount = payload.starCount.toLocaleString(); installYear = payload['installs-per-year'].toLocaleString(); } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = calcWidth(name); var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
Fix pep8 missing newline at end of file
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015-2017: # Matthieu Estrada, ttamalfor@gmail.com # # This file is part of (AlignakApp). # # (AlignakApp) 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. # # (AlignakApp) 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 (AlignakApp). If not, see <http://www.gnu.org/licenses/>. """ The Locales package contains classes to manage translation. """
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015-2017: # Matthieu Estrada, ttamalfor@gmail.com # # This file is part of (AlignakApp). # # (AlignakApp) 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. # # (AlignakApp) 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 (AlignakApp). If not, see <http://www.gnu.org/licenses/>. """ The Locales package contains classes to manage translation. """
Set scim_externalid to nullable, default null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddExternalidToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('scim_externalid')->nullable()->default(null); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('scim_externalid'); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddExternalidToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('scim_externalid'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('scim_externalid'); }); } }
Add missing return type declaration to Push interface
<?php namespace Rhymix\Framework\Drivers; /** * The Push driver interface. */ interface PushInterface { /** * Create a new instance of the current Push driver, using the given settings. * * @param array $config * @return void */ public static function getInstance(array $config): object; /** * Get the human-readable name of this Push driver. * * @return string */ public static function getName(): string; /** * Get the list of configuration fields required by this Push driver. * * @return array */ public static function getRequiredConfig(): array; /** * Get the list of configuration fields optionally used by this Push driver. * * @return array */ public static function getOptionalConfig(): array; /** * Check if the current SMS driver is supported on this server. * * This method returns true on success and false on failure. * * @return bool */ public static function isSupported(): bool; /** * Send a message. * * This method returns true on success and false on failure. * * @param object $message * @param array $tokens * @return \stdClass */ public function send(\Rhymix\Framework\Push $message, array $tokens): \stdClass; }
<?php namespace Rhymix\Framework\Drivers; /** * The Push driver interface. */ interface PushInterface { /** * Create a new instance of the current Push driver, using the given settings. * * @param array $config * @return void */ public static function getInstance(array $config): object; /** * Get the human-readable name of this Push driver. * * @return string */ public static function getName(): string; /** * Get the list of configuration fields required by this Push driver. * * @return array */ public static function getRequiredConfig(): array; /** * Get the list of configuration fields optionally used by this Push driver. * * @return array */ public static function getOptionalConfig(): array; /** * Check if the current SMS driver is supported on this server. * * This method returns true on success and false on failure. * * @return bool */ public static function isSupported(): bool; /** * Send a message. * * This method returns true on success and false on failure. * * @param object $message * @param array $tokens * @return object */ public function send(\Rhymix\Framework\Push $message, array $tokens); }
FIX bug in event creation
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, api class EventCompassion(models.Model): _inherit = "crm.event.compassion" @api.model def create(self, vals): event = super().create(vals) if event.campaign_id: event.analytic_id.campaign_id = event.campaign_id event.origin_id.campaign_id = event.campaign_id return event @api.multi def write(self, vals): res = super().write(vals) for new_event in self: if new_event.campaign_id: if new_event.analytic_id: new_event.analytic_id.campaign_id = new_event.campaign_id if new_event.origin_id: new_event.origin_id.campaign_id = new_event.campaign_id return res
############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, api class EventCompassion(models.Model): _inherit = "crm.event.compassion" @api.model def create(self, vals): event = super().create(vals) if event.campaign_id: event.analytic_id.campaign_id = event.campaign_id event.origin_id.campaign_id = event.campaign_id return event @api.multi def write(self, vals): res = super().write(vals) for new_event in self: if new_event.campaign_id: new_event.analytic_id.campaign_id = new_event.campaign_id new_event.origin_id.campaign_id = new_event.campaign_id return res
Update supported Python and Django versions
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-contentfiles', version='0.2.4', description='Blanc Content Files', long_description=readme, url='https://github.com/developersociety/blanc-contentfiles', maintainer='The Developer Society', maintainer_email='studio@dev.ngo', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.11', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], license='BSD', )
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-contentfiles', version='0.2.4', description='Blanc Content Files', long_description=readme, url='https://github.com/developersociety/blanc-contentfiles', maintainer='The Developer Society', maintainer_email='studio@dev.ngo', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
Add html_url into default keys
import { GitHub } from './GitHub'; import * as _ from 'lodash'; const fs = require('fs'); let hub = null; let jsonFile = null; let keys = [ 'name', 'description', 'updated_at', 'html_url', 'language', 'stargazers_count', 'forks_count', 'contributor_count' ]; if (process.argv.length > 2) { let user = process.argv[2]; let token = process.argv[3]; let userAgent = process.argv[4]; jsonFile = process.argv[5]; hub = new GitHub(user, token, userAgent, keys); } hub.parseUserRepositories() .then((userJSON) => { hub.parseOrganizationRepositories() .then((orgJSON) => { let minimal = {}; minimal['repositories'] = userJSON; _.each(orgJSON, (value, key) => { minimal[key] = value; }); console.log('Updating github.json'); fs.writeFile(jsonFile, JSON.stringify(minimal, null, 2), (err) => { if (err) { console.log(err); } }); }).catch((err) => console.log(err)); }).catch((err) => console.log(err));
import { GitHub } from './GitHub'; import * as _ from 'lodash'; const fs = require('fs'); let hub = null; let jsonFile = null; let keys = [ 'name', 'description', 'updated_at', 'language', 'stargazers_count', 'forks_count', 'contributor_count' ]; if (process.argv.length > 2) { let user = process.argv[2]; let token = process.argv[3]; let userAgent = process.argv[4]; jsonFile = process.argv[5]; hub = new GitHub(user, token, userAgent, keys); } hub.parseUserRepositories() .then((userJSON) => { hub.parseOrganizationRepositories() .then((orgJSON) => { let minimal = {}; minimal['repositories'] = userJSON; _.each(orgJSON, (value, key) => { minimal[key] = value; }); console.log('Updating github.json'); fs.writeFile(jsonFile, JSON.stringify(minimal, null, 2), (err) => { if (err) { console.log(err); } }); }).catch((err) => console.log(err)); }).catch((err) => console.log(err));
Use full source map in production
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const Dotenv = require('dotenv-webpack'); module.exports = { entry: { 'facebook-messenger/handler': './src/facebook-messenger/handler.js', }, target: 'node', externals: [ 'aws-sdk' ], module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: ['es2015'] } }, { test: /\.json/, loader: 'json-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { from: '.env' } ]), new Dotenv({ safe: true }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true, warnings: false, drop_debugger: true } }) ], output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js' }, devtool: "source-map" };
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const Dotenv = require('dotenv-webpack'); module.exports = { entry: { 'facebook-messenger/handler': './src/facebook-messenger/handler.js', }, target: 'node', externals: [ 'aws-sdk' ], module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: ['es2015'] } }, { test: /\.json/, loader: 'json-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { from: '.env' } ]), new Dotenv({ safe: true }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true, warnings: false, drop_debugger: true } }) ], output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js' }, devtool: "cheap-module-source-map" };
Save answer but error occured
var express = require('express'); var router = express.Router(); var Answer = require(config.root.MODEL_ROOT).answer; var scoreMod = require(config.root.MODULE_ROOT).score; function saveAnswer(ua, answers) { var answer = new Answer(); answer.ua = ua; answer.gender = answers.a1; answer.age = answers.a2; answer.married = answers.a3; answer.atHome = answers.a4; answer.needs = answers.a5; answer.interiorRatio = answers.a6; answer.color = answers.a7; answer.culture = answers.a8; answer.save(function(err) { logger.info("Answer is saved!"); if (err) { logger.error("DB error: saving Answer!"); } }); } router.post("/", function(req, res, next) { // Calculating score var score = new scoreMod(); // calculate score.calculate(req.body); var myscore = score.getScore(); var result = score.getResult(); if (!myscore) { res.status(400).send("Wrong answer type"); } else { // DB: save answer saveAnswer(req.headers['user-agent'], req.body); res.send({ url: "/result/" + result.first }); } }); module.exports = router;
var express = require('express'); var router = express.Router(); var Answer = require(config.root.MODEL_ROOT).answer; var scoreMod = require(config.root.MODULE_ROOT).score; function saveAnswer(ua, answers) { var answer = new Answer(); answer.ua = ua; answer.gender = answers.a1; answer.age = answers.a2; answer.married = answers.a3; answer.atHome = answers.a4; answer.needs = answers.a5; answer.interiorRatio = answers.a6; answer.color = answers.a7; answer.culture = answers.a8; answer.save(function(err) { logger.info("Answer is saved!"); if (err) { logger.error("DB error: saving Answer!"); } }); } router.post("/", function(req, res, next) { // Calculating score var score = new scoreMod(); // calculate score.calculate(req.body); var myscore = score.getScore(); var result = score.getResult(); if (!myscore) { res.status(400).send("Wrong answer type"); } else { // TODO: result first와 second 값으로 결과 페이지 구성하기! // DB: save answer // TODO: uncomment to save answer to DB //saveAnswer(req.headers['user-agent'], req.body); res.send({ url: "/result/" + result.first }); } }); module.exports = router;
Add a few more cgi paths
'use strict'; module.exports = [ 'admin.cgi', 'administrator.cgi', 'backup.cgi', 'cgi-bin/bash', 'cgi-bin/common/attr', // open proxy test 'cgi-bin/printenv', 'concept.cgi', 'contact.cgi', 'count.cgi', 'counter.cgi', 'defaultwebpage.cgi', 'env.cgi', 'fire.cgi', 'firewall.cgi', 'formmail.cgi', 'getheaders2.php', 'getheaders9.php', 'hello.cgi', 'helpdesk.cgi', 'index.cgi', 'index2.cgi', 'info.cgi', 'kontakt.cgi', 'login.cgi', 'main.cgi', 'meme.cgi', 'muieblackcat', // Muieblackcat http://eromang.zataz.com/2011/08/14/suc027-muieblackcat-setup-php-web-scanner-robot/ 'query.cgi', 'reboot.cgi', 'report.cgi', 'scripts/setup.php', // phpMyAdmin setup path 'supply.cgi', 'test.sh', 'testproxy.php', // open proxy test 'tmunblock.cgi', 'user/soapcaller.bs', 'webmap.cgi', 'whois.cgi', 'zmap.io' // https://zmap.io/ ];
'use strict'; module.exports = [ 'admin.cgi', 'administrator.cgi', 'backup.cgi', 'cgi-bin/common/attr', // open proxy test 'cgi-bin/printenv', 'concept.cgi', 'count.cgi', 'counter.cgi', 'firewall.cgi', 'formmail.cgi', 'getheaders2.php', 'getheaders9.php', 'helpdesk.cgi', 'index.cgi', 'index2.cgi', 'info.cgi', 'kontakt.cgi', 'main.cgi', 'muieblackcat', // Muieblackcat http://eromang.zataz.com/2011/08/14/suc027-muieblackcat-setup-php-web-scanner-robot/ 'zmap.io', // https://zmap.io/ 'query.cgi', 'reboot.cgi', 'report.cgi', 'scripts/setup.php', // phpMyAdmin setup path 'supply.cgi', 'test.sh', 'testproxy.php', // open proxy test 'tmunblock.cgi', 'webmap.cgi', 'whois.cgi' ];
Add 'Framework :: Django :: 1.9' to classifiers https://travis-ci.org/RyanBalfanz/django-smsish/builds/105968596
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-smsish', version='1.1', packages=[ 'smsish', 'smsish.sms', ], include_package_data=True, license='MIT', # example license description='A simple Django app to send SMS messages using an API similar to that of django.core.mail.', long_description=README, url='https://github.com/RyanBalfanz/django-smsish', author='Ryan Balfanz', author_email='ryan@ryanbalfanz.net', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Topic :: Communications', 'Topic :: Communications :: Telephony', ], )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-smsish', version='1.1', packages=[ 'smsish', 'smsish.sms', ], include_package_data=True, license='MIT', # example license description='A simple Django app to send SMS messages using an API similar to that of django.core.mail.', long_description=README, url='https://github.com/RyanBalfanz/django-smsish', author='Ryan Balfanz', author_email='ryan@ryanbalfanz.net', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Topic :: Communications', 'Topic :: Communications :: Telephony', ], )
Add test case for wrapping a stream passed as a param git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2601 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
import java.io.*; public class OpenStream { public static void main(String[] argv) throws Exception { FileInputStream in = null; try { in = new FileInputStream(argv[0]); } finally { // Not guaranteed to be closed here! if (Boolean.getBoolean("inscrutable")) in.close(); } FileInputStream in2 = null; try { in2 = new FileInputStream(argv[1]); } finally { // This one will be closed if (in2 != null) in2.close(); } // oops! exiting the method without closing the stream } public void byteArrayStreamDoNotReport() { ByteArrayOutputStream b = new ByteArrayOutputStream(); PrintStream out = new PrintStream(b); out.println("Hello, world!"); } public void systemInDoNotReport() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(reader.readLine()); } public void socketDoNotReport(java.net.Socket socket) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(reader.readLine()); } public void paramStreamDoNotReport(java.io.OutputStream os) throws IOException { PrintStream ps = new PrintStream(os); ps.println("Hello"); } } // vim:ts=4
import java.io.*; public class OpenStream { public static void main(String[] argv) throws Exception { FileInputStream in = null; try { in = new FileInputStream(argv[0]); } finally { // Not guaranteed to be closed here! if (Boolean.getBoolean("inscrutable")) in.close(); } FileInputStream in2 = null; try { in2 = new FileInputStream(argv[1]); } finally { // This one will be closed if (in2 != null) in2.close(); } // oops! exiting the method without closing the stream } public void byteArrayStreamDoNotReport() { ByteArrayOutputStream b = new ByteArrayOutputStream(); PrintStream out = new PrintStream(b); out.println("Hello, world!"); } public void systemInDoNotReport() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(reader.readLine()); } public void socketDoNotReport(java.net.Socket socket) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(reader.readLine()); } }
Add userAgent information when tracking visits
function trackDetailsAction(action) { Parse.Analytics.track('detailsPageAction', { action: action }); } function trackHomepageAction(searchTerm, category) { var dimensions = {}; if (searchTerm) { dimensions.action = 'search'; } else { dimensions.action = 'category'; dimensions.category = category; } Parse.Analytics.track('homePageAction', dimensions); } function trackRoute(route) { Parse.Analytics.track('visit', { page: route, platform: window.navigator.platform, userAgent: window.navigator.userAgent }); } function trackQuery(params) { _.keys(params).forEach(function(k) { if (_.isEmpty(params[k])) { delete params[k]; } }); if (!_.isEmpty(params)) { Parse.Analytics.track('query', params); } } module.exports = { trackDetailsAction: trackDetailsAction, trackHomepageAction: trackHomepageAction, trackRoute: trackRoute, trackQuery: trackQuery };
function trackDetailsAction(action) { Parse.Analytics.track('detailsPageAction', { action: action }); } function trackHomepageAction(searchTerm, category) { var dimensions = {}; if (searchTerm) { dimensions.action = 'search'; } else { dimensions.action = 'category'; dimensions.category = category; } Parse.Analytics.track('homePageAction', dimensions); } function trackRoute(route) { Parse.Analytics.track('visit', { page: route }); } function trackQuery(params) { _.keys(params).forEach(function(k) { if (_.isEmpty(params[k])) { delete params[k]; } }); if (!_.isEmpty(params)) { Parse.Analytics.track('query', params); } } module.exports = { trackDetailsAction: trackDetailsAction, trackHomepageAction: trackHomepageAction, trackRoute: trackRoute, trackQuery: trackQuery };
Set Django to version 1.8.13 and add mock as dependency
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages PACKAGE = "patlms-web" setup( name=PACKAGE, version=0.1, description='PAT LMS web server', author='Adam Chyła', author_email='adam@chyla.org', license='GPLv3', url='https://github.com/chyla/pat-lms', packages=find_packages(exclude=['tests.*', 'tests', 'test.*', 'test*']), install_requires=['Django==1.8.13', ], setup_requires=['pytest-runner', ], tests_require=['pytest', 'mock', ], classifiers=[ 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages PACKAGE = "patlms-web" setup( name=PACKAGE, version=0.1, description='PAT LMS web server', author='Adam Chyła', author_email='adam@chyla.org', license='GPLv3', url='https://github.com/chyla/pat-lms', packages=find_packages(exclude=['tests.*', 'tests', 'test.*', 'test*']), install_requires=['Django>=1.8.0', ], setup_requires=['pytest-runner', ], tests_require=['pytest', ], classifiers=[ 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, )
Fix mapping of [allowed actions] vs. [VM state]
export function canStart (state) { return state && (state === 'down' || state === 'paused' || state === 'suspended') } export function canShutdown (state) { return canRestart(state) || state === 'reboot_in_progress' } export function canRestart (state) { return state && (state === 'up' || state === 'migrating') } export function canSuspend (state) { return state && (state === 'up') } export function canConsole (state) { return state && (state === 'up' || state === 'powering_up' || state === 'powering_down' || state === 'paused' || state === 'migrating' || state === 'reboot_in_progress' || state === 'saving_state') } /* public enum VmStatus { UNASSIGNED, DOWN, UP, POWERING_UP, PAUSED, MIGRATING, UNKNOWN, NOT_RESPONDING, WAIT_FOR_LAUNCH, REBOOT_IN_PROGRESS, SAVING_STATE, RESTORING_STATE, SUSPENDED, IMAGE_LOCKED, POWERING_DOWN; } */
// TODO: review - use VM status functions similar to the ovirt-engine export function canStart (state) { return state && state === 'down' } // TODO: review export function canShutdown (state) { return canRestart(state) } // TODO: review export function canRestart (state) { return state && (canSuspend(state) || state === 'paused' || state === 'suspended') } // TODO: review export function canSuspend (state) { return state && (state === 'up' || state === 'powering_up') } // TODO: review export function canConsole (state) { return canSuspend(state) } /* public enum VmStatus { UNASSIGNED, DOWN, UP, POWERING_UP, PAUSED, MIGRATING, UNKNOWN, NOT_RESPONDING, WAIT_FOR_LAUNCH, REBOOT_IN_PROGRESS, SAVING_STATE, RESTORING_STATE, SUSPENDED, IMAGE_LOCKED, POWERING_DOWN; } */
Remove sqlite3 package. Its available by default in most python distributions.
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').read(), install_requires=[ 'weavelib', 'eventlet!=0.22', 'bottle', 'GitPython', 'redis', 'appdirs', 'peewee', ], entry_points={ 'console_scripts': [ 'weave-launch = app:handle_launch', 'weave-main = app:handle_main' ] } )
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').read(), install_requires=[ 'weavelib', 'eventlet!=0.22', 'bottle', 'GitPython', 'redis', 'sqlite3', 'appdirs', 'peewee', ], entry_points={ 'console_scripts': [ 'weave-launch = app:handle_launch', 'weave-main = app:handle_main' ] } )
Tweak license labels for consistency
package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0 License", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0 licenses", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT License", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License 1.1", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } }
package net.squanchy.about.licenses; import android.support.annotation.StringRes; import net.squanchy.R; enum License { APACHE_2("Apache 2.0", R.string.license_notice_apache_2), GLIDE("BSD, part MIT and Apache 2.0", R.string.license_notice_glide), ECLIPSE_PUBLIC_LICENSE("Eclipse Public License 1.0", R.string.license_notice_eclipse_public_license), MIT("MIT", R.string.license_notice_mit), OPEN_FONT_LICENSE("Open Font License", R.string.license_notice_open_font_license); private final String label; @StringRes private final int noticeResId; License(String label, int noticeResId) { this.label = label; this.noticeResId = noticeResId; } public String label() { return label; } @StringRes public int noticeResId() { return noticeResId; } }
Move message handling out of core
import queryString from 'query-string' import events from '../core/events' import * as constants from '../constants' import { actions } from '../store/actions' import ReconnectingWebSocket from 'reconnectingwebsocket' const { setDocumentCaptured, setToken, setAuthenticated } = actions export default class Socket { connect(jwt) { const query = queryString.stringify({ jwt: jwt }) const url = `${constants.DEV_SOCKET_URL}?${query}` const socket = new ReconnectingWebSocket(url) socket.onopen = () => { this.socket = socket this.onMessage() setToken(jwt) setAuthenticated(true) } } onMessage() { this.socket.onmessage = (e) => { const data = JSON.parse(e.data) events.emit('onMessage', data) } } sendMessage(message) { this.socket.send(message) } }
import queryString from 'query-string' import events from '../core/events' import * as constants from '../constants' import { actions } from '../store/actions' import ReconnectingWebSocket from 'reconnectingwebsocket' const { setDocumentCaptured, setToken, setAuthenticated } = actions export default class Socket { connect(jwt) { const query = queryString.stringify({ jwt: jwt }) const url = `${constants.DEV_SOCKET_URL}?${query}` const socket = new ReconnectingWebSocket(url) socket.onopen = () => { this.socket = socket this.onMessage() setToken(jwt) setAuthenticated(true) } } handleData(data) { events.emit('onMessage', data) if (data.is_document) { setDocumentCaptured(true) } } onMessage() { this.socket.onmessage = (e) => { const data = JSON.parse(e.data) this.handleData(data) } } sendMessage(message) { this.socket.send(message) } }
Allow 'Y' and 'N' (upper case) as a response for a yes/no question.
package net.rubygrapefruit.platform.prompts; class YesNoListener extends AbstractListener { private final boolean defaultValue; private Boolean selected; private boolean finished; YesNoListener(boolean defaultValue) { this.defaultValue = defaultValue; } public boolean isFinished() { return finished; } public Boolean getSelected() { return selected; } @Override public void character(char ch) { if (ch == 'y' || ch == 'Y') { selected = true; finished = true; } else if (ch == 'n' || ch == 'N') { selected = false; finished = true; } } @Override public void controlKey(Key key) { if (key == Key.Enter) { selected = defaultValue; finished = true; } } @Override public void endInput() { finished = true; } }
package net.rubygrapefruit.platform.prompts; class YesNoListener extends AbstractListener { private final boolean defaultValue; private Boolean selected; private boolean finished; YesNoListener(boolean defaultValue) { this.defaultValue = defaultValue; } public boolean isFinished() { return finished; } public Boolean getSelected() { return selected; } @Override public void character(char ch) { if (ch == 'y') { selected = true; finished = true; } else if (ch == 'n') { selected = false; finished = true; } } @Override public void controlKey(Key key) { if (key == Key.Enter) { selected = defaultValue; finished = true; } } @Override public void endInput() { finished = true; } }
Refactor: Use ConfigXmlParser in activity. Adds CordovaWebView.init() This does subtly change the API surface due to CordovaWebView.init(), but only minimally, and is backwards compatibly with the default generated projects from prior versions.
/* Licensed to the Apache Software Foundation (ASF) 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 __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } }
/* Licensed to the Apache Software Foundation (ASF) 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 __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); // Set by <content src="index.html" /> in config.xml super.loadUrl(Config.getStartUrl()); //super.loadUrl("file:///android_asset/www/index.html"); } }
Use Equal() to compare FileInfo time This is because on some systems it is necessary to accurately compare time.
/* rulehunter - A server to find rules in data based on user specified goals Copyright (C) 2016 vLife Systems Ltd <http://vlifesystems.com> 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; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ package fileinfo import "time" // FileInfo represents a file name and modified time type FileInfo interface { Name() string ModTime() time.Time } // IsEqual returns if two FileInfo objects are equal func IsEqual(a, b FileInfo) bool { return a.Name() == b.Name() && a.ModTime().Equal(b.ModTime()) }
/* rulehunter - A server to find rules in data based on user specified goals Copyright (C) 2016 vLife Systems Ltd <http://vlifesystems.com> 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; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ package fileinfo import "time" // FileInfo represents a file name and modified time type FileInfo interface { Name() string ModTime() time.Time } // IsEqual returns if two FileInfo objects are equal func IsEqual(a, b FileInfo) bool { return a.Name() == b.Name() && a.ModTime() == b.ModTime() }
Fix mypy error in introspection check
from functools import partial from graphene.types.resolver import default_resolver from graphql import ResolveInfo def should_trace(info: ResolveInfo) -> bool: if info.field_name not in info.parent_type.fields: return False resolver = info.parent_type.fields[info.field_name].resolver return not ( resolver is None or is_default_resolver(resolver) or is_introspection_field(info) ) def is_introspection_field(info: ResolveInfo): if info.path is not None: for path in info.path: if isinstance(path, str) and path.startswith("__"): return True return False def is_default_resolver(resolver): while isinstance(resolver, partial): resolver = resolver.func if resolver is default_resolver: return True return resolver is default_resolver
from functools import partial from graphene.types.resolver import default_resolver from graphql import ResolveInfo def should_trace(info: ResolveInfo) -> bool: if info.field_name not in info.parent_type.fields: return False resolver = info.parent_type.fields[info.field_name].resolver return not ( resolver is None or is_default_resolver(resolver) or is_introspection_field(info) ) def is_introspection_field(info: ResolveInfo): for path in info.path: if isinstance(path, str) and path.startswith("__"): return True return False def is_default_resolver(resolver): while isinstance(resolver, partial): resolver = resolver.func if resolver is default_resolver: return True return resolver is default_resolver
Fix new line being included in an anchor
const axios = require('axios'); const chalk = require('chalk'); const helpers = require('../helpers'); exports.listArticles = function (argv) { const articleCount = argv.limit > 1 ? argv.limit : 1; axios.get('https://api.spaceflightnewsapi.net/articles/', { params: { limit: articleCount } }).then((response) => { const articles = response.data; const articlesByDate = articles.reduce((byDate, article) => { const title = chalk`${article.title}`; const publishedAt = new Date(article.date_published * 1000).toLocaleDateString(); const articleDetails = chalk`{yellow ${article.news_site_long}}`; const readSource = `Read on ${article.url}`; const dayArticles = byDate[publishedAt] = byDate[publishedAt] || []; dayArticles.push(`${articleDetails} | ${title}\n${readSource} \n`); return byDate; }, {}); for (const date in articlesByDate) { const dayArticles = articlesByDate[date]; helpers.printMessage(`${date}\n----------`); dayArticles.forEach(article => helpers.printMessage(article)); } }).catch(error => { const errorMessage = `${error.code}: ${error.message}`; helpers.printError(errorMessage); }); };
const axios = require('axios'); const chalk = require('chalk'); const helpers = require('../helpers'); exports.listArticles = function (argv) { const articleCount = argv.limit > 1 ? argv.limit : 1; axios.get('https://api.spaceflightnewsapi.net/articles/', { params: { limit: articleCount } }).then((response) => { const articles = response.data; const articlesByDate = articles.reduce((byDate, article) => { const title = chalk`${article.title}`; const publishedAt = new Date(article.date_published * 1000).toLocaleDateString(); const articleDetails = chalk`{yellow ${article.news_site_long}}`; const readSource = `Read on ${article.url}`; const dayArticles = byDate[publishedAt] = byDate[publishedAt] || []; dayArticles.push(`${articleDetails} | ${title}\n${readSource}\n`); return byDate; }, {}); for (const date in articlesByDate) { const dayArticles = articlesByDate[date]; helpers.printMessage(`${date}\n----------`); dayArticles.forEach(article => helpers.printMessage(article)); } }).catch(error => { const errorMessage = `${error.code}: ${error.message}`; helpers.printError(errorMessage); }); };
Fix the failing test and add one more test to cover both when/otherwise conditions.
/** * Licensed to the Apache Software Foundation (ASF) 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 org.apache.camel.language; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringSimpleExpressionTest extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/language/SpringSimpleExpressionTest.xml"); } public void testSimpleWhenString() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("correct"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } public void testSimpleOtherwiseString() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("incorrect"); template.sendBody("direct:start", "Bye World"); assertMockEndpointsSatisfied(); } }
/** * Licensed to the Apache Software Foundation (ASF) 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 org.apache.camel.language; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringSimpleExpressionTest extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/language/SpringSimpleExpressionTest.xml"); } public void testSimpleEmptyString() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("False"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } }
Switch from delay ID to direct style manipulation. I was having trouble with the extension CSS file so I figured this was easier.
(function () { "use strict"; var settings, display; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { display = document.documentElement.style.display; document.documentElement.style.display = 'none'; window.setTimeout(function () { document.documentElement.style.display = display; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
(function () { "use strict"; var settings, id; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { id = document.firstChild.id || ''; document.firstChild.id += ' delay'; window.setTimeout(function () { document.firstChild.id = id; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
Use shortcut listen() for starting the HTTPServer.
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **settings.TORNADO_SETTINGS) def run(): from astral.api.handlers.events import queue_listener event_thread = threading.Thread(target=queue_listener) event_thread.daemon = True event_thread.start() app = NodeWebAPI() app.listen(settings.TORNADO_SETTINGS['port']) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **settings.TORNADO_SETTINGS) def run(): from astral.api.handlers.events import queue_listener event_thread = threading.Thread(target=queue_listener) event_thread.daemon = True event_thread.start() app = NodeWebAPI() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(settings.TORNADO_SETTINGS['port']) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
Add comment where it's probably necessary
<?php // Put the PML into a temp file. $pmlTempFile = tempnam("/tmp", "PML_IDE"); file_put_contents($pmlTempFile, $_POST["value"]); // Generate the graphviz file. $graphvizTempFile = tempnam("/tmp", "pml-studio"); file_put_contents($graphvizTempFile, shell_exec("../thirdparty/traverse/traverse $pmlTempFile")); // The second line in the file causes the filename to be displayed in the image, // looks messy when the filename is a tempfile generated here, remove the name. $tempFile = tempnam(".", "pml-studio"); shell_exec("sed '2d' $graphvizTempFile > $tempFile && mv $tempFile $graphvizTempFile"); // Generate the image. $pngTempFile = tempnam("../images", "pml-studio"); file_put_contents($pngTempFile, shell_exec("dot -Tpng $graphvizTempFile")); // Make it accessible. chmod($pngTempFile, 0755); // Return the relative file name of the image. echo "images/" . basename($pngTempFile);?>
<?php // Put the PML into a temp file. $pmlTempFile = tempnam("/tmp", "PML_IDE"); file_put_contents($pmlTempFile, $_POST["value"]); // Generate the graphviz file. $graphvizTempFile = tempnam("/tmp", "pml-studio"); file_put_contents($graphvizTempFile, shell_exec("../thirdparty/traverse/traverse $pmlTempFile")); $tempFile = tempnam(".", "pml-studio"); shell_exec("sed '2d' $graphvizTempFile > $tempFile && mv $tempFile $graphvizTempFile"); // Generate the image. $pngTempFile = tempnam("../images", "pml-studio"); file_put_contents($pngTempFile, shell_exec("dot -Tpng $graphvizTempFile")); // Make it accessible. chmod($pngTempFile, 0755); // Return the relative file name of the image. echo "images/" . basename($pngTempFile);?>
Increment version after change to get_base_url
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) with open('README.md') as readme: long_description = readme.read() setup( name='parserutils', description='A collection of performant parsing utilities', long_description=long_description, long_description_content_type='text/markdown', keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='1.2.4', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0' ], tests_require=['mock'], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) with open('README.md') as readme: long_description = readme.read() setup( name='parserutils', description='A collection of performant parsing utilities', long_description=long_description, long_description_content_type='text/markdown', keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='1.2.3', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0' ], tests_require=['mock'], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
Fix black space on login modal
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2016 */ import { BACKGROUND_COLOR, SUSSOL_ORANGE, WARMER_GREY } from './colors'; import { APP_FONT_FAMILY } from './fonts'; export const authStyles = { authFormModal: { flex: 1, backgroundColor: BACKGROUND_COLOR, justifyContent: 'flex-start', }, authFormTextInputStyle: { flex: 1, marginHorizontal: 60, color: SUSSOL_ORANGE, fontFamily: APP_FONT_FAMILY, }, authFormContainer: { marginTop: 80, marginHorizontal: 300, alignItems: 'center', justifyContent: 'flex-start', backgroundColor: 'white', borderColor: WARMER_GREY, borderWidth: 1, borderRadius: 1, }, authFormButton: { backgroundColor: SUSSOL_ORANGE, }, authFormButtonContainer: { alignSelf: 'stretch', }, authFormButtonText: { color: 'white', fontFamily: APP_FONT_FAMILY, textAlign: 'center', fontSize: 22, marginVertical: 15, }, authFormLogo: { marginTop: 30, marginBottom: 60, }, authWindowButtonText: { fontFamily: APP_FONT_FAMILY, color: WARMER_GREY, }, loginButton: { marginTop: 60, }, };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2016 */ import { BACKGROUND_COLOR, SUSSOL_ORANGE, WARMER_GREY } from './colors'; import { APP_FONT_FAMILY } from './fonts'; export const authStyles = { authFormModal: { position: 'absolute', top: 0, left: 0, backgroundColor: BACKGROUND_COLOR, justifyContent: 'flex-start', }, authFormTextInputStyle: { flex: 1, marginHorizontal: 60, color: SUSSOL_ORANGE, fontFamily: APP_FONT_FAMILY, }, authFormContainer: { marginTop: 80, marginHorizontal: 300, alignItems: 'center', justifyContent: 'flex-start', backgroundColor: 'white', borderColor: WARMER_GREY, borderWidth: 1, borderRadius: 1, }, authFormButton: { backgroundColor: SUSSOL_ORANGE, }, authFormButtonContainer: { alignSelf: 'stretch', }, authFormButtonText: { color: 'white', fontFamily: APP_FONT_FAMILY, textAlign: 'center', fontSize: 22, marginVertical: 15, }, authFormLogo: { marginTop: 30, marginBottom: 60, }, authWindowButtonText: { fontFamily: APP_FONT_FAMILY, color: WARMER_GREY, }, loginButton: { marginTop: 60, }, };
Use parent[x] == x for root, not -1 as before
package main type DisjoinSet struct { parent []int rank []int } func NewDisjoinSet() *DisjoinSet { return &DisjoinSet{} } func (s *DisjoinSet) Make() int { x := len(s.parent) s.parent = append(s.parent, x) s.rank = append(s.rank, 0) return x } func (s *DisjoinSet) Find(x int) int { if s.parent[x] == x { return x } return s.Find(s.parent[x]) } func (s *DisjoinSet) Join(x, y int) { xRoot := s.Find(x) yRoot := s.Find(y) switch { case s.rank[xRoot] < s.rank[yRoot]: s.parent[xRoot] = yRoot case s.rank[xRoot] > s.rank[yRoot]: s.parent[yRoot] = xRoot default: s.rank[xRoot]++ s.parent[yRoot] = xRoot } }
package main type DisjoinSet struct { parent []int rank []int } func NewDisjoinSet() *DisjoinSet { return &DisjoinSet{} } func (s *DisjoinSet) Make() int { s.parent = append(s.parent, -1) s.rank = append(s.rank, 0) return len(s.parent) - 1 } func (s *DisjoinSet) Find(x int) int { if s.parent[x] == -1 { return x } return s.Find(s.parent[x]) } func (s *DisjoinSet) Join(x, y int) { xRoot := s.Find(x) yRoot := s.Find(y) switch { case s.rank[xRoot] < s.rank[yRoot]: s.parent[xRoot] = yRoot case s.rank[xRoot] > s.rank[yRoot]: s.parent[yRoot] = xRoot default: s.rank[xRoot]++ s.parent[yRoot] = xRoot } }
Fix deprecation re nested ternary
<?php class Security_Config_Framework extends Config { protected static $_remoteSetupWhitelist = array( "127.0.0.1" ); protected static $_allowAllRemoteAdmin = true; protected static $_remoteAdminWhiteList = array( "127.0.0.1" ); protected static $_salt = "Php.Gt default salt - please change this!"; protected static $_domain; protected static $_remoteIp; public static function init() { if(!defined("APPSALT")) { define("APPSALT", hash("sha512", static::$_salt)); } static::$_remoteIp = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : null; static::$_domain = isset(static::$_domain) ? static::$_domain : (isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : null); } public static function getDomain() { return static::$_domain; } public static function isSetupAllowed() { return in_array(static::$_remoteIp, static::$_remoteSetupWhitelist); } public static function isAdminAllowed() { return in_array(static::$_remoteIp, static::$_remoteAdminWhiteList) || static::$_allowAllRemoteAdmin; } }#
<?php class Security_Config_Framework extends Config { protected static $_remoteSetupWhitelist = array( "127.0.0.1" ); protected static $_allowAllRemoteAdmin = true; protected static $_remoteAdminWhiteList = array( "127.0.0.1" ); protected static $_salt = "Php.Gt default salt - please change this!"; protected static $_domain; protected static $_remoteIp; public static function init() { if(!defined("APPSALT")) { define("APPSALT", hash("sha512", static::$_salt)); } static::$_remoteIp = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : null; static::$_domain = isset(static::$_domain) ? static::$_domain : isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : null; } public static function getDomain() { return static::$_domain; } public static function isSetupAllowed() { return in_array(static::$_remoteIp, static::$_remoteSetupWhitelist); } public static function isAdminAllowed() { return in_array(static::$_remoteIp, static::$_remoteAdminWhiteList) || static::$_allowAllRemoteAdmin; } }#
Fix test broken by last commit.
""" Handlers for fetching upload templates. """ from django.shortcuts import render CONTENT_TYPE__CSV = 'text/csv' TEMPLATE__SAMPLES_BATCH_IMPORT_FROM_SERVER = 'sample_list_targets_template.csv' TEMPLATE__SAMPLES_BATCH_BROWSER_UPLOAD = ( 'sample_list_browser_upload_template.csv') def sample_list_targets_template(request): """Let the user download a blank sample targets template as a comma-separated values file (.csv) so they can fill it in and upload it back to the server. """ context = {} return render(request, TEMPLATE__SAMPLES_BATCH_IMPORT_FROM_SERVER, context, content_type=CONTENT_TYPE__CSV) def variant_set_upload_template(request): """Let the user download a blank variant set template as a blank VCF file to be filled in. """ context = {} return render(request, 'variant_set_upload_template.vcf', context, content_type='text/tab-separated-values') def sample_list_browser_upload_template(request): """Template that allows the user to indicate the names of samples they will updload through the browser form. """ context = {} return render(request, TEMPLATE__SAMPLES_BATCH_BROWSER_UPLOAD, context, content_type=CONTENT_TYPE__CSV)
""" Handlers for fetching upload templates. """ from django.shortcuts import render CONTENT_TYPE__CSV = 'text/csv' TEMPLATE__SAMPLES_BATCH_IMPORT_FROM_SERVER = 'sample_list_targets_template.csv' TEMPLATE__SAMPLES_BATCH_BROWSER_UPLOAD = ( 'sample_list_browser_upload_template.tsv') def sample_list_targets_template(request): """Let the user download a blank sample targets template as a comma-separated values file (.csv) so they can fill it in and upload it back to the server. """ context = {} return render(request, TEMPLATE__SAMPLES_BATCH_IMPORT_FROM_SERVER, context, content_type=CONTENT_TYPE__CSV) def variant_set_upload_template(request): """Let the user download a blank variant set template as a blank VCF file to be filled in. """ context = {} return render(request, 'variant_set_upload_template.vcf', context, content_type='text/tab-separated-values') def sample_list_browser_upload_template(request): """Template that allows the user to indicate the names of samples they will updload through the browser form. """ context = {} return render(request, TEMPLATE__SAMPLES_BATCH_BROWSER_UPLOAD, context, content_type=CONTENT_TYPE__CSV)
Make cookie a little more robust
'use strict'; const uuidv4 = require('uuid/v4'); // TODO init that sets cookie name? const sessionIdent = 'tiny-ident'; const get = (req, res) => { let uuid; if ((req.cookies || {})[sessionIdent]) { uuid = req.cookies[sessionIdent]; } else { // generate unique session-id uuid = uuidv4(); } setCookie(req, res, uuid); return uuid; }; const setCookie = (req, res, uuid) => { console.log(req.get('host')); // maxAge = one year from now. const maxAge = 1000 * 60 * 60 * 24 * 365; // Date object set at one year from now. const expires = new Date(); expires.setFullYear(expires.getFullYear() + 1); if (res.cookie) { res.cookie(sessionIdent, uuid, { domain: req.get('host'), httpOnly: true, expires: expires, maxAge: maxAge, sameSite: 'strict' }); } }; module.exports = { get };
'use strict'; const uuidv4 = require('uuid/v4'); // TODO init that sets cookie name? const sessionIdent = 'tiny-ident'; const get = (req, res) => { let uuid; if ((req.cookies || {})[sessionIdent]) { uuid = req.cookies[sessionIdent]; } else { // generate unique session-id uuid = uuidv4(); } set(res, uuid); return uuid; }; // TODO: update cookie expire-time when used const set = (res, uuid) => { // maxAge = one year from now. const maxAge = 1000 * 60 * 60 * 24 * 365; // Date object set at one year from now. const expires = new Date(); expires.setFullYear(expires.getFullYear() + 1); if (res.cookie) { res.cookie(sessionIdent, uuid, { httpOnly: true, expires: expires, maxAge: maxAge }); } }; module.exports = { get };
Use `Error.toString` for a displayed message whenever possible
/* * Copyright 2015 Vivliostyle Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import ko from "knockout"; function MessageDialog(queue) { this.list = queue; this.visible = ko.pureComputed(function() { return queue().length > 0; }); } MessageDialog.prototype.getDisplayMessage = function(errorInfo) { var e = errorInfo.error; var msg = e && (e.toString() || e.frameTrace || e.stack); if (msg) { msg = msg.split("\n", 1)[0]; } if (!msg) { msg = errorInfo.messages.join("\n"); } return msg; }; export default MessageDialog;
/* * Copyright 2015 Vivliostyle Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import ko from "knockout"; function MessageDialog(queue) { this.list = queue; this.visible = ko.pureComputed(function() { return queue().length > 0; }); } MessageDialog.prototype.getDisplayMessage = function(errorInfo) { var msg; var e = errorInfo.error; var stack = e && (e.frameTrace || e.stack || e.toString()); if (stack) { msg = stack.split("\n", 1)[0]; } if (!msg) { msg = errorInfo.messages.join("\n"); } return msg; }; export default MessageDialog;
Change next to createStore for better readability
import compose from './compose' /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ export default function applyMiddleware(...middlewares) { return (createStore) => (reducer, initialState) => { var store = createStore(reducer, initialState) var dispatch = store.dispatch var chain = [] var middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) } chain = middlewares.map(middleware => middleware(middlewareAPI)) dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }
import compose from './compose' /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ export default function applyMiddleware(...middlewares) { return (next) => (reducer, initialState) => { var store = next(reducer, initialState) var dispatch = store.dispatch var chain = [] var middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) } chain = middlewares.map(middleware => middleware(middlewareAPI)) dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }
Use stream for lower memory usage
import base64 import os from armaadmin import users, web class AuthorizedHandler(web.HTTPHandler): auth = [ 'Basic', 'Key' ] realm = 'unknown' def respond(self): auth_header = self.request.headers.get('Authorization') if not auth_header: return unauthorized() try: self.auth_type, self.auth_string = auth_header.split(' ', 1) #Ignore bad Authorization headers except: return unauthorized() if not self.auth_type in self.auth: return unauthorized() web.HTTPHandler.respond(self) def unauthorized(self): self.response.headers.set('WWW-Authenticate', ','.join(self.auth) + ' realm="' + self.realm + '"') raise web.HTTPError(401) class PageHandler(web.HTTPHandler): page = 'index.html' def do_get(self): with open(os.path.dirname(__file__) + '/html/' + self.page, 'r') as file: self.response.headers.set('Content-Type', 'text/html') return 200, file
import base64 import os from armaadmin import users, web class AuthorizedHandler(web.HTTPHandler): auth = [ 'Basic', 'Key' ] realm = 'unknown' def respond(self): auth_header = self.request.headers.get('Authorization') if not auth_header: return unauthorized() try: self.auth_type, self.auth_string = auth_header.split(' ', 1) #Ignore bad Authorization headers except: return unauthorized() if not self.auth_type in self.auth: return unauthorized() web.HTTPHandler.respond(self) def unauthorized(self): self.response.headers.set('WWW-Authenticate', ','.join(self.auth) + ' realm="' + self.realm + '"') raise web.HTTPError(401) class PageHandler(web.HTTPHandler): page = 'index.html' def do_get(self): with open(os.path.dirname(__file__) + '/html/' + self.page, 'r') as file: self.response.headers.set('Content-Type', 'text/html') return 200, file.read()
Fix a race condition when adding output streams before all input streams are added.
var LogStream = require('./LogStream'); var lodash = require('lodash'); /** * The LogFactory constructor. * @constructor */ var LogFactory = function () { var self = this; self._inputs = {}; self._outputs = []; }; /** * Create a new LogStream. * @param name The name of the component originating the logs. * @returns {LogStream} */ LogFactory.prototype.create = function (name) { var self = this; self._inputs[name] = new LogStream(name); lodash.forEach(self._outputs, function (outputStream) { self._inputs[name].pipe(outputStream); }); return self._inputs[name]; }; /** * Connect all loggers to an output stream. * * Example: * logFactory.pipe(process.stdout) * * @param outputStream A node stream.Writable that will accept all log events. */ LogFactory.prototype.pipe = function (outputStream) { var self = this; self._outputs.push(outputStream); lodash.forEach(self._inputs, function (stream) { stream.pipe(outputStream, { end: false }); }); }; // It's a single instance. module.exports = new LogFactory();
var LogStream = require('./LogStream'); var lodash = require('lodash'); /** * The LogFactory constructor. * @constructor */ var LogFactory = function () { var self = this; self._streams = {}; self._filters = []; }; /** * Create a new LogStream. * @param name The name of the component originating the logs. * @returns {LogStream} */ LogFactory.prototype.create = function (name) { var self = this; self._streams[name] = new LogStream(name); self._streams[name].on('error', function (error) { self.streams['BeagleDrone.server.LogFactory'].error(error); }); return self._streams[name]; }; /** * Connect all loggers to an output stream. * * Example: * logFactory.pipe(process.stdout) * * @param outputStream A node stream.Writable that will accept all log events. */ LogFactory.prototype.pipe = function (outputStream) { var self = this; lodash.forEach(self._streams, function (stream) { stream.pipe(outputStream, { end: false }); }); }; // It's a single instance. module.exports = new LogFactory();
feature(blog): Add functionality to created blog post
'use strict'; //noinspection JSUnresolvedVariable var path = require('path'), baboon = require('../lib/baboon')(path.join(__dirname)), // middleware = baboon.middleware, server = baboon.server, // app = server.app, config = baboon.config, // auth = middleware.auth, api = require(config.path.api); /////////////////////////////////////////// // routes /////////////////////////////////////////// // login route //app.get('/login', function(req, res) { // res.render('login'); //}); //app.get('*', function(req, res) { // res.render('index'); //}); // login middleware //app.post('/login', auth.login); // //// logout middleware //app.get('/logout', auth.logout); /////////////////////////////////////////// // api /////////////////////////////////////////// // enable socket.io api api.socket(baboon); /////////////////////////////////////////// // server /////////////////////////////////////////// // start express server server.start();
'use strict'; //noinspection JSUnresolvedVariable var path = require('path'), baboon = require('../lib/baboon')(path.join(__dirname)), // middleware = baboon.middleware, server = baboon.server, app = server.app, config = baboon.config, // auth = middleware.auth, api = require(config.path.api); /////////////////////////////////////////// // routes /////////////////////////////////////////// // login route //app.get('/login', function(req, res) { // res.render('login'); //}); //app.get('*', function(req, res) { // res.render('index'); //}); // login middleware //app.post('/login', auth.login); // //// logout middleware //app.get('/logout', auth.logout); /////////////////////////////////////////// // api /////////////////////////////////////////// // enable socket.io api api.socket(baboon); /////////////////////////////////////////// // server /////////////////////////////////////////// // start express server server.start();
Tweak commuting activity POST endpoint.
import rp from 'request-promise' import { Observable } from 'rx' const sendActivityToCoreService = (activities$, requestLib=rp) => { return activities$ .flatMap(activity => { const performRequest = requestLib({ method: 'POST', uri: process.env.CORE_ACTIVITY_API_ENDPOINT || 'https://velocitas-core.herokuapp.com/api/v1/commuting/activities', body: activity.toJSON, json: true }) return Observable.fromPromise(performRequest) .catch(e => { console.error(`Error performing HTTP request: ${e}`); return Observable.just('error'); }) .tap(v => console.log(`Performed HTTP request. Response: ${v}`)) .map(_ => activity) }); }; export default sendActivityToCoreService;
import rp from 'request-promise' import { Observable } from 'rx' const sendActivityToCoreService = (activities$, requestLib=rp) => { return activities$ .flatMap(activity => { const performRequest = requestLib({ method: 'POST', uri: process.env.CORE_ACTIVITY_API_ENDPOINT || 'https://velocitas-core.herokuapp.com/api/commutes/activities', body: activity.toJSON, json: true }) return Observable.fromPromise(performRequest) .catch(e => { console.error(`Error performing HTTP request: ${e}`); return Observable.just('error'); }) .tap(v => console.log(`Performed HTTP request. Response: ${v}`)) .map(_ => activity) }); }; export default sendActivityToCoreService;
[native] Use threadLabel function in ThreadVisibility Test Plan: Tested all of thread types and checked if label is displayed correctly Reviewers: ashoat, palys-swm Reviewed By: ashoat, palys-swm Subscribers: zrebcu411, Adrian, atul, subnub Differential Revision: https://phabricator.ashoat.com/D659
// @flow import * as React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { threadLabel } from 'lib/shared/thread-utils'; import type { ThreadType } from 'lib/types/thread-types'; import ThreadIcon from './thread-icon.react'; type Props = {| +threadType: ThreadType, +color: string, |}; function ThreadVisibility(props: Props) { const { threadType, color } = props; const visLabelStyle = [styles.visibilityLabel, { color }]; const label = threadLabel(threadType); return ( <View style={styles.container}> <ThreadIcon threadType={threadType} color={color} /> <Text style={visLabelStyle}>{label}</Text> </View> ); } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'row', }, visibilityLabel: { fontSize: 16, fontWeight: 'bold', paddingLeft: 4, }, }); export default ThreadVisibility;
// @flow import * as React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { threadTypes, type ThreadType } from 'lib/types/thread-types'; import ThreadIcon from './thread-icon.react'; type Props = {| +threadType: ThreadType, +color: string, |}; function ThreadVisibility(props: Props) { const { threadType, color } = props; const visLabelStyle = [styles.visibilityLabel, { color }]; let label; if (threadType === threadTypes.CHAT_SECRET) { label = 'Secret'; } else if (threadType === threadTypes.PRIVATE) { label = 'Private'; } else { label = 'Open'; } return ( <View style={styles.container}> <ThreadIcon threadType={threadType} color={color} /> <Text style={visLabelStyle}>{label}</Text> </View> ); } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'row', }, visibilityLabel: { fontSize: 16, fontWeight: 'bold', paddingLeft: 4, }, }); export default ThreadVisibility;
Add instrumentation test to validate that recipe type is passed to recipes activity
package com.cwainner.chris.recipecentral; import android.support.test.rule.ActivityTestRule; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; public class MainActivityInstrumentationTest { @Rule public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void validateEditText(){ onView(withId(R.id.recipeEditText)).perform(typeText("Brownies")) .check(matches(withText("Brownies"))); } @Test public void textInputSentToRecipesActivity(){ String textToInput = "Brownies"; onView(withId(R.id.recipeEditText)).perform(typeText(textToInput)); onView(withId(R.id.getRecipesButton)).perform(click()); onView(withId(R.id.recipeTypeView)).check(matches(withText("Recipe type: " + textToInput))); } }
package com.cwainner.chris.recipecentral; import android.support.test.rule.ActivityTestRule; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; public class MainActivityInstrumentationTest { @Rule public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void validateEditText(){ onView(withId(R.id.recipeEditText)).perform(typeText("Brownies")) .check(matches(withText("Brownies"))); } }
Fix 16-bit unsigned hex parsing Exception with custom unsigned hex parser.
package com.example.testapp; import java.net.InetAddress; /** All public data members, similar to a C-struct */ public class ClientDevice { public int id; public long hash; public String name; public InetAddress ip; public int port; long unsignedParseLongHex(String s) { long l = 0; long hi = Long.parseLong(s.substring(0, 8), 16), lo = Long.parseLong( s.substring(8), 16); l = (hi << 32) | lo; return l; } ClientDevice(String desc) { id = 0; port = 0; // desc format: <name> (hash in 64-bit hex) connected String delims = "[ ]+"; String tokens[] = desc.split(delims); name = tokens[0]; String hashString = tokens[1].substring(1, tokens[1].length() - 1); // Long.parseLong **sucks**. It is expecting a positive number, so it // doesn't work if the first character on a 16-hex is 8-f // I'm doing the split into two 32-bit longs and bitwise xor. hash = unsignedParseLongHex(hashString); } @Override public boolean equals(Object other) { if (other instanceof ClientDevice) return ((ClientDevice) other).hash == this.hash; else return false; } @Override public int hashCode() { return (int) (hash & 0xffffffff); } }
package com.example.testapp; import java.net.InetAddress; /** All public data members, similar to a C-struct */ public class ClientDevice { public int id; public long hash; public String name; public InetAddress ip; public int port; ClientDevice(String desc) { id = 0; port = 0; // desc format: <name> (hash in 64-bit hex) connected String delims = "[ ]+"; String tokens[] = desc.split(delims); name = tokens[0]; String hashString = tokens[1].substring(1, tokens[1].length() - 1); hash = Long.parseLong(hashString, 16); } @Override public boolean equals(Object other) { if (other instanceof ClientDevice) return ((ClientDevice) other).hash == this.hash; else return false; } @Override public int hashCode() { return (int) (hash & 0xffffffff); } }
Remove the section from deptnums, to match with crsid. WRIT 111A and WRI111B have the same crsid, so now they'll have the same deptnum, too.
var _ = require('lodash') var courses = require('./db').courses function splitDeptNum(deptNumString) { // "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"] // -> {depts: ['AS', 'RE'], num: 230} var combined = deptNumString.toUpperCase() var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi var matches = regex.exec(combined) return { dept: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]], num: parseInt(matches[4], 10) } } function buildDeptNum(course) { return course.depts.join('/') + ' ' + course.num } module.exports.splitDeptNum = splitDeptNum module.exports.buildDeptNum = buildDeptNum
var _ = require('lodash') var courses = require('./db').courses function splitDeptNum(deptNumString) { // "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"] // -> {depts: ['AS', 'RE'], num: 230, sect: 'A'} var combined = deptNumString.toUpperCase() var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi var matches = regex.exec(combined) return { dept: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]], num: parseInt(matches[4], 10), sect: matches[5] || undefined } } function buildDeptNum(course) { return course.depts.join('/') + ' ' + course.num + (course.sect || '') } module.exports.splitDeptNum = splitDeptNum module.exports.buildDeptNum = buildDeptNum
fix: Call itemMediator in Array constructor
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } const def = initMK(this); const { itemMediator } = def; // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { this[index] = itemMediator ? itemMediator(arg, index) : arg; }); this.length = arguments.length; } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } initMK(this); // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { this[index] = arg; }); this.length = arguments.length; } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
Fix bugs with unzip command
var path = require('path'); var spawn = require('child_process').spawn; exports.TGZ = '.tar.gz'; exports.ZIP = '.zip'; function extract(type, archivePath, destDir, cb) { var child; switch(type) { case exports.TGZ: child = spawn('tar', ['-xzf', archivePath, '-C', destDir]); break; case exports.ZIP: child = spawn('unzip', [archivePath, '-d', destDir]); break; default: return cb(new Error('Invalid archive type !')); } process.stdin.pipe(child.stdin); child.stdout.pipe(process.stdout, {end: true}); child.stderr.pipe(process.stderr, {end: true}); child.once('close', function(code) { if(code !== 0) { return cb(new Error('Error while extracting !')); } return cb(null, archivePath); }); } exports.zip = extract.bind(null, exports.ZIP); exports.tgz = extract.bind(null, exports.TGZ);
var path = require('path'); var spawn = require('child_process').spawn; exports.TGZ = '.tar.gz'; exports.ZIP = '.zip'; function extract(type, archivePath, destDir, cb) { var child; switch(type) { case exports.TGZ: child = spawn('tar', ['-xzf', archivePath, '-C', destDir]); break; case exports.ZIP: var subDir = path.basename(archivePath, type); destDir = path.join(destDir, subDir); child = spawn('unzip', [archivePath, '-d', destDir]); break; default: return cb(new Error('Invalid archive type !')); } process.stdin.pipe(child.stdin); child.stdout.pipe(process.stdout, {end: true}); child.stderr.pipe(process.stderr, {end: true}); child.once('close', function(code) { if(code !== 0) { return cb(new Error('Error while extracting !')); } return cb(null, archivePath); }); } exports.zip = extract.bind(null, exports.ZIP); exports.tgz = extract.bind(null, exports.TGZ);
CATL-939: Access Array Values Directly On Method Call
<?php function _civicrm_api3_case_getcaselist_spec(&$spec) { $spec = civicrm_api3('Case', 'getfields', array('api_action' => 'get'))['values']; $spec['case_manager'] = array( 'title' => 'Case Manager', 'description' => 'Contact id of the case manager', 'type' => CRM_Utils_Type::T_INT, ); $spec['contact_is_deleted'] = array( 'title' => 'Contact Is Deleted', 'description' => 'Set FALSE to filter out cases for deleted contacts, TRUE to return only cases of deleted contacts', 'type' => CRM_Utils_Type::T_BOOLEAN, ); } function civicrm_api3_case_getcaselist($params) { return CRM_Civicase_Utils_Caselist::getCaseList($params); }
<?php function _civicrm_api3_case_getcaselist_spec(&$spec) { $result = civicrm_api3('Case', 'getfields', array('api_action' => 'get')); $spec = $result['values']; $spec['case_manager'] = array( 'title' => 'Case Manager', 'description' => 'Contact id of the case manager', 'type' => CRM_Utils_Type::T_INT, ); $spec['contact_is_deleted'] = array( 'title' => 'Contact Is Deleted', 'description' => 'Set FALSE to filter out cases for deleted contacts, TRUE to return only cases of deleted contacts', 'type' => CRM_Utils_Type::T_BOOLEAN, ); } function civicrm_api3_case_getcaselist($params) { return CRM_Civicase_Utils_Caselist::getCaseList($params); }
Add fetch methods for popular and airing today tv shows and data stores to hold results
angular.module('zeus.landing', []) .controller('LandingController', function($scope, Landing) { $scope.popularmovies = {}; $scope.latestmovies = {}; $scope.upcomingmovies = {}; $scope.popularshows = {}; $scope.latestshows = {}; $scope.fetchPopularMovies = function() { Landing.getPopularMovies() .then(function(data) { $scope.popularmovies = data.results; }); }; $scope.fetchLatestMovies = function() { Landing.getLatestMovies() .then(function(data) { $scope.latestmovies = data.results; }); }; $scope.fetchUpcomingMovies = function() { Landing.getUpcomingMovies() .then(function(data) { $scope.upcomingmovies = data.results; }); }; $scope.fetchPopularShows = function() { Landing.getPopularShows() .then(function(data) { $scope.popularshows = data.results; }); }; $scope.fetchLatestShows = function() { Landing.getLatestShows() .then(function(data) { $scope.latestshows = data.results; }); }; });
angular.module('zeus.landing', []) .controller('LandingController', function($scope, Landing) { $scope.popularmovies = {}; $scope.latestmovies = {}; $scope.upcomingmovies = {}; $scope.fetchPopularMovies = function() { Landing.getPopularMovies() .then(function(data) { $scope.popularmovies = data.results; }); }; $scope.fetchLatestMovies = function() { Landing.getLatestMovies() .then(function(data) { $scope.latestmovies = data.results; }); }; $scope.fetchUpcomingMovies = function() { Landing.getUpcomingMovies() .then(function(data) { $scope.upcomingmovies = data.results; }); }; });
Use get_manager() for Counter direct
# -*- coding: utf-8 -*- # Copyright 2017 - 2019 Avram Lubkin, All Rights Reserved # 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/. """ **Enlighten counter submodule** Provides Counter class """ import sys from enlighten._counter import Counter as _Counter from enlighten._counter import SubCounter # pylint: disable=unused-import # noqa: F401 from enlighten._manager import get_manager # Counter is defined here to avoid circular dependencies class Counter(_Counter): # pylint: disable=missing-docstring __doc__ = _Counter.__doc__ def __init__(self, **kwargs): manager = kwargs.get('manager', None) if manager is None: manager = get_manager(stream=kwargs.get('stream', sys.stdout), counter_class=self.__class__, set_scroll=False) manager.counters[self] = 1 kwargs['manager'] = manager super(Counter, self).__init__(**kwargs)
# -*- coding: utf-8 -*- # Copyright 2017 - 2019 Avram Lubkin, All Rights Reserved # 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/. """ **Enlighten counter submodule** Provides Counter class """ import sys from enlighten._counter import Counter as _Counter from enlighten._counter import SubCounter # pylint: disable=unused-import # noqa: F401 from enlighten._manager import Manager # Counter is defined here to avoid circular dependencies class Counter(_Counter): # pylint: disable=missing-docstring __doc__ = _Counter.__doc__ def __init__(self, **kwargs): manager = kwargs.get('manager', None) if manager is None: manager = Manager(stream=kwargs.get('stream', sys.stdout), counter_class=self.__class__, set_scroll=False) manager.counters[self] = 1 kwargs['manager'] = manager super(Counter, self).__init__(**kwargs)
Remove support for app:// protocol
import { L10nError } from '../../lib/errors'; const HTTP_STATUS_CODE_OK = 200; function load(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType('text/plain'); } xhr.open('GET', url, true); xhr.addEventListener('load', e => { if (e.target.status === HTTP_STATUS_CODE_OK || e.target.status === 0) { resolve(e.target.response); } else { reject(new L10nError('Not found: ' + url)); } }); xhr.addEventListener('error', reject); xhr.addEventListener('timeout', reject); xhr.send(null); }); } export function fetchResource(res, { code }) { const url = res.replace('{locale}', code); return load(url); }
import { L10nError } from '../../lib/errors'; const HTTP_STATUS_CODE_OK = 200; function load(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType('text/plain'); } xhr.open('GET', url, true); xhr.addEventListener('load', e => { if (e.target.status === HTTP_STATUS_CODE_OK || e.target.status === 0) { resolve(e.target.response); } else { reject(new L10nError('Not found: ' + url)); } }); xhr.addEventListener('error', reject); xhr.addEventListener('timeout', reject); // the app: protocol throws on 404, see https://bugzil.la/827243 try { xhr.send(null); } catch (e) { if (e.name === 'NS_ERROR_FILE_NOT_FOUND') { // the app: protocol throws on 404, see https://bugzil.la/827243 reject(new L10nError('Not found: ' + url)); } else { throw e; } } }); } export function fetchResource(res, { code }) { const url = res.replace('{locale}', code); return load(url); }
Fix 163 music art image selector.
'use strict'; /* global Connector */ Connector.playerSelector = '.m-playbar'; Connector.trackArtImageSelector = '.head.j-flag img'; Connector.getTrack = function() { var track = $('.fc1').text(); var re = new RegExp(String.fromCharCode(160), 'g'); return track.replace(re, ' '); }; Connector.getArtist = function () { return $('.by').children('span').attr('title') || null; }; Connector.playButtonSelector = '.btns .ply'; Connector.currentTimeSelector = '.j-flag.time em'; Connector.getDuration = function () { var totalSecondValue = $('#g_player').find('.time').text(); var duration = ''; if (totalSecondValue) { totalSecondValue = totalSecondValue.substr(totalSecondValue.length-4); duration = +totalSecondValue.split(':')[0]*60 + (+totalSecondValue.split(':')[1]); } return duration; }; Connector.isPlaying = function () { return $('.btns .ply').hasClass('pas'); };
'use strict'; /* global Connector */ Connector.playerSelector = '.m-playbar'; Connector.trackArtImageSelector = '.head img'; Connector.getTrack = function() { var track = $('.fc1').text(); var re = new RegExp(String.fromCharCode(160), 'g'); return track.replace(re, ' '); }; Connector.getArtist = function () { return $('.by').children('span').attr('title') || null; }; Connector.playButtonSelector = '.btns .ply'; Connector.currentTimeSelector = '.j-flag.time em'; Connector.getDuration = function () { var totalSecondValue = $('#g_player').find('.time').text(); var duration = ''; if (totalSecondValue) { totalSecondValue = totalSecondValue.substr(totalSecondValue.length-4); duration = +totalSecondValue.split(':')[0]*60 + (+totalSecondValue.split(':')[1]); } return duration; }; Connector.isPlaying = function () { return $('.btns .ply').hasClass('pas'); };
Add JSON and urlencoded body parsers.
'use strict'; let Gpio = require('pigpio').Gpio; let express = require('express'); let path = require('path'); let bodyParser = require('body-parser'); let gpioService = require('../lib/gpioservice')(Gpio); let ledHandler = require('../lib/ledhandler')(gpioService); let motorhandler = require('../lib/motorhandler')(gpioService); let api = require('../lib/restservice'); api.registerHandler('led', ledHandler); api.registerHandler('motor', motorhandler); let app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // api app.get('/api/:apiversion/:target/:key', api.dispatch); app.get('/api/:apiversion/:target', api.dispatch); app.post('/api/:apiversion/:target/:key', api.dispatch); app.post('/api/:apiversion/:target', api.dispatch); // static content app.use('/', express.static(path.join(__dirname, 'public'))); app.listen(8080, () => console.log('Listening on :8080'));
'use strict'; let Gpio = require('pigpio').Gpio; let express = require('express'); let path = require('path'); let gpioService = require('../lib/gpioservice')(Gpio); let ledHandler = require('../lib/ledhandler')(gpioService); let motorhandler = require('../lib/motorhandler')(gpioService); let api = require('../lib/restservice'); api.registerHandler('led', ledHandler); api.registerHandler('motor', motorhandler); let app = express(); // api app.get('/api/:apiversion/:target/:key/:value', api.dispatch); app.get('/api/:apiversion/:target/:key', api.dispatch); app.get('/api/:apiversion/:target', api.dispatch); app.post('/api/:apiversion/:target/:key/:value', api.dispatch); app.post('/api/:apiversion/:target/:key', api.dispatch); app.post('/api/:apiversion/:target', api.dispatch); // static content app.use('/', express.static(path.join(__dirname, 'public'))); app.listen(8080, () => console.log('Listening on :8080'));
Correct the patterns to match symbols appropriately
/** * Core Arez primitives. */ @OmitPattern( type = "^.*\\.Arez_[^\\.]+$", symbol = "^toString$", unless = "arez.enable_names" ) @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]+Repository$", symbol = "^getRepositoryName$", unless = "arez.enable_names" ) // No repository should have equals defined @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]+Repository$", symbol = "\\$equals" ) // No repositories need their own identity if native components disabled @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]+Repository$", symbol = "^\\$\\$arezi\\$\\$_id$", unless = "arez.enable_native_components" ) @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]+Repository$", symbol = "^\\$\\$arezi\\$\\$_nextId$", unless = "arez.enable_native_components" ) @OmitPattern( symbol = "^\\$clinit$" ) @KeepPattern( type = "^arez\\.ArezContextHolder$", symbol = "^\\$clinit$", unless = "arez.enable_zones" ) @KeepPattern( type = "^arez\\.ZoneHolder$", symbol = "^\\$clinit$", when = "arez.enable_zones" ) package arez; import grim.annotations.KeepPattern; import grim.annotations.OmitPattern;
/** * Core Arez primitives. */ @OmitPattern( type = "^.*\\.Arez_.*$", symbol = "^toString$", unless = "arez.enable_names" ) @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]Repository$", symbol = "^getRepositoryName$", unless = "arez.enable_names" ) // No repository should have equals defined @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]Repository$", symbol = "\\$equals" ) // No repositories need their own identity if native components disabled @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]Repository$", symbol = "^\\$\\$arezi\\$\\$_id$", unless = "arez.enable_native_components" ) @OmitPattern( type = "^.*(\\.|_)Arez_[^\\.]Repository$", symbol = "^\\$\\$arezi\\$\\$_nextId$", unless = "arez.enable_native_components" ) @OmitPattern( symbol = "^\\$clinit$" ) @KeepPattern( type = "^arez\\.ArezContextHolder$", symbol = "^\\$clinit$", unless = "arez.enable_zones" ) @KeepPattern( type = "^arez\\.ZoneHolder$", symbol = "^\\$clinit$", when = "arez.enable_zones" ) package arez; import grim.annotations.KeepPattern; import grim.annotations.OmitPattern;
Raise min required Python version to 3.5 Python 3.4 reached eol
import os import sys from distutils.core import setup def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() if sys.version_info >= (3, 5): install_requires = [] else: install_requires = ['asyncio'] install_requires.append('watchdog') exec(open('hachiko/version.py').read()) setup(name='hachiko', version=__version__, author='John Biesnecker', author_email='jbiesnecker@gmail.com', url='https://github.com/biesnecker/hachiko', packages=['hachiko'], package_dir={'hachiko': './hachiko'}, install_requires=install_requires, description='Asyncio wrapper around watchdog.', license='mit', long_description=read('README.txt') )
import os import sys from distutils.core import setup def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() if sys.version_info >= (3, 4): install_requires = [] else: install_requires = ['asyncio'] install_requires.append('watchdog') exec(open('hachiko/version.py').read()) setup(name='hachiko', version=__version__, author='John Biesnecker', author_email='jbiesnecker@gmail.com', url='https://github.com/biesnecker/hachiko', packages=['hachiko'], package_dir={'hachiko': './hachiko'}, install_requires=install_requires, description='Asyncio wrapper around watchdog.', license='mit', long_description=read('README.txt') )
Fix head color -- add material
import * as THREE from 'three'; import Material from '../helpers/material'; import MeshHelper from '../helpers/meshHelper'; import Helpers from '../../utils/helpers'; import Config from '../../data/config'; // Loads in a single object from the config file export default class Model { constructor(scene, loader) { this.scene = scene; // Manager is passed in to loader to determine when loading done in main this.loader = loader; this.obj = null; } load() { // Load model with ObjectLoader this.loader.load(Config.model.path, obj => { obj.traverse((child) => { if (child instanceof THREE.Mesh) { // Create material for mesh and set its map to texture by name from preloaded textures const material = new Material(0xffffff).basic; child.material = material; // Set to cast and receive shadow if enabled if (Config.shadow.enabled) { child.receiveShadow = true; child.castShadow = true; } } }); // Set prop to obj this.obj = obj; obj.name = 'dummyHead'; obj.position.y = 1; // necessary for raycasting onto the zone shape obj.rotation.y += Math.PI; obj.scale.multiplyScalar(Config.model.scale); this.scene.add(obj); }); } }
import * as THREE from 'three'; import Material from '../helpers/material'; import MeshHelper from '../helpers/meshHelper'; import Helpers from '../../utils/helpers'; import Config from '../../data/config'; // Loads in a single object from the config file export default class Model { constructor(scene, loader) { this.scene = scene; // Manager is passed in to loader to determine when loading done in main this.loader = loader; this.obj = null; } load() { // Load model with ObjectLoader this.loader.load(Config.model.path, obj => { obj.traverse((child) => { if (child instanceof THREE.Mesh) { // Create material for mesh and set its map to texture by name from preloaded textures // const material = new Material(0xffffff).standard; // child.material = material; // Set to cast and receive shadow if enabled if (Config.shadow.enabled) { child.receiveShadow = true; child.castShadow = true; } } }); // Set prop to obj this.obj = obj; obj.name = 'dummyHead'; obj.position.y = 1; // necessary for raycasting onto the zone shape obj.rotation.y += Math.PI; obj.scale.multiplyScalar(Config.model.scale); this.scene.add(obj); }); } }
Add --params flag to get-capacity
package cmd import ( "context" "fmt" "github.com/spf13/cobra" "github.com/container-storage-interface/spec/lib/go/csi" ) var getCapacity struct { caps volumeCapabilitySliceArg params mapOfStringArg } var getCapacityCmd = &cobra.Command{ Use: "get-capacity", Aliases: []string{"capacity"}, Short: `invokes the rpc "GetCapacity"`, RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithTimeout(root.ctx, root.timeout) defer cancel() rep, err := controller.client.GetCapacity( ctx, &csi.GetCapacityRequest{ Version: &root.version.Version, VolumeCapabilities: getCapacity.caps.data, Parameters: getCapacity.params.data, }) if err != nil { return err } fmt.Println(rep.AvailableCapacity) return nil }, } func init() { controllerCmd.AddCommand(getCapacityCmd) flagVolumeCapabilities(getCapacityCmd.Flags(), &getCapacity.caps) getCapacityCmd.Flags().Var( &getCapacity.params, "params", `One or more key/value pairs may be specified to send with the request as its Parameters field: --params key1=val1,key2=val2 --params=key3=val3`) }
package cmd import ( "context" "fmt" "github.com/spf13/cobra" "github.com/container-storage-interface/spec/lib/go/csi" ) var getCapacity struct { caps volumeCapabilitySliceArg } var getCapacityCmd = &cobra.Command{ Use: "get-capacity", Aliases: []string{"capacity"}, Short: `invokes the rpc "GetCapacity"`, RunE: func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithTimeout(root.ctx, root.timeout) defer cancel() rep, err := controller.client.GetCapacity( ctx, &csi.GetCapacityRequest{ Version: &root.version.Version, VolumeCapabilities: getCapacity.caps.data, }) if err != nil { return err } fmt.Println(rep.AvailableCapacity) return nil }, } func init() { controllerCmd.AddCommand(getCapacityCmd) flagVolumeCapabilities(getCapacityCmd.Flags(), &getCapacity.caps) }
Fix issue with gulp sequence Signed-off-by: Matt Stratton <39982728c5a806c113d54b69a3f65ecf65602e8a@gmail.com>
var gulp = require('gulp'), htmlmin = require('gulp-htmlmin'), imgRetina = require('gulp-img-retina'); // runSequence = require('run-sequence'); gulp.task('copy-html', function(){ return gulp.src('public/**/*.html') .pipe(gulp.dest('dist')) }) var retinaOpts = { suffix: {1: '', 2: '@2x'} }; gulp.task('min-html', function() { return gulp.src('public/**/*.html') .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); }) // min-html was taking forever gulp.task('retina-html', function() { return gulp.src(['dist/**/*.html', '!dist/events/2015*/**', '!dist/events/2016*/**']) .pipe(imgRetina(retinaOpts)) .on('error', function(e) { console.log(e.message); }) .pipe(gulp.dest('dist')); }) gulp.task('process-html', gulp.series('min-html', 'retina-html'));
var gulp = require('gulp'), htmlmin = require('gulp-htmlmin'), imgRetina = require('gulp-img-retina'); // runSequence = require('run-sequence'); gulp.task('process-html', function(callback) { runSequence('min-html', 'retina-html', callback ) }) gulp.task('copy-html', function(){ return gulp.src('public/**/*.html') .pipe(gulp.dest('dist')) }) var retinaOpts = { suffix: {1: '', 2: '@2x'} }; gulp.task('min-html', function() { return gulp.src('public/**/*.html') .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); }) // min-html was taking forever gulp.task('retina-html', function() { return gulp.src(['dist/**/*.html', '!dist/events/2015*/**', '!dist/events/2016*/**']) .pipe(imgRetina(retinaOpts)) .on('error', function(e) { console.log(e.message); }) .pipe(gulp.dest('dist')); })
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
""" Tests for qutip.nonmarkov.heom. """ from qutip.nonmarkov.heom import ( BathExponent, Bath, BosonicBath, DrudeLorentzBath, DrudeLorentzPadeBath, UnderDampedBath, FermionicBath, LorentzianBath, LorentzianPadeBath, HEOMSolver, HSolverDL, HierarchyADOs, HierarchyADOsState, ) class TestBathAPI: def test_api(self): # just assert that the baths are importable assert BathExponent assert Bath assert BosonicBath assert DrudeLorentzBath assert DrudeLorentzPadeBath assert UnderDampedBath assert FermionicBath assert LorentzianBath assert LorentzianPadeBath class TestSolverAPI: def test_api(self): # just assert that the solvers and associated classes are importable assert HEOMSolver assert HSolverDL assert HierarchyADOs assert HierarchyADOsState
""" Tests for qutip.nonmarkov.heom. """ from qutip.nonmarkov.heom import ( BathExponent, Bath, BosonicBath, DrudeLorentzBath, DrudeLorentzPadeBath, UnderDampedBath, FermionicBath, LorentzianBath, LorentzianPadeBath, HEOMSolver, HSolverDL, ) class TestBathAPI: def test_api(self): # just assert that the baths are importable assert BathExponent assert Bath assert BosonicBath assert DrudeLorentzBath assert DrudeLorentzPadeBath assert UnderDampedBath assert FermionicBath assert LorentzianBath assert LorentzianPadeBath class TestSolverAPI: def test_api(self): # just assert that the solvers are importable assert HEOMSolver assert HSolverDL
Use port 5000 for dokku
var webpack = require('webpack'); var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var env = process.env.WEBPACK_ENV; var WebpackDevServer = require('webpack-dev-server'); var appName = 'app'; var host = '0.0.0.0'; var port = '5000'; var plugins = [], outputFile; if (env === 'build') { plugins.push(new UglifyJsPlugin({ minimize: true })); outputFile = appName + '.min.js'; } else { outputFile = appName + '.js'; } var config = { entry: './src/index.js', devtool: 'source-map', output: { path: __dirname + '/lib', filename: outputFile, publicPath: __dirname + '/public' }, module: { loaders: [ { test: /(\.jsx|\.js)$/, loader: 'babel', exclude: /(node_modules|bower_components)/ } ] }, plugins: plugins }; if (env === 'dev') { new WebpackDevServer(webpack(config), { contentBase: './public', hot: true, debug: true }).listen(port, host, function (err, result) { if (err) { console.log(err); } }); console.log('-------------------------'); console.log('Local web server runs at http://' + host + ':' + port); console.log('-------------------------'); } module.exports = config;
var webpack = require('webpack'); var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var env = process.env.WEBPACK_ENV; var WebpackDevServer = require('webpack-dev-server'); var appName = 'app'; var host = '0.0.0.0'; var port = '9000'; var plugins = [], outputFile; if (env === 'build') { plugins.push(new UglifyJsPlugin({ minimize: true })); outputFile = appName + '.min.js'; } else { outputFile = appName + '.js'; } var config = { entry: './src/index.js', devtool: 'source-map', output: { path: __dirname + '/lib', filename: outputFile, publicPath: __dirname + '/public' }, module: { loaders: [ { test: /(\.jsx|\.js)$/, loader: 'babel', exclude: /(node_modules|bower_components)/ } ] }, plugins: plugins }; if (env === 'dev') { new WebpackDevServer(webpack(config), { contentBase: './public', hot: true, debug: true }).listen(port, host, function (err, result) { if (err) { console.log(err); } }); console.log('-------------------------'); console.log('Local web server runs at http://' + host + ':' + port); console.log('-------------------------'); } module.exports = config;
Use self> for selfbot prefix, and >/b> for normal bot prefix
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config/config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('self>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>', 'b>')) extensions = ('cat', 'default', 'eddb', 'osu', 'nsfw', 'repl', 'rpg', 'stats', 'wolfram', 'xkcd') for extension in extensions: try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config/config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('b>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>')) extensions = ('cat', 'default', 'eddb', 'osu', 'nsfw', 'repl', 'rpg', 'stats', 'wolfram', 'xkcd') for extension in extensions: try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
Correct require to point to models/game-info.js.
var GameInfo = require('models/game-info.js'); 'use stricts'; /* * Render th first page */ exports.index = function(req, res){ res.render('index'{ user : req.user || null }); } exports.getGame = function(req, res){ var id = req.params.id Game.findOne({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.createGame = function(req, res){ res.render('game'{ user : req.user || null }); } exports.deleteGame = function(req, res){ var id = req.params.id Game.delete({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.updateGame = function(req, res){ res.render('game'{ user : req.user || null }); } exports.displayGame = function(req, res){ var id = req.params.id Game.findOne({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.showList = function(req, res){ res.render('page'{ user : req.user || null }); }
var GameInfo = require('module'); 'use stricts'; /* * Render th first page */ exports.index = function(req, res){ res.render('index'{ user : req.user || null }); } exports.getGame = function(req, res){ var id = req.params.id Game.findOne({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.createGame = function(req, res){ res.render('game'{ user : req.user || null }); } exports.deleteGame = function(req, res){ var id = req.params.id Game.delete({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.updateGame = function(req, res){ res.render('game'{ user : req.user || null }); } exports.displayGame = function(req, res){ var id = req.params.id Game.findOne({_id:id},function(game,err){ if (err){res.send(err);} else{res.jsonp(game);} }); } exports.showList = function(req, res){ res.render('page'{ user : req.user || null }); }
Return update time for the latest release
import packageJson from 'package-json'; export const getLatestVersion = (req, res) => { packageJson('cncjs') .then(data => { const latest = data['dist-tags'].latest; const time = data.time[latest]; const { name, version, description, homepage } = { ...data.versions[latest] }; res.send({ time, name, version, description, homepage }); }) .catch(err => { res.status(400).send({ err: err }); }); };
import packageJson from 'package-json'; export const getLatestVersion = (req, res) => { packageJson('cncjs', 'latest') .then(json => { const { name, version, description, homepage } = { ...json }; res.send({ name, version, description, homepage }); }) .catch((err) => { res.status(400).send({ err: err }); }); };
Fix license header violations in sal-common-api Change-Id: I58fdef120495514ef94f2e9681790786ba4e0841 Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>
/* * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.md.sal.common.api.data; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; /** * * Failure of asynchronous transaction commit caused by failure * of optimistic locking. * * This exception is raised and returned when transaction commit * failed, because other transaction finished successfully * and modified same data as failed transaction. * * Clients may recover from this error condition by * retrieving current state and submitting new updated * transaction. * */ public class OptimisticLockFailedException extends TransactionCommitFailedException { private static final long serialVersionUID = 1L; public OptimisticLockFailedException(final String message, final Throwable cause) { super(message, cause, RpcResultBuilder.newError(ErrorType.APPLICATION, "resource-denied", message, null, null, cause)); } public OptimisticLockFailedException(final String message) { this(message, null); } }
package org.opendaylight.controller.md.sal.common.api.data; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; /** * * Failure of asynchronous transaction commit caused by failure * of optimistic locking. * * This exception is raised and returned when transaction commit * failed, because other transaction finished successfully * and modified same data as failed transaction. * * Clients may recover from this error condition by * retrieving current state and submitting new updated * transaction. * */ public class OptimisticLockFailedException extends TransactionCommitFailedException { private static final long serialVersionUID = 1L; public OptimisticLockFailedException(final String message, final Throwable cause) { super(message, cause, RpcResultBuilder.newError(ErrorType.APPLICATION, "resource-denied", message, null, null, cause)); } public OptimisticLockFailedException(final String message) { this(message, null); } }
Add missing serial version ID (default). git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1572570 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) 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 org.apache.commons.compress.archivers; /** * Exception thrown by ArchiveStreamFactory if a format is * requested/detected that doesn't support streaming. * @since 1.8 */ public class StreamingNotSupportedException extends ArchiveException { private static final long serialVersionUID = 1L; private final String format; /** * Creates a new StreamingNotSupportedException. * @param format the format that has been requested/detected. */ public StreamingNotSupportedException(String format) { super("The " + format + " doesn't support streaming."); this.format = format; } /** * Returns the format that has been requested/detected. * @return the format that has been requested/detected. */ public String getFormat() { return format; } }
/* * Licensed to the Apache Software Foundation (ASF) 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 org.apache.commons.compress.archivers; /** * Exception thrown by ArchiveStreamFactory if a format is * requested/detected that doesn't support streaming. * @since 1.8 */ public class StreamingNotSupportedException extends ArchiveException { private final String format; /** * Creates a new StreamingNotSupportedException. * @param format the format that has been requested/detected. */ public StreamingNotSupportedException(String format) { super("The " + format + " doesn't support streaming."); this.format = format; } /** * Returns the format that has been requested/detected. * @return the format that has been requested/detected. */ public String getFormat() { return format; } }
Check content._content before using it to prevent errors
""" Embedded tweet plugin for Pelican ================================= This plugin allows you to embed Twitter tweets into your articles. And also provides a link for Twitter username. i.e. @username will be replaced by a link to Twitter username page. @username/status/tweetid will be replaced by a `Embedded-tweet`_ API. .. _Embedded-tweet: https://dev.twitter.com/docs/embedded-tweets """ from pelican import signals import re def embed_tweet(content): if not content._content: return content._content = re.sub( r'(^|[^@\w])@(\w{1,15})\b', '\\1<a href="https://twitter.com/\\2">@\\2</a>', re.sub( r'(^|[^@\w])@(\w{1,15})/status/(\d+)\b', '\\1<blockquote class="twitter-tweet" align="center"><a href="https://twitter.com/\\2/status/\\3">Tweet of \\2/\\3</a></blockquote>', content._content ) ) + '<script src="//platform.twitter.com/widgets.js" charset="utf-8"></script>' def register(): signals.content_object_init.connect(embed_tweet)
""" Embedded tweet plugin for Pelican ================================= This plugin allows you to embed Twitter tweets into your articles. And also provides a link for Twitter username. i.e. @username will be replaced by a link to Twitter username page. @username/status/tweetid will be replaced by a `Embedded-tweet`_ API. .. _Embedded-tweet: https://dev.twitter.com/docs/embedded-tweets """ from pelican import signals import re def embed_tweet(content): content._content = re.sub( r'(^|[^@\w])@(\w{1,15})\b', '\\1<a href="https://twitter.com/\\2">@\\2</a>', re.sub( r'(^|[^@\w])@(\w{1,15})/status/(\d+)\b', '\\1<blockquote class="twitter-tweet" align="center"><a href="https://twitter.com/\\2/status/\\3">Tweet of \\2/\\3</a></blockquote>', content._content ) ) + '<script src="//platform.twitter.com/widgets.js" charset="utf-8"></script>' def register(): signals.content_object_init.connect(embed_tweet)
Fix "Extend Expiration Date" Server Action Server Action had bugs where server.expiration_date would cause an exception if it wasn't set, and was using the old method `group.approvers`. These issues have been fixed, and the plugin is more stable. [DEV-13752]
""" Server Action to extend the expiration date of a Server by 30 days and notify Approvers in the Server's Group. """ import datetime from utilities.logger import ThreadLogger from utilities.mail import send_mail, InvalidConfigurationException logger = ThreadLogger(__name__) def run(job, logger=None): # Extend Server Expiration Date server = job.server_set.first() # If the server doesn't have an expiration date, this Server Action will # quit and _not_ assign it one. if server.expiration_date is None: return "", "This server does not have an expiration date.", "" new_date = server.expiration_date + datetime.timedelta(days=30) server.set_value_for_custom_field("expiration_date", new_date) # Notify Approvers email_body = ( f"{job.owner} has extended {server.hostname}'s expiration date by 30 days." ) email_addrs = [approver.user.email for approver in server.group.get_approvers()] subject = "CloudBolt: Server expiration extended by 30 days." try: send_mail(subject, email_body, None, email_addrs) except InvalidConfigurationException: logger.debug("Cannot connect to email (SMTP) server") return "", "", ""
import datetime from utilities.logger import ThreadLogger from utilities.mail import send_mail from utilities.mail import InvalidConfigurationException """ Server action to extend expiration date on a server by 30 days """ def run(job, logger=None): # Extend Server Expiration Date server = job.server_set.first() new_date = server.expiration_date + datetime.timedelta(days=30) server.set_value_for_custom_field("expiration_date", new_date) # Notify Approver email_body = ( '{} has extended {}\'s expiration date by 30 days.'.format(job.owner, server.hostname) ) emails = [] for approver in server.group.approvers.all(): emails.append(approver.user.email) subject = 'CloudBolt: Server expiration extended by 30 days.' try: send_mail(subject, email_body, None, emails) except InvalidConfigurationException: logger.debug('Cannot connect to email (SMTP) server') return "", "", ""
Add time to imported modules.
import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) day = 1000 if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) status = shutdown(camera) # image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
import capture from picamera import PiCamera def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) day = 1000 if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) status = shutdown(camera) # image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
Add sort by default for homeroom select
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import SimpleFilterSelect, {ALL} from './SimpleFilterSelect'; // For selecting a homeroom by teacher name export default function SelectHomeroomByEducator({homeroomId, onChange, homerooms, disableSort, style = undefined}) { const homeroomOptions = [{value: ALL, label: 'All'}].concat(_.compact(homerooms).map(homeroom => { return { value: homeroom.id.toString(), label: homeroom.educator.full_name }; })); const sortedHomeroomOptions = disableSort ? homeroomOptions : _.sortBy(homeroomOptions, 'label'); return ( <SimpleFilterSelect style={style} placeholder="Homeroom..." value={homeroomId.toString()} onChange={onChange} options={sortedHomeroomOptions} /> ); } SelectHomeroomByEducator.propTypes = { homeroomId: PropTypes.any.isRequired, // could be 'all' onChange: PropTypes.func.isRequired, homerooms: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, educator: PropTypes.shape({ full_name: PropTypes.string, // or null email: PropTypes.string.isRequired }) })).isRequired, disableSort: PropTypes.bool, style: PropTypes.object };
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import SimpleFilterSelect, {ALL} from './SimpleFilterSelect'; // For selecting a homeroom by teacher name export default function SelectHomeroomByEducator({homeroomId, onChange, homerooms, style = undefined}) { const homeroomOptions = [{value: ALL, label: 'All'}].concat(_.compact(homerooms).map(homeroom => { return { value: homeroom.id.toString(), label: homeroom.educator.full_name }; })); return ( <SimpleFilterSelect style={style} placeholder="Homeroom..." value={homeroomId.toString()} onChange={onChange} options={homeroomOptions} /> ); } SelectHomeroomByEducator.propTypes = { homeroomId: PropTypes.any.isRequired, // could be 'all' onChange: PropTypes.func.isRequired, homerooms: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, educator: PropTypes.shape({ full_name: PropTypes.string, // or null email: PropTypes.string.isRequired }) })).isRequired, style: PropTypes.object };
Delete page warning working with child page count
<p>Are you sure you want to delete this page? This cannot be recovered.</p> <? $msg = ''; if ($count = $page->mptt->count() > 0): $titlelist = ''; foreach ($page->mptt->descendants() as $pi): $titlelist .= "<li>" . $pi->page->title . "</li>"; endforeach; $titlelist = preg_replace("/\, $/", "", $titlelist); $msg = "<p><strong>Warning:</strong><br />Deleting this page will make it's " . $count . " child "; $msg .= ($count !== 1) ? 'page' : 'pages'; $msg .= " inaccessible:</p><div id=\"sledge-page-delete-children\"><ul>" . $titlelist . "</ul></div>"; endif; echo $msg; ?> <p>Click 'Okay' to delete, or 'Cancel' to keep the page.</p>
<p>Are you sure you want to delete this page? This cannot be recovered.</p> <? $msg = ''; if ($count = $page->mptt->count() > 0): $titlelist = ''; foreach ($page->mptt->descendants() as $pi): $titlelist .= "<li>" . $pi->title . "</li>"; endforeach; $titlelist = preg_replace("/\, $/", "", $titlelist); $msg = "<p><strong>Warning:</strong><br />Deleting this page will make it's " . $count . " child "; $msg .= ($count !== 1) ? 'page' : 'pages'; $msg .= " inaccessible:</p><div id=\"sledge-page-delete-children\"><ul>" . $titlelist . "</ul></div>"; endif; echo $msg; ?> <p>Click 'Okay' to delete, or 'Cancel' to keep the page.</p>
Put default headers as constant and make it immutable. With additional cosmetic fixes.
import functools DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])): def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS): """ A middleware that allow CORS calls, by adding the headers Access-Control-Allow-Origin and Access-Control-Allow-Headers. This middlware accepts two optional parameters `allow_origin` and `allow_headers` for customization of the headers values. By default will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]` respectively. """ @functools.wraps(func) def wrapper(request, *args, **kwargs): response = func(request, *args, **kwargs) if not response.headers: response.headers = {} response.headers['Access-Control-Allow-Origin'] = allow_origin response.headers['Access-Control-Allow-Headers'] = ', '.join(allow_headers) return response return wrapper
import functools def wrap_cors( func=None, *, allow_origin='*', allow_headers=set(["Origin", "X-Requested-With", "Content-Type", "Accept"])): """ A middleware that allow CORS calls, by adding the headers Access-Control-Allow-Origin and Access-Control-Allow-Headers. This middlware accepts two optional parameters `allow_origin` and `allow_headers` for customization of the headers values. By default will be `*` and a set of `[Origin, X-Requested-With, Content-Type, Accept]` respectively. """ @functools.wraps(func) def wrapper(request, *args, **kwargs): response = func(request, *args, **kwargs) if not response.headers: response.headers = {} response.headers['Access-Control-Allow-Origin'] = allow_origin response.headers['Access-Control-Allow-Headers'] = ', '.join(allow_headers) return response return wrapper
Test Driven Development Unit Test code CONTD https://app.asana.com/0/334403035277160/335518406456410
<?php /** * PSR-4 Compliant Autoloader * * This will dynamically load classes by resolving the prefix and class name. This is the method that * frameworks such as Laravel and Composer automatically resolve class names and load them. To use it, * simply set the configurable parameters inside the closure. This example is taken from PHP-FIG, * referenced below. * * @param string $class fully qualified class name to load * @see http://www.php-fig.org/psr/psr-4/examples/ PSR-4 Example Autoloader **/ spl_autoload_register(function($class) { /** * CONFIGURABLE PARAMETERS * prefix: the prefix for all the classes (i.e., the namespace) * baseDir: the base directory for all classes (default = current directory) **/ $prefix = "PetRescueAbq\\Http\\Petfoster"; $baseDir = __DIR__; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $className = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $baseDir . str_replace("\\", "/", $className) . ".php"; // if the file exists, require it if(file_exists($file)) { require_once($file); } });
<?php /** * PSR-4 Compliant Autoloader * * This will dynamically load classes by resolving the prefix and class name. This is the method that frameworks * such as Laravel and Composer automatically resolve class names and load them. To use it, simply set the * configurable parameters inside the closure. This example is taken from PHP-FIG, referenced below. * * @param string $class fully qualified class name to load * @see http://www.php-fig.org/psr/psr-4/examples/ PSR-4 Example Autoloader **/ spl_autoload_register(function($class) { /** * CONFIGURABLE PARAMETERS * prefix: the prefix for all the classes (i.e., the namespace) * baseDir: the base directory for all classes (default = current directory) **/ $prefix = "PetRescueAbq\\Http\\Petfoster"; $baseDir = __DIR__; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $className = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $baseDir . str_replace("\\", "/", $className) . ".php"; // if the file exists, require it if(file_exists($file)) { require_once($file); } });
Add the corresponding interface method
<?php namespace Modules\Setting\Repositories; use Modules\Core\Repositories\BaseRepository; interface SettingRepository extends BaseRepository { /** * Create or update the settings * @param $settings * @return mixed */ public function createOrUpdate($settings); /** * Find a setting by its name * @param $settingName * @return mixed */ public function findByName($settingName); /** * Return all modules that have settings * with its settings * @param array|string $modules * @return array */ public function moduleSettings($modules); /** * Return the saved module settings * @param $module * @return mixed */ public function savedModuleSettings($module); /** * Find settings by module name * @param string $module * @return mixed */ public function findByModule($module); }
<?php namespace Modules\Setting\Repositories; use Modules\Core\Repositories\BaseRepository; interface SettingRepository extends BaseRepository { /** * Create or update the settings * @param $settings * @return mixed */ public function createOrUpdate($settings); /** * Find a setting by its name * @param $settingName * @return mixed */ public function findByName($settingName); /** * Return all modules that have settings * with its settings * @param array|string $modules * @return array */ public function moduleSettings($modules); /** * Return the saved module settings * @param $module * @return mixed */ public function savedModuleSettings($module); }
Remove redundant "docker" string in the command The base DockerCommand class adds "docker" to the start for all command. DockerBuildCommand also adds a superfluous "docker" creating the command "docker docker build", which naturally fails.
package com.stacktoheap.go.docker.Commands.BuildCommands; import com.stacktoheap.go.docker.Commands.DockerCommand; import com.stacktoheap.go.docker.Config; import com.stacktoheap.go.docker.Context; import org.apache.commons.io.FilenameUtils; public class DockerBuildCommand extends DockerCommand { public DockerBuildCommand(Context taskContext, Config taskConfig) { super(taskContext, taskConfig); } @Override public void buildCommand(Context taskContext, Config taskConfig) { command.add("build"); command.add("-t"); command.add(getTemporaryImageTag(taskContext)); String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile); command.add(dockerFilePath); } @Override protected boolean shouldRun(Context taskContext, Config taskConfig) { return taskConfig.isDockerBuild; } }
package com.stacktoheap.go.docker.Commands.BuildCommands; import com.stacktoheap.go.docker.Commands.DockerCommand; import com.stacktoheap.go.docker.Config; import com.stacktoheap.go.docker.Context; import org.apache.commons.io.FilenameUtils; public class DockerBuildCommand extends DockerCommand { public DockerBuildCommand(Context taskContext, Config taskConfig) { super(taskContext, taskConfig); } @Override public void buildCommand(Context taskContext, Config taskConfig) { command.add("docker"); command.add("build"); command.add("-t"); command.add(getTemporaryImageTag(taskContext)); String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile); command.add(dockerFilePath); } @Override protected boolean shouldRun(Context taskContext, Config taskConfig) { return taskConfig.isDockerBuild; } }
Sort runs by text score Search results for runs are sorted by text score.
from flask import Blueprint, request, redirect, render_template, url_for from flask.views import MethodView from recipyGui import recipyGui, mongo from forms import SearchForm runs = Blueprint('runs', __name__, template_folder='templates') @recipyGui.route('/') def index(): form = SearchForm() query = request.args.get('query', '') if not query: # Return all runs, ordered by date (oldest run first) runs = [r for r in mongo.db.recipies.find({}).sort('date', -1)] else: # Search runs using the query string q = { '$text': { '$search': query} } score = { 'score': { '$meta': 'textScore' } } score_sort = [('score', {'$meta': 'textScore'})] runs = [r for r in mongo.db.recipies.find(q, score).sort(score_sort)] print 'runs:', runs print 'query:', query return render_template('runs/list.html', runs=runs, query=query, form=form) #class ListView(MethodView): # def get(self): # runs = Run.objects.all() # print runs # return render_template('runs/list.html', runs=runs) # Register urls #runs.add_url_rule('/', view_func=ListView.as_view('list'))
from flask import Blueprint, request, redirect, render_template, url_for from flask.views import MethodView from recipyGui import recipyGui, mongo from forms import SearchForm runs = Blueprint('runs', __name__, template_folder='templates') @recipyGui.route('/') def index(): form = SearchForm() query = request.args.get('query', '') if not query: # Return all runs, ordered by date (oldest run first) runs = [r for r in mongo.db.recipies.find({}).sort('date', -1)] else: # Search runs using the query string q = { '$text': { '$search': query} } runs = [r for r in mongo.db.recipies.find(q)] print 'runs:', runs print 'query:', query return render_template('runs/list.html', runs=runs, query=query, form=form) #class ListView(MethodView): # def get(self): # runs = Run.objects.all() # print runs # return render_template('runs/list.html', runs=runs) # Register urls #runs.add_url_rule('/', view_func=ListView.as_view('list'))
Add back security by default
var fs = require('fs'); var path = require('path'), nconf = require('nconf'), ipc = require('ipc'); var DEFAULT_ROOT_PATH = ipc.sendSync('appdir'); var DEFAULT_CONFIG = { "root_path": DEFAULT_ROOT_PATH, "repository": { "file": { "path": path.join(DEFAULT_ROOT_PATH, "public", "data.json") }, "security": { "iv_size": 16, "cipher": "aes256", "rounds_factor": 10, "enabled": true }, "use": "file" } }; nconf.argv() .env() .file(process.env.CONFIG_FILE || path.join(DEFAULT_ROOT_PATH, "config.ini")) .defaults(DEFAULT_CONFIG); module.exports = nconf;
var fs = require('fs'); var path = require('path'), nconf = require('nconf'), ipc = require('ipc'); var DEFAULT_ROOT_PATH = ipc.sendSync('appdir'); var DEFAULT_CONFIG = { "root_path": DEFAULT_ROOT_PATH, "repository": { "file": { "path": path.join(DEFAULT_ROOT_PATH, "public", "data.json") }, "security": { "iv_size": 16, "cipher": "aes256", "rounds_factor": 10, "enabled": false }, "use": "file" } }; nconf.argv() .env() .file(process.env.CONFIG_FILE || path.join(DEFAULT_ROOT_PATH, "config.ini")) .defaults(DEFAULT_CONFIG); module.exports = nconf;
Change port to port 80
// require('dotenv').config(); const bodyParser = require('body-parser'); const metadata = require('../package.json'); const compression = require('compression'); const express = require('express'); const path = require('path'); const port = 80; // const secret = process.env.SESSION_SECRET; // const redisClient = redis.createClient(); const app = express(); app.use(bodyParser.json({limit: '40mb'})); app.use(compression()); // gzip compress all responses const routes = ['/', '/contact', '/portfolio', '/skills', '/', '/hackerwords', '/goolp', '/immerse', ]; for (const route of routes) { app.get(route, (req, res) => { res.sendFile(path.join(__dirname, '/../client/index.html')); }); } app.use(express.static(path.join(__dirname, '../client'))); // wildcard route app.get('*', function(req, res) { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`); });
// require('dotenv').config(); const bodyParser = require('body-parser'); const metadata = require('../package.json'); const compression = require('compression'); const express = require('express'); const path = require('path'); const port = 3000; // const secret = process.env.SESSION_SECRET; // const redisClient = redis.createClient(); const app = express(); app.use(bodyParser.json({limit: '40mb'})); app.use(compression()); // gzip compress all responses const routes = ['/', '/contact', '/portfolio', '/skills', '/', '/hackerwords', '/goolp', '/immerse', ]; for (const route of routes) { app.get(route, (req, res) => { res.sendFile(path.join(__dirname, '/../client/index.html')); }); } app.use(express.static(path.join(__dirname, '../client'))); // wildcard route app.get('*', function(req, res) { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`); });
Remove variable declaration for service and just return the object.
Application.Services.factory('tags', ["mcapi", function tags(mcapi) { return { tags: [], createTag: function (tag, item_id) { mcapi('/tags/item/%', item_id) .success(function (tag) { return tag; }).post(tag); }, removeTag: function (tag_id, item_id) { mcapi('/tags/%/item/%', tag_id, item_id) .success(function (tag) { return tag; }).delete(); } }; }]);
Application.Services.factory('tags', ["mcapi", function tags(mcapi) { var service = { tags: [], createTag: function (tag, item_id) { mcapi('/tags/item/%', item_id) .success(function (tag) { return tag; }).post(tag); }, removeTag: function (tag_id, item_id) { mcapi('/tags/%/item/%', tag_id, item_id) .success(function (tag) { return tag; }).delete(); } }; return service; }]);
Rewrite the test script to hint all glyphs Which reveals that no MM-compatible hinting is really done :(
from psautohint import autohint from psautohint import psautohint baseDir = "tests/data/source-code-pro" masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") glyphList = None fonts = [] for master in masters: print("Hinting %s" % master) path = "%s/%s/font.otf" % (baseDir, master) font = autohint.openOpenTypeFile(path, "font.otf", None) names = font.getGlyphList() info = font.getFontInfo(font.getPSName(), path, False, False, [], []) info = info.getFontInfo() if glyphList is None: glyphList = names else: assert glyphList == names glyphs = [] for name in names: glyph = font.convertToBez(name, False) glyphs.append(glyph[0]) fonts.append(psautohint.autohint(info, glyphs, False, False, False)) glyphs = [] for i in range(len(glyphList)): glyphs.append([f[i] for f in fonts]) print("MM Hinting") glyphs = psautohint.autohintmm(info, glyphs, True)
from psautohint import autohint from psautohint import psautohint d = "tests/data/source-code-pro" mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") gg = [] ii = None for m in mm: f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None) g = f.convertToBez("A", False) gg.append(g[0]) if ii is None: ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], []) ii = ii.getFontInfo() gg = psautohint.autohint(ii, gg, True) gg = psautohint.autohintmm(ii, [gg], True)
Enable smartypants mode on marked
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; }; renderer.codespan = function(code) { return katex.renderToString(code, katexOpts); }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setUseWrapMode(true); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); event.preventDefault(); return false; } };
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; }; renderer.codespan = function(code) { return katex.renderToString(code, katexOpts); }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setUseWrapMode(true); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); event.preventDefault(); return false; } };
ebiten: Add an explicit type to CursorModeType consts for pkg.go.dev
// Copyright 2019 The Ebiten Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ebiten import "github.com/hajimehoshi/ebiten/v2/internal/driver" // CursorModeType represents // a render and coordinate mode of a mouse cursor. type CursorModeType int const ( CursorModeVisible CursorModeType = CursorModeType(driver.CursorModeVisible) CursorModeHidden CursorModeType = CursorModeType(driver.CursorModeHidden) CursorModeCaptured CursorModeType = CursorModeType(driver.CursorModeCaptured) )
// Copyright 2019 The Ebiten Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ebiten import "github.com/hajimehoshi/ebiten/v2/internal/driver" // A CursorModeType represents // a render and coordinate mode of a mouse cursor. type CursorModeType int // Cursor Modes const ( CursorModeVisible = CursorModeType(driver.CursorModeVisible) CursorModeHidden = CursorModeType(driver.CursorModeHidden) CursorModeCaptured = CursorModeType(driver.CursorModeCaptured) )
Include full table diff string in the exception message Otherwise it doesn't get rendered in behat reports etc unless in verbose mode, which turns out to be not that useful.
<?php /** * @author Andrew Coulton <andrew@ingenerator.com> * @licence BSD-3-Clause */ namespace Ingenerator\BehatTableAssert; /** * @package Ingenerator\BehatTableAssert */ class TableAssertionFailureException extends \RuntimeException { /** * @var array */ protected $diff; /** * @var string */ protected $diff_string; /** * @param string $message * @param array $diff * @param string $diff_string */ public function __construct($message, array $diff, $diff_string) { $this->diff = $diff; $this->diff_string = $diff_string; parent::__construct($message."\n\n".$this->diff_string); } /** * @return array */ public function getDiff() { return $this->diff; } /** * @return string */ public function getDiffString() { return $this->diff_string; } }
<?php /** * @author Andrew Coulton <andrew@ingenerator.com> * @licence BSD-3-Clause */ namespace Ingenerator\BehatTableAssert; /** * @package Ingenerator\BehatTableAssert */ class TableAssertionFailureException extends \RuntimeException { /** * @var array */ protected $diff; /** * @var string */ protected $diff_string; /** * @param string $message * @param array $diff * @param string $diff_string */ public function __construct($message, array $diff, $diff_string) { $this->diff = $diff; $this->diff_string = $diff_string; parent::__construct($message); } /** * @return string */ public function __toString() { return $this->getMessage()."\n\n".$this->diff_string; } /** * @return array */ public function getDiff() { return $this->diff; } /** * @return string */ public function getDiffString() { return $this->diff_string; } }
Change engine type of users table because sucks hosting
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); $table->engine = 'MyISAM'; }); DB::statement('ALTER TABLE users ADD FULLTEXT search(name, email)'); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropIndex('search'); }); Schema::drop('users'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); DB::statement('ALTER TABLE users ADD FULLTEXT search(name, email)'); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropIndex('search'); }); Schema::drop('users'); } }
Add title to earnings' index view
@extends('layout') @section('title', __('general.earnings')) @section('body') <div class="wrapper my-3"> <h2>{{ __('general.earnings') }}</h2> <div class="box mt-3"> @if (count($earnings)) @foreach ($earnings as $earning) <div class="box__section row"> <div class="row__column"> <div>{{ $earning->description }}</div> <div style="margin-top: 10px; font-size: 14px;">{{ $earning->formatted_happened_on }}</div> </div> <div class="row__column text-right" style="color: green;">&euro; {{ $earning->formatted_amount }}</div> </div> @endforeach @else <div class="box__section text-center">You don't have any earnings</div> @endif </div> </div> @endsection
@extends('layout') @section('body') <div class="wrapper my-3"> <h2>{{ __('general.earnings') }}</h2> <div class="box mt-3"> @if (count($earnings)) @foreach ($earnings as $earning) <div class="box__section row"> <div class="row__column"> <div>{{ $earning->description }}</div> <div style="margin-top: 10px; font-size: 14px;">{{ $earning->formatted_happened_on }}</div> </div> <div class="row__column text-right" style="color: green;">&euro; {{ $earning->formatted_amount }}</div> </div> @endforeach @else <div class="box__section text-center">You don't have any earnings</div> @endif </div> </div> @endsection
Allow more complex targetting in script test
""" Usage: transport_tester.py [--port=<port>] [<target_ip_optional_port>] Options: -p --port=<port> Number to use [default: 8885]. """ from gevent import monkey monkey.patch_all() # noqa import time from docopt import docopt from ethereum import slogging from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": slogging.configure(':DEBUG') options = docopt(__doc__) port = int(options['--port']) target = options['<target_ip_optional_port>'] if target and ':' in target: target, target_port = target.split(':') target_port = int(target_port) else: target_port = port with socket_factory('0.0.0.0', port) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if target: t.send(None, (target, target_port), b'hello')
from gevent import monkey monkey.patch_all() # noqa import sys import time from ethereum import slogging from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": slogging.configure(':DEBUG') with socket_factory('0.0.0.0', 8885) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if len(sys.argv) > 1: t.send(None, (sys.argv[1], 8885), b'hello')
Set a very large timeout for AppVeyor slowness
'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ simplemocha: { options: { timeout: 30000 }, app: { src: ['test/test.js'] } }, jshint: { options: { jshintrc: '.jshintrc' }, lib: ['lib/**/*.js', 'tasks/**/*.js', 'Gruntfile.js'] }, release: {}, "steal-build": { "test-webworker": { options: { system: { configMain: "@empty", main: "worker", baseUrl: __dirname + "/test/browser/webworker" }, buildOptions: { bundleSteal: true, quiet: true } } } }, testee: { tests: { options: { browsers: [ "firefox" ] }, src: [ "test/browser/test.html" ] } } }); grunt.registerTask('default', 'test'); grunt.registerTask('test', [ 'jshint', 'simplemocha' ]); grunt.registerTask("test:browser", [ "steal-build", "testee" ]); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('testee'); grunt.loadTasks("tasks"); };
'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ simplemocha: { app: { src: ['test/test.js'] } }, jshint: { options: { jshintrc: '.jshintrc' }, lib: ['lib/**/*.js', 'tasks/**/*.js', 'Gruntfile.js'] }, release: {}, "steal-build": { "test-webworker": { options: { system: { configMain: "@empty", main: "worker", baseUrl: __dirname + "/test/browser/webworker" }, buildOptions: { bundleSteal: true, quiet: true } } } }, testee: { tests: { options: { browsers: [ "firefox" ] }, src: [ "test/browser/test.html" ] } } }); grunt.registerTask('default', 'test'); grunt.registerTask('test', [ 'jshint', 'simplemocha' ]); grunt.registerTask("test:browser", [ "steal-build", "testee" ]); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('testee'); grunt.loadTasks("tasks"); };
Fix crash in Direct Messages column settings Fixes #892
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import SettingText from '../../../components/setting_text'; const messages = defineMessages({ filter_regex: { id: 'home.column_settings.filter_regex', defaultMessage: 'Filter out by regular expressions' }, settings: { id: 'home.settings', defaultMessage: 'Column settings' }, }); @injectIntl export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { settings, onChange, intl } = this.props; return ( <div> <span className='column-settings__section'><FormattedMessage id='home.column_settings.advanced' defaultMessage='Advanced' /></span> <div className='column-settings__row'> <SettingText settings={settings} settingPath={['regex', 'body']} onChange={onChange} label={intl.formatMessage(messages.filter_regex)} /> </div> </div> ); } }
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import SettingText from '../../../components/setting_text'; const messages = defineMessages({ filter_regex: { id: 'home.column_settings.filter_regex', defaultMessage: 'Filter out by regular expressions' }, settings: { id: 'home.settings', defaultMessage: 'Column settings' }, }); @injectIntl export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { settings, onChange, intl } = this.props; return ( <div> <span className='column-settings__section'><FormattedMessage id='home.column_settings.advanced' defaultMessage='Advanced' /></span> <div className='column-settings__row'> <SettingText settings={settings} settingKey={['regex', 'body']} onChange={onChange} label={intl.formatMessage(messages.filter_regex)} /> </div> </div> ); } }
Update version string to 2.6.0-rc.1
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./src/options'); exports.version = '2.6.0-rc.1'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ events: [{name: 'hold', time: 400}], endHold: 'onLeave' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./src/resolution'); require('./src/fonts');
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./src/options'); exports.version = '2.6.0-pre.20.1'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ events: [{name: 'hold', time: 400}], endHold: 'onLeave' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./src/resolution'); require('./src/fonts');
Add filter on getCaptures to only return valid captures
import EventEmitter from 'eventemitter2' import store from '../store/store' import { actions } from '../store/actions' const events = new EventEmitter() store.subscribe(handleEvent) const authenticated = (state) => state.globals.authenticated const hasDocumentCaptured = (state) => state.globals.hasDocumentCaptured const hasFaceCaptured = (state) => state.globals.hasFaceCaptured function handleEvent () { const state = store.getState() const { documentCaptures, faceCaptures } = state const data = { documentCaptures: documentCaptures[0] || null, faceCaptures: faceCaptures[0] || null } if (authenticated(state)) { events.emit('ready') } if (hasDocumentCaptured(state)) { events.emit('documentCapture', data) } if (hasFaceCaptured(state)) { events.emit('faceCapture', data) } if (hasDocumentCaptured(state) && hasFaceCaptured(state)) { events.emit('complete', data) } } events.getCaptures = () => { const state = store.getState() const { documentCaptures, faceCaptures } = state const filterValid = (capture) => capture.isValid const [ documentCapture ] = documentCaptures.filter(filterValid) const [ faceCapture ] = faceCaptures.filter(filterValid) const data = { documentCapture: (documentCapture || null), faceCapture: (faceCapture || null) } return data } export default events
import EventEmitter from 'eventemitter2' import store from '../store/store' import { actions } from '../store/actions' const events = new EventEmitter() store.subscribe(handleEvent) const authenticated = (state) => state.globals.authenticated const hasDocumentCaptured = (state) => state.globals.hasDocumentCaptured const hasFaceCaptured = (state) => state.globals.hasFaceCaptured function handleEvent () { const state = store.getState() const { documentCaptures, faceCaptures } = state const data = { documentCaptures: documentCaptures[0] || null, faceCaptures: faceCaptures[0] || null } if (authenticated(state)) { events.emit('ready') } if (hasDocumentCaptured(state)) { events.emit('documentCapture', data) } if (hasFaceCaptured(state)) { events.emit('faceCapture', data) } if (hasDocumentCaptured(state) && hasFaceCaptured(state)) { events.emit('complete', data) } } events.getCaptures = () => { const state = store.getState() const { documentCaptures, faceCaptures } = state const data = { documentCapture: documentCaptures[0] || null, faceCapture: faceCaptures[0] || null } return data } export default events
Fix problem with creating tables
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from pytoon.connection import BrickConnection app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/app.db' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = SQLAlchemy(app) print(db.get_app()) print('starting database') print('database created') @app.route('/') def index(): timestamps = Electricity.query.all() data = '<table><tbody>' for t in timestamps: data += '<tr><td>{}</td></tr>'.format(t.timestamp) data += '</tbody></table>' return data class PyToon(object): def __init__(self, database): host = "192.168.178.35" port = 4223 BrickConnection(host, port, database) class Electricity(db.Model): timestamp = db.Column(db.DateTime, primary_key=True) def __init__(self, timestamp): self.timestamp = timestamp def __repr__(self): return '<Timestamp {}>'.format(self.timestamp) db.create_all() if __name__ == '__main__': pt = PyToon(db) app.run(debug=True, use_reloader=False)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from pytoon.connection import BrickConnection app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = SQLAlchemy(app) print(db.get_app()) print('starting database') db.create_all() print('database created') @app.route('/') def index(): timestamps = Electricity.query.all() data = '<table><tbody>' for t in timestamps: data += '<tr><td>{}</td></tr>'.format(t.timestamp) data += '</tbody></table>' return data class PyToon(object): def __init__(self, database): host = "192.168.178.35" port = 4223 BrickConnection(host, port, database) class Electricity(db.Model): timestamp = db.Column(db.DateTime, primary_key=True) def __repr__(self): return '<Timestamp {}>'.format(self.timestamp) if __name__ == '__main__': pt = PyToon(db) app.run(debug=True, use_reloader=False)