text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix sonar warning: Bad practice - Non-serializable value stored into instance field of a serializable class
/* * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt 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. BloatIt 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 BloatIt. If not, see <http://www.gnu.org/licenses/>. */ package com.bloatit.web.exceptions; import com.bloatit.web.utils.url.IndexPageUrl; import com.bloatit.web.utils.url.Url; // No serialization possible because IndexPageUrl is not serialisable. @SuppressWarnings("serial") public class RedirectException extends Exception { private final Url url; public RedirectException(final Url url) { if (url == null) { this.url = new IndexPageUrl(); } else { this.url = url; } } public Url getUrl() { return url; } }
/* * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt 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. BloatIt 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 BloatIt. If not, see <http://www.gnu.org/licenses/>. */ package com.bloatit.web.exceptions; import com.bloatit.web.utils.url.IndexPageUrl; import com.bloatit.web.utils.url.Url; public class RedirectException extends Exception { private static final long serialVersionUID = -8000625161101556546L; private final Url url; public RedirectException(final Url url) { if (url == null) { this.url = new IndexPageUrl(); } else { this.url = url; } } public Url getUrl() { return url; } }
Set the tiddlywebwiki binary limit to 1MB.
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', }
Use a default base_url when not specified in config file Also report the base_url at startup
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller if ( ! global.settings.base_url ) global.settings.base_url = '/api/*'; var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port + " with base_url " + global.settings.base_url); });
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port); });
Use a free name on PyPi
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='w', packages=['wallace'], version="0.11.0", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], } ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
"""Install Wallace as a command line utility.""" from setuptools import setup setup_args = dict( name='wallace-platform', packages=['wallace'], version="0.11.0", description='Wallace, a platform for experimental cultural evolution', url='http://github.com/berkeley-cocosci/Wallace', author='Berkeley CoCoSci', author_email='wallace@cocosci.berkeley.edu', license='MIT', keywords=['science', 'cultural evolution', 'experiments', 'psychology'], classifiers=[], zip_safe=False, entry_points={ 'console_scripts': [ 'wallace = wallace.command_line:wallace', ], } ) # Read in requirements.txt for dependencies. setup_args['install_requires'] = install_requires = [] setup_args['dependency_links'] = dependency_links = [] with open('requirements.txt') as f: for line in f.readlines(): req = line.strip() if not req or req.startswith('#'): continue if req.startswith('-e '): dependency_links.append(req[3:]) else: install_requires.append(req) setup(**setup_args)
Use appliesToPhase to prevent running
/* @flow */ import path from 'path' import File from '../File' import Rule from '../Rule' import State from '../State' import type { Command, OptionsInterface, Phase } from '../types' export default class CreateOutputTree extends Rule { static phases: Set<Phase> = new Set(['initialize']) static alwaysEvaluate: boolean = true static description: string = 'Create directory tree for aux files when `outputDirectory` is set.' static async appliesToPhase (state: State, command: Command, phase: Phase, options: OptionsInterface): Promise<boolean> { return await Rule.appliesToPhase(state, command, phase, options) && !!options.outputDirectory } async run () { const directories = await this.globPath('**/*', { types: 'directories', ignorePattern: `${this.options.outputDirectory || '.'}/**` }) directories.unshift('.') await Promise.all(directories.map(directory => File.ensureDir(path.resolve(this.rootPath, this.options.outputDirectory || '.', directory)))) return true } }
/* @flow */ import path from 'path' import File from '../File' import Rule from '../Rule' import type { Phase } from '../types' export default class CreateOutputTree extends Rule { static phases: Set<Phase> = new Set(['initialize']) static alwaysEvaluate: boolean = true static description: string = 'Create directory tree for aux files when `outputDirectory` is set.' async run () { if (this.options.outputDirectory) { const directories = await this.globPath('**/*', { types: 'directories', ignorePattern: `${this.options.outputDirectory}/**` }) directories.unshift('.') await Promise.all(directories.map(directory => File.ensureDir(path.resolve(this.rootPath, this.options.outputDirectory || '.', directory)))) } return true } }
Remove force to production ES
import _ from 'underscore' import search from 'api/lib/elasticsearch.coffee' import { matchAll } from 'api/apps/search/queries' const { NODE_ENV } = process.env // GET /api/search export const index = (req, res, next) => { const env = NODE_ENV === 'production' ? 'production' : 'staging' let index = '' if (req.query.type) { index = _.map(req.query.type.split(','), term => { return `${term}_${env}` }).join(',') } search.client.search({ index, body: { indices_boost: { artists_production: 4, tags_production: 3, partners_production: 2 }, query: matchAll(req.query.term) }}, (error, response) => { if (error) { return console.log(`nothing matched for: ${req.query.term}`) } return res.send(response.hits) } ) }
import _ from 'underscore' import search from 'api/lib/elasticsearch.coffee' import { matchAll } from 'api/apps/search/queries' const { NODE_ENV } = process.env // GET /api/search export const index = (req, res, next) => { const env = NODE_ENV === 'production' ? 'production' : 'production' let index = '' if (req.query.type) { index = _.map(req.query.type.split(','), term => { return `${term}_${env}` }).join(',') } search.client.search({ index, body: { indices_boost: { artists_production: 4, tags_production: 3, partners_production: 2 }, query: matchAll(req.query.term) }}, (error, response) => { if (error) { return console.log(`nothing matched for: ${req.query.term}`) } return res.send(response.hits) } ) }
Fix paths now that master is running with new structure
var config = require('../src/config/config') var client = require('mongodb').MongoClient var fs = require('fs-extra') client.connect(config.database.host+'vegodev', function(err, db){ if (err) throw err //Drop vegodev database if it exists db.dropDatabase(function(err, result) { var adminDb = db.admin() //Get a fresh copy adminDb.command({ copydb: 1, fromdb: 'vegosvar', todb: 'vegodev' }, function(err, result) { if (err) throw err if(result.ok) { console.log('Database copied successfully') } //Copy uploads folder var source = '/var/www/beta.vegosvar.se/src/uploads' var destination = '/var/www/dev.vegosvar.se/src/uploads' //assume this directory has a lot of files and folders fs.emptyDir(destination, function (err) { if (err) throw err fs.copy(source, destination, function (err) { if (err) throw err console.log('Uploads folder copied successfully') db.close() }) }) }) }) })
var config = require('../src/config/config') var client = require('mongodb').MongoClient var fs = require('fs-extra') client.connect(config.database.host+'vegodev', function(err, db){ if (err) throw err //Drop vegodev database if it exists db.dropDatabase(function(err, result) { var adminDb = db.admin() //Get a fresh copy adminDb.command({ copydb: 1, fromdb: 'vegosvar', todb: 'vegodev' }, function(err, result) { if (err) throw err if(result.ok) { console.log('Database copied successfully') } //Copy uploads folder var source = '/var/www/beta.vegosvar.se/uploads' var destination = '/var/www/dev.vegosvar.se/src/uploads' //assume this directory has a lot of files and folders fs.emptyDir(destination, function (err) { if (err) throw err fs.copy(source, destination, function (err) { if (err) throw err console.log('Uploads folder copied successfully') db.close() }) }) }) }) })
Fix correct capitalisation of interface
<?php namespace Phaza\NorwegianAddressData\Parser; use Closure; use Phaza\NorwegianAddressData\Objects\Address; class SOSIParser implements SOSIParserInterface { /** * @var Closure */ private $callback; /** * @var resource */ private $handle; public function __construct( Closure $callback ) { $this->callback = $callback; } public function parse( $handle ) { $this->handle = $handle; stream_filter_append( $this->handle, 'convert.iconv.ISO-8859-15/UTF-8', STREAM_FILTER_READ ); $callback = $this->callback; while( ( $line = $this->seekTo( '.PUNKT' ) ) !== false ) { $buffer = [$line]; $this->seekTo( '..NØ', $buffer ); $buffer[] = fgets( $this->handle ); // coordinates $adr = Address::makeFromBuffer( $buffer ); $callback( $adr ); } } protected function seekTo( $string, array &$buffer = null ) { do { $line = fgets( $this->handle ); if($buffer) { $buffer[] = trim($line); } } while( $line !== false && strpos( $line, $string ) === false ); return $line ? trim($line) : false; } }
<?php namespace Phaza\NorwegianAddressData\Parser; use Closure; use Phaza\NorwegianAddressData\Objects\Address; class SOSIParser implements SosiParserInterface { /** * @var Closure */ private $callback; /** * @var resource */ private $handle; public function __construct( Closure $callback ) { $this->callback = $callback; } public function parse( $handle ) { $this->handle = $handle; stream_filter_append( $this->handle, 'convert.iconv.ISO-8859-15/UTF-8', STREAM_FILTER_READ ); $callback = $this->callback; while( ( $line = $this->seekTo( '.PUNKT' ) ) !== false ) { $buffer = [$line]; $this->seekTo( '..NØ', $buffer ); $buffer[] = fgets( $this->handle ); // coordinates $adr = Address::makeFromBuffer( $buffer ); $callback( $adr ); } } protected function seekTo( $string, array &$buffer = null ) { do { $line = fgets( $this->handle ); if($buffer) { $buffer[] = trim($line); } } while( $line !== false && strpos( $line, $string ) === false ); return $line ? trim($line) : false; } }
Replace codes to HTTP Codes.
<?php /** * @author Andrey Helldar <helldar@ai-rus.com> * * @since 2017-02-20 * @since 2017-03-08 Add statuses for user. * @since 2017-03-20 Replace codes to HTTP Codes. */ return array( 1 => 'Unknown method!', 2 => 'Unknown error!', 3 => 'Access denied.', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 204 => 'No content', 301 => 'Moved', 302 => 'Found', 304 => 'Not Modified', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 409 => 'Conflict', 500 => 'Internal Server Error', 502 => 'Bad Gateway', 503 => 'Service Unvailable', );
<?php /** * @author Andrey Helldar <helldar@ai-rus.com> * * @since 2017-02-20 * @since 2017-03-08 Add statuses for user. */ return array( 1 => 'Unknown method', 2 => 'Unknown error!', 10 => 'Access denied.', 11 => 'Unauthorized.', 20 => 'Successfully.', 21 => 'Success!', 22 => 'Error.', 30 => 'Login successfully.', 31 => 'Logout successfully.', 40 => 'User successfully authorized!', 41 => 'User authenticated successfully!', 42 => 'User already authorized!', 43 => 'User successfully updated!', 50 => 'Activated successfully!', 51 => 'Activation failed!', 52 => 'Deactivated successfully!', 53 => 'Deactivation failed!', );
Fix the condition to rebuild the phrase cache
<?php namespace wcf\system\language\preload; use wcf\data\language\Language; use wcf\system\language\preload\command\CachePreloadPhrases; use wcf\system\WCF; /** * Provides the URL to the preload cache for * phrases and creates it if it is missing. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload * @since 6.0 */ final class PhrasePreloader { /** * Returns the URL to the preload cache. Will implicitly * create the cache if it does not exist. */ public function getUrl(Language $language): string { if (!$this->needsRebuild($language)) { $this->rebuild($language); } return \sprintf( '%s%s?v=%d', WCF::getPath(), $language->getPreloadCacheFilename(), \LAST_UPDATE_TIME ); } private function needsRebuild(Language $language): bool { return \file_exists(\WCF_DIR . $language->getPreloadCacheFilename()); } private function rebuild(Language $language): void { $command = new CachePreloadPhrases($language); $command(); } }
<?php namespace wcf\system\language\preload; use wcf\data\language\Language; use wcf\system\language\preload\command\CachePreloadPhrases; use wcf\system\WCF; /** * Provides the URL to the preload cache for * phrases and creates it if it is missing. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload * @since 6.0 */ final class PhrasePreloader { /** * Returns the URL to the preload cache. Will implicitly * create the cache if it does not exist. */ public function getUrl(Language $language): string { if ($this->needsRebuild($language)) { $this->rebuild($language); } return \sprintf( '%s%s?v=%d', WCF::getPath(), $language->getPreloadCacheFilename(), \LAST_UPDATE_TIME ); } private function needsRebuild(Language $language): bool { return \file_exists(\WCF_DIR . $language->getPreloadCacheFilename()); } private function rebuild(Language $language): void { $command = new CachePreloadPhrases($language); $command(); } }
Remove injected dependency to avoid conflict with setup controller
package controllers; import common.contexts.ProjectContext; import play.inject.Injector; import play.libs.F; import play.mvc.Controller; import play.mvc.Result; import productcatalog.controllers.HomeController; import setupwidget.controllers.SetupController; import javax.inject.Inject; import javax.inject.Singleton; /** * Controller for main web pages like index, imprint and contact. */ @Singleton public final class ApplicationController extends Controller { private final Injector injector; private final SetupController setupController; @Inject public ApplicationController(final Injector injector, final SetupController setupController) { this.injector = injector; this.setupController = setupController; } public F.Promise<Result> index() { return setupController.handleOrFallback(() -> { final HomeController homeController = injector.instanceOf(HomeController.class); final ProjectContext projectContext = injector.instanceOf(ProjectContext.class); final String defaultLanguage = projectContext.defaultLanguage().toLanguageTag(); return homeController.show(defaultLanguage); }); } public Result untrail(final String path) { return movedPermanently("/" + path); } }
package controllers; import common.contexts.ProjectContext; import play.inject.Injector; import play.libs.F; import play.mvc.Controller; import play.mvc.Result; import productcatalog.controllers.HomeController; import setupwidget.controllers.SetupController; import javax.inject.Inject; import javax.inject.Singleton; /** * Controller for main web pages like index, imprint and contact. */ @Singleton public final class ApplicationController extends Controller { private final Injector injector; private final SetupController setupController; private final ProjectContext projectContext; @Inject public ApplicationController(final Injector injector, final SetupController setupController, final ProjectContext projectContext) { this.injector = injector; this.setupController = setupController; this.projectContext = projectContext; } public F.Promise<Result> index() { return setupController.handleOrFallback(() -> { final HomeController homeController = injector.instanceOf(HomeController.class); final String defaultLanguage = projectContext.defaultLanguage().toLanguageTag(); return homeController.show(defaultLanguage); }); } public Result untrail(final String path) { return movedPermanently("/" + path); } }
Fix some bugs - Date : 04/07/2017
<?php error_reporting(E_ALL); ini_set('display_errors', 1); include('classLoad.php'); //classes loading end session_start(); //post input processing $action = htmlentities($_POST['action']);//this parameter's used to let the dispatcher decide the action to take $sourceName = htmlentities($_POST['source']);//this parameter's used to know from which view comes this request $pageNumber = "";//this parameter is used in case of views with pagination, we added it to our source if ( isset($_POST['pageNumber']) ) { $pageNumber = "?p=".htmlentities($_POST['pageNumber']); } //Components Porcessing //Step 1: Generate components names $component = ucfirst($sourceName); $componentController = ucfirst($component)."ActionController"; //Step 2 : Create new components $componentController = new AppController($sourceName); $componentController->$action($_POST); $source = $componentController->source(); //Step 3 : Send response $_SESSION['actionMessage'] = $componentController->actionMessage(); $_SESSION['typeMessage'] = $componentController->typeMessage(); $_SESSION['form'] = $_POST; //this session is used to store form's fields for backwards actions $_SESSION['form']['name'] = $sourceName; header('Location:../'.$source.$pageNumber);
<?php include('classLoad.php'); //classes loading end session_start(); //post input processing $action = htmlentities($_POST['action']);//this parameter's used to let the dispatcher decide the action to take $sourceName = htmlentities($_POST['source']);//this parameter's used to know from which view comes this request $pageNumber = "";//this parameter is used in case of views with pagination, we added it to our source if ( isset($_POST['pageNumber']) ) { $pageNumber = "?p=".htmlentities($_POST['pageNumber']); } //Components Porcessing //Step 1: Generate components names $component = ucfirst($sourceName); $componentController = ucfirst($component)."ActionController"; //Step 2 : Create new components $componentController = new AppController($sourceName); $componentController->$action($_POST); $source = $componentController->source(); //Step 3 : Send response $_SESSION['actionMessage'] = $componentController->actionMessage(); $_SESSION['typeMessage'] = $componentController->typeMessage(); $_SESSION['form'] = $_POST; //this session is used to store form's fields for backwards actions $_SESSION['form']['name'] = $sourceName; header('Location:../'.$source.$pageNumber);
Replace implementation of ls by using the indexer
import config import cliparser import indexer import io import os def command_ls(index): print "Indexed files:" for filename in index.list_files(): print filename def command_view(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: print open(result_file).read() def command_add(config, filename): full_path = os.path.join(config.notes_path, filename) io.edit_file(full_path) print "Added", full_path def command_edit(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: io.edit_file(result_file) def command_rm(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: print "Are you sure you want to delete %s? (y/n)" % result_file choice = io.get_choice() if choice == "y": os.remove(result_file) def command_reindex(config): indexer.reindex(config)
import config import cliparser import indexer import io import os def command_ls(index): with index.index.searcher() as searcher: results = searcher.documents() print "Indexed files:" for result in results: print result["filename"] def command_view(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: print open(result_file).read() def command_add(config, filename): full_path = os.path.join(config.notes_path, filename) io.edit_file(full_path) print "Added", full_path def command_edit(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: io.edit_file(result_file) def command_rm(index, query): result_file = indexer.find_result(index.index, query) if result_file is None: print "No results found" else: print "Are you sure you want to delete %s? (y/n)" % result_file choice = io.get_choice() if choice == "y": os.remove(result_file) def command_reindex(config): indexer.reindex(config)
Use function to fix lint
"use strict"; let map; function init(options) { map = setupMap(options); } function commands(bot, options, action) { const message = action.message; const words = message.split(" "); let args = words.slice(); // copy words args.splice(0, 1); // remove command args = args.join(" "); const target = args.split(/[ ,]/g).filter(Boolean).join(", "); const url = map.get(words[0]); if (url) { bot.say(action.target, (target ? target + ": " + url : url)); } } function setupMap(options) { const temp = new Map(); temp.set(options.commandPrefix + "css", "https://github.com/thelounge/lounge/wiki/CSS-Modifications"); temp.set(options.commandPrefix + "wiki", "https://github.com/thelounge/lounge/wiki/"); temp.set(options.commandPrefix + "docs", "https://thelounge.github.io/docs/"); temp.set(options.commandPrefix + "releases", "https://github.com/thelounge/lounge/release"); return temp; } module.exports = {init, commands};
"use strict"; let map; var init = function(options) { map = setupMap(options); } var commands = function(bot, options, action) { const message = action.message; const words = message.split(" "); let args = words.slice(); // copy words args.splice(0, 1); // remove command args = args.join(" "); const target = args.split(/[ ,]/g).filter(Boolean).join(", "); const url = map.get(words[0]); if (url) { bot.say(action.target, (target ? target + ": " + url : url)); } }; function setupMap(options) { const temp = new Map(); temp.set(options.commandPrefix + "css", "https://github.com/thelounge/lounge/wiki/CSS-Modifications"); temp.set(options.commandPrefix + "wiki", "https://github.com/thelounge/lounge/wiki/"); temp.set(options.commandPrefix + "docs", "https://thelounge.github.io/docs/"); temp.set(options.commandPrefix + "releases", "https://github.com/thelounge/lounge/release"); return temp; } module.exports = {init, commands};
Add unregister form action creator
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type formId: string */ export function unregisterForm(formId) { return { type: REGISTER_FORM, payload: formId, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
Remove uses of using() from migrations This hardcoded the db_alias fetched from schema_editor and forces django to try and migrate any second database you use, rather than routing to the default database. In testing a build from scratch, these do not appear needed. Using using() prevents us from using multiple databases behind edxapp.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models DEFAULT_PROFILES = [ "desktop_mp4", "desktop_webm", "mobile_high", "mobile_low", "youtube", ] def create_default_profiles(apps, schema_editor): """ Add default profiles """ Profile = apps.get_model("edxval", "Profile") for profile in DEFAULT_PROFILES: Profile.objects.get_or_create(profile_name=profile) def delete_default_profiles(apps, schema_editor): """ Remove default profiles """ Profile = apps.get_model("edxval", "Profile") Profile.objects.filter(profile_name__in=DEFAULT_PROFILES).delete() class Migration(migrations.Migration): dependencies = [ ('edxval', '0001_initial'), ] operations = [ migrations.RunPython(create_default_profiles, delete_default_profiles), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models DEFAULT_PROFILES = [ "desktop_mp4", "desktop_webm", "mobile_high", "mobile_low", "youtube", ] def create_default_profiles(apps, schema_editor): """ Add default profiles """ Profile = apps.get_model("edxval", "Profile") db_alias = schema_editor.connection.alias for profile in DEFAULT_PROFILES: Profile.objects.using(db_alias).get_or_create(profile_name=profile) def delete_default_profiles(apps, schema_editor): """ Remove default profiles """ Profile = apps.get_model("edxval", "Profile") db_alias = schema_editor.connection.alias Profile.objects.using(db_alias).filter(profile_name__in=DEFAULT_PROFILES).delete() class Migration(migrations.Migration): dependencies = [ ('edxval', '0001_initial'), ] operations = [ migrations.RunPython(create_default_profiles, delete_default_profiles), ]
Change method of generating random numbers and add getShortURL() method
package main import ( "fmt" "io/ioutil" "math/rand" "strings" "time" ) var ( animals []string adjectives []string ) func readWords(filename string) ([]string, error) { d, err := ioutil.ReadFile(filename) if err != nil { return []string{}, err } words := strings.Split(string(d), "\n") return words, nil } func getShortURL() string { return fmt.Sprintf("%s%s", adjectives[rand.Intn(len(adjectives))], animals[rand.Intn(len(animals))]) } func main() { animals, _ = readWords("animals4.txt") adjectives, _ = readWords("adjectives3.txt") rand.Seed(time.Now().UnixNano()) for { <-time.After(time.Second) fmt.Println(getShortURL()) } }
package main import "fmt" import "crypto/md5" // url, gfy-url func convert(input string, n, max int) []int { b := md5.Sum([]byte(input)) // 16 bytes result := make([]int, n) blocksize := (numbits(max) / 8) + 1 j := 0 for i := 0; i < n; i++ { result[i] = getInt(b[j:j+blocksize]) % max j += blocksize } return result } func getInt(b []byte) int { l := len(b) result := 0 var shiftby uint32 for i := 0; i < l; i++ { shiftby = uint32(8 * (l - i - 1)) result |= int(b[i]) << shiftby } return result } func numbits(n int) int { result := 0 for n > 0 { n = n / 2 result++ } return result } // max is implicitly 256 func convert2(input string, n int) []int { b := md5.Sum([]byte(input)) result := make([]int, n) for i := 0; i < n; i++ { result[i] = int(b[i]) } return result } func main() { fmt.Println((numbits(32767) / 8) + 1) fmt.Println(convert("hivkdv", 8, 1024)) }
Throw error where no mapping was found for a route
import { routes } from './config-routes.js' import { connect } from 'react-redux' export const path = Object.keys(routes).reduce((mapping, route) => { mapping[route] = routes[route].pattern return mapping }, {}) export const paramsToProps = Object.keys(routes).reduce((mapping, route) => { mapping[routes[route].pattern] = (state, { routeParams }) => routes[route].paramsToProps(state, routeParams) return mapping }, {}) export const uriToLink = Object.keys(routes).reduce((mapping, route) => { mapping[route] = routes[route].uriToLink return mapping }, {}) export const connectFromRoute = (...args) => connect( (state, ownProps) => { const mapRoute = paramsToProps[ownProps.route.path] if (mapRoute === undefined) throw new ReferenceError( `Mapping for route \`${ownProps.route.path}\`is missing` ) return mapRoute ? mapRoute(state, ownProps) : {} })(...args)
import { routes } from './config-routes.js' import { connect } from 'react-redux' export const path = Object.keys(routes).reduce((mapping, route) => { mapping[route] = routes[route].pattern return mapping }, {}) export const paramsToProps = Object.keys(routes).reduce((mapping, route) => { mapping[routes[route].pattern] = (state, { routeParams }) => routes[route].paramsToProps(state, routeParams) return mapping }, {}) export const uriToLink = Object.keys(routes).reduce((mapping, route) => { mapping[route] = routes[route].uriToLink return mapping }, {}) export const connectFromRoute = (...args) => connect( (state, ownProps) => { const mapRoute = paramsToProps[ownProps.route.path] //TODO warning if no mapping is found for the route (because it fails //silently but it can hide an error) return mapRoute ? mapRoute(state, ownProps) : {} })(...args)
Change gulp compile task name to compile-ts
const gulp = require("gulp"); const browserify = require("browserify"); const tsify = require("tsify"); const source = require("vinyl-source-stream"); const config = { paths: { build: "./build" } }; gulp.task("generate-website", function() { return gulp.src("./web/*") .pipe(gulp.dest("./build/")); }); gulp.task("compile-ts", function() { return browserify({ basedir: "./", paths: ["./src/"], entries: ["./src/Entrypoint.ts"] }) .plugin(tsify) .bundle() .pipe(source("webhexagon.js")) .pipe(gulp.dest("./build/")); }); gulp.task("build", ["generate-website", "compile-ts"], function() {});
const gulp = require("gulp"); const browserify = require("browserify"); const tsify = require("tsify"); const source = require("vinyl-source-stream"); const config = { paths: { build: "./build" } }; gulp.task("generate-website", function() { return gulp.src("./web/*") .pipe(gulp.dest("./build/")); }); gulp.task("compile", function() { return browserify({ basedir: "./", paths: ["./src/"], entries: ["./src/Entrypoint.ts"] }) .plugin(tsify) .bundle() .pipe(source("webhexagon.js")) .pipe(gulp.dest("./build/")); }); gulp.task("build", ["generate-website", "compile"], function() {});
Add some extras to props
const date = new Date(); const [major, minor, patch] = process.versions.node.split('.'); export const defaults = { date: { day: date.getDate(), month: date.getMonth(), fullYear: date.getFullYear() }, node: {major, minor, patch}, user: { name: '', github: '', email: '' }, package: { name: '', description: '' }, curly: { left: '{', right: '}' } }; export const properties = { 'user.name': { description: 'Your name: ', message: 'Required', required: true }, 'user.email': { description: 'Your email (will be publicly available, optional): ', pattern: /@/, message: 'Should be a valid e-mail' }, 'user.github': { description: 'Your GitHub public username: ', pattern: /^[a-z0-9]+[a-z0-9\-]+[a-z0-9]+$/i, message: 'Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen', required: true }, 'package.name': { description: 'Package name: ', pattern: /^[a-z0-9]+[a-z0-9\-_]+$/, message: 'Package name may only contain alphanumeric characters, hyphens or underscores', required: true }, 'package.description': { description: 'Package description: ' } };
const date = new Date(); export const defaults = { date: { day: date.getDate(), month: date.getMonth(), fullYear: date.getFullYear() }, user: { name: '', github: '', email: '' }, package: { name: '', description: '' } }; export const properties = { 'user.name': { description: 'Your name: ', message: 'Required', required: true }, 'user.email': { description: 'Your email (will be publicly available, optional): ', pattern: /@/, message: 'Should be a valid e-mail' }, 'user.github': { description: 'Your GitHub public username: ', pattern: /^[a-z0-9]+[a-z0-9\-]+[a-z0-9]+$/i, message: 'Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen', required: true }, 'package.name': { description: 'Package name: ', pattern: /^[a-z0-9]+[a-z0-9\-_]+$/, message: 'Package name may only contain alphanumeric characters, hyphens or underscores', required: true }, 'package.description': { description: 'Package description: ' } };
Remove unnecessary argument from seeder file
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then(() => done()) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then((rows) => { console.log(rows); return done(); }) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
Add user timeline API method.
var _ = require('lodash'), Promise = require('bluebird'); module.exports.userTimeline = function(params) { return this.get("/statuses/user_timeline.json", params); } module.exports.show = function(params) { var path = "/statuses/show.json?id=" + params.id; return this.get(path, params); }; module.exports.lookup = function(params) { var self = this; var ids = _.chunk(params.id, 100); delete params.id; return Promise.resolve(ids) .map(function(ids) { var path = "/statuses/lookup.json?id=" + ids; return self.get(path, params) .then(function(res) {return { data: res };}) .catch(function(e) {return { error: e };}); }).reduce(function(obj, res) { if (res.data) { obj.data.push(res.data); } if (res.error) { obj.errors.push(res.error); } return obj; }, {data: [], errors: []}) .then(function(result) { result.data = _.flatten(result.data); result.errors = _.flatten(result.errors); return result; }); };
var _ = require('lodash'), Promise = require('bluebird'); module.exports.show = function(params) { var path = "/statuses/show.json?id=" + params.id; return this.get(path, params); }; module.exports.lookup = function(params) { var self = this; var ids = _.chunk(params.id, 100); delete params.id; return Promise.resolve(ids) .map(function(ids) { var path = "/statuses/lookup.json?id=" + ids; return self.get(path, params) .then(function(res) {return { data: res };}) .catch(function(e) {return { error: e };}); }).reduce(function(obj, res) { if (res.data) { obj.data.push(res.data); } if (res.error) { obj.errors.push(res.error); } return obj; }, {data: [], errors: []}) .then(function(result) { result.data = _.flatten(result.data); result.errors = _.flatten(result.errors); return result; }); };
Change the service detail task label
import mixin from 'reactjs-mixin'; import React from 'react'; import {StoreMixin} from 'mesosphere-shared-reactjs'; import MesosStateStore from '../stores/MesosStateStore'; import Service from '../structs/Service'; import TaskView from './TaskView'; class ServiceDetailTaskTab extends mixin(StoreMixin) { constructor() { super(...arguments); this.store_listeners = [ {name: 'state', events: ['success']} ]; } render() { let tasks = MesosStateStore.getTasksByService(this.props.service); return ( <TaskView tasks={tasks} inverseStyle={true} label="Instance" parentRouter={this.context.router} /> ); } } ServiceDetailTaskTab.contextTypes = { router: React.PropTypes.func }; ServiceDetailTaskTab.propTypes = { service: React.PropTypes.instanceOf(Service) }; module.exports = ServiceDetailTaskTab;
import mixin from 'reactjs-mixin'; import React from 'react'; import {StoreMixin} from 'mesosphere-shared-reactjs'; import MesosStateStore from '../stores/MesosStateStore'; import Service from '../structs/Service'; import TaskView from './TaskView'; class ServiceDetailTaskTab extends mixin(StoreMixin) { constructor() { super(...arguments); this.store_listeners = [ {name: 'state', events: ['success']} ]; } render() { let tasks = MesosStateStore.getTasksByService(this.props.service); return ( <TaskView tasks={tasks} inverseStyle={true} parentRouter={this.context.router} /> ); } } ServiceDetailTaskTab.contextTypes = { router: React.PropTypes.func }; ServiceDetailTaskTab.propTypes = { service: React.PropTypes.instanceOf(Service) }; module.exports = ServiceDetailTaskTab;
Set organization and user groups to UserModel
import Vue from 'vue'; // Backbone Models import ConfigModel from 'dashboard/data/config-model'; import UserModel from 'dashboard/data/user-model'; import OrganizationModel from 'dashboard/data/organization-model'; import UserGroupsCollection from 'dashboard/data/user-groups-collection'; import BackgroundPollingModel from 'dashboard/data/background-polling/dashboard-background-polling-model'; const BackboneCoreModels = {}; BackboneCoreModels.install = function (Vue, options) { Vue.mixin({ beforeCreate () { this.$cartoModels = options; } }); }; const configModel = new ConfigModel({ ...window.CartoConfig.data.config, base_url: window.CartoConfig.data.user_data.base_url }); const userModel = configureUserModel(window.CartoConfig.data.user_data); const backgroundPollingModel = new BackgroundPollingModel({ showGeocodingDatasetURLButton: true, geocodingsPolling: true, importsPolling: true }, { configModel, userModel }); Vue.use(BackboneCoreModels, { config: configModel, user: userModel, backgroundPolling: backgroundPollingModel }); function configureUserModel (userData) { const userModel = new UserModel(userData); if (userData.organization) { userModel.setOrganization(new OrganizationModel(userData.organization, { configModel })); } if (userData.groups) { userModel.setGroups(new UserGroupsCollection(userData.groups, { configModel })); } return userModel; }
import Vue from 'vue'; // Backbone Models import ConfigModel from 'dashboard/data/config-model'; import UserModel from 'dashboard/data/user-model'; import BackgroundPollingModel from 'dashboard/data/background-polling/dashboard-background-polling-model'; const BackboneCoreModels = {}; BackboneCoreModels.install = function (Vue, options) { Vue.mixin({ beforeCreate () { this.$cartoModels = options; } }); }; const configModel = new ConfigModel({ ...window.CartoConfig.data.config, base_url: window.CartoConfig.data.user_data.base_url }); const userModel = new UserModel(window.CartoConfig.data.user_data); const backgroundPollingModel = new BackgroundPollingModel({ showGeocodingDatasetURLButton: true, geocodingsPolling: true, importsPolling: true }, { configModel, userModel }); Vue.use(BackboneCoreModels, { config: configModel, user: userModel, backgroundPolling: backgroundPollingModel });
Use of @component for buttons in form
@section('js') <script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script> @endsection @component('core::admin._buttons-form', ['model' => $model]) @endcomponent {!! BootForm::hidden('id') !!} @include('core::admin._image-fieldset', ['field' => 'image']) <div class="row"> <div class="col-sm-2 form-group @if($errors->has('position'))has-error @endif"> {!! BootForm::text(__('Position'), 'position') !!} </div> </div> <div class="row"> <div class="col-sm-6"> {!! BootForm::text(__('Url'), 'url') !!} </div> </div> {!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!} {!! TranslatableBootForm::hidden('status')->value(0) !!} {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!} {!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}
@section('js') <script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script> @endsection @include('core::admin._buttons-form') {!! BootForm::hidden('id') !!} @include('core::admin._image-fieldset', ['field' => 'image']) <div class="row"> <div class="col-sm-2 form-group @if($errors->has('position'))has-error @endif"> {!! BootForm::text(__('Position'), 'position') !!} </div> </div> <div class="row"> <div class="col-sm-6"> {!! BootForm::text(__('Url'), 'url') !!} </div> </div> {!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!} {!! TranslatableBootForm::hidden('status')->value(0) !!} {!! TranslatableBootForm::checkbox(__('Published'), 'status') !!} {!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}
Add sale_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-b44d9932402c4941921f83487b823e7359d324c0
{ "name" : "Sales Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_sale.html", "depends" : ["product", "stock", "mrp"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["sale_demo.xml", "sale_unit_test.xml"], "description": """ The base module to manage quotations and sales orders. * Workflow with validation steps: - Quotation -> Sale order -> Invoice * Invoicing methods: - Invoice on order (before or after shipping) - Invoice on delivery - Invoice on timesheets - Advance invoice * Partners preferences (shipping, invoicing, incoterm, ...) * Products stocks and prices * Delivery methods: - all at once, multi-parcel - delivery costs """, "update_xml" : [ "sale_workflow.xml", "sale_sequence.xml", "sale_data.xml", "sale_view.xml", "sale_report.xml", "sale_wizard.xml", "stock_view.xml", "sale_security.xml" ], "active": False, "installable": True }
{ "name" : "Sales Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_sale.html", "depends" : ["product", "stock", "mrp"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["sale_demo.xml", "sale_unit_test.xml"], "description": """ The base module to manage quotations and sales orders. * Workflow with validation steps: - Quotation -> Sale order -> Invoice * Invoicing methods: - Invoice on order (before or after shipping) - Invoice on delivery - Invoice on timesheets - Advance invoice * Partners preferences (shipping, invoicing, incoterm, ...) * Products stocks and prices * Delivery methods: - all at once, multi-parcel - delivery costs """, "update_xml" : [ "sale_workflow.xml", "sale_sequence.xml", "sale_data.xml", "sale_view.xml", "sale_report.xml", "sale_wizard.xml", "stock_view.xml" ], "active": False, "installable": True }
Fix jquery snippet test require
require('es5-shim'); require('./clientIdGenerator'); require('./clipboard'); require('./messageParser'); require('./webSocketManager'); require('./settingsStore'); require('./app.js'); // describe blocks for test organization describe('Utilities', function() { require('./utils/dateTimeFormatter'); require('./utils/handlebarsHelpers'); require('./utils/searchCriteria'); }); describe('Backbone', function() { describe('Models', function() { require('./models/request'); require('./models/settings'); }); describe('Views', function() { require('./views/channelSelector'); require('./views/request'); require('./views/serverLogs'); require('./views/settings'); require('./views/app'); }); }); host = 'localhost'; port = 8000; chai.use(require('sinon-chai')); chai.use(require('chai-jquery')); var Backbone = require('backbone'); Backbone.$ = require('jquery'); require('../../source/js/utils/handlebarsHelpers'); if (window.mochaPhantomJS) { mochaPhantomJS.run(); } else { mocha.run(); }
require('es5-shim'); require('./clientIdGenerator'); require('./clipboard'); require('./jQuerySnippet'); require('./messageParser'); require('./webSocketManager'); require('./settingsStore'); require('./app.js'); // describe blocks for test organization describe('Utilities', function() { require('./utils/dateTimeFormatter'); require('./utils/handlebarsHelpers'); require('./utils/searchCriteria'); }); describe('Backbone', function() { describe('Models', function() { require('./models/request'); require('./models/settings'); }); describe('Views', function() { require('./views/channelSelector'); require('./views/request'); require('./views/serverLogs'); require('./views/settings'); require('./views/app'); }); }); host = 'localhost'; port = 8000; chai.use(require('sinon-chai')); chai.use(require('chai-jquery')); var Backbone = require('backbone'); Backbone.$ = require('jquery'); require('../../source/js/utils/handlebarsHelpers'); if (window.mochaPhantomJS) { mochaPhantomJS.run(); } else { mocha.run(); }
Use explicit API(s) for examples
#!/usr/bin/env python # XXX: Broken - Does O_NONBLOCK work at all? """An implementation of the Python Concurrency Problem of 99 Bottles of Beer See: http://wiki.python.org/moin/Concurrency/99Bottles """ import sys from circuits.io import File from circuits import Component from circuits.net.protocols import LP class Tail(Component): """A complex component which combines the ``File`` and ``LP`` (Line Protoco) components together to implement similar functionality to the UNIX ``tail`` command. """ def init(self, filename): """Initialize the Component. NB: This is automatically called after ``__new__`` and ``__init__``. """ (File(filename, "r") + LP()).register(self) class Grep(Component): """A simple component that simply listens for ``line`` events from the ``Tail`` component and performs a regular expression match against each line. If the line matches it is printed to standard output. """ def init(self, pattern): self.pattern = pattern def line(self, line): """Line Event Handler""" if self.pattern in line: print(line) # Configure and "run" the System. app = Tail(sys.argv[1]) Grep(sys.argv[2]).register(app) app.run()
#!/usr/bin/env python # XXX: Broken - Does O_NONBLOCK work at all? """An implementation of the Python Concurrency Problem of 99 Bottles of Beer See: http://wiki.python.org/moin/Concurrency/99Bottles """ import sys from circuits.io import File from circuits import Component from circuits.net.protocols import LP class Tail(Component): """A complex component which combines the ``File`` and ``LP`` (Line Protoco) components together to implement similar functionality to the UNIX ``tail`` command. """ def init(self, filename): """Initialize the Component. NB: This is automatically called after ``__new__`` and ``__init__``. """ (File(filename, "r") + LP()).register(self) class Grep(Component): """A simple component that simply listens for ``line`` events from the ``Tail`` component and performs a regular expression match against each line. If the line matches it is printed to standard output. """ def init(self, pattern): self.pattern = pattern def line(self, line): """Line Event Handler""" if self.pattern in line: print(line) # Configure and "run" the System. from circuits import Debugger (Tail(sys.argv[1]) + Debugger() + Grep(sys.argv[2])).run()
Add support for presenter and continuing frame capture Click the right click of the presenter will trigger frame capture.
from cam import OpenCV_Cam import cv2 import os.path cam = OpenCV_Cam(0) cam.size = (1920, 1080) KEY_ESC = 27 KEY_SPACE = ord(' ') prevFrame = None i = 0 fname="frame.png" if os.path.isfile(fname): prevFrame = cv2.imread(fname) fourcc = cv2.cv.CV_FOURCC(*'XVID') video = cv2.VideoWriter('output.avi',fourcc, 3.0, cam.size, isColor =True) while True: # Capture frame-by-frame frame = cam.read() # image processing functions # Load the frame into a window named as 'Press any key to exit' if (prevFrame is not None): showFrame = cv2.addWeighted(frame,0.7,prevFrame,0.3,0) else: showFrame = frame resizeShowFrame = cv2.resize(showFrame, (0,0), fx = 0.5, fy = 0.5 ) cv2.imshow('Press ESC to exit', resizeShowFrame) # wait for the key key_code = cv2.waitKey(10) if key_code is KEY_SPACE or key_code == 2228224: cv2.imwrite('frame'+str(i)+'.png', frame) video.write(frame) prevFrame = frame i += 1 elif key_code is KEY_ESC: break cv2.destroyAllWindows() cam.release() video.release()
from cam import OpenCV_Cam import cv2 cam = OpenCV_Cam(0) cam.size = (1920, 1080) KEY_ESC = 27 KEY_SPACE = ord(' ') prevFrame = None i = 0 fourcc = cv2.cv.CV_FOURCC(*'XVID') video = cv2.VideoWriter('output.avi',fourcc, 3.0, (1920,1080), isColor =True) while True: # Capture frame-by-frame frame = cam.read() # image processing functions # Load the frame into a window named as 'Press any key to exit' if (prevFrame is not None): showFrame = cv2.addWeighted(frame,0.7,prevFrame,0.3,0) else: showFrame = frame resizeShowFrame = cv2.resize(showFrame, (0,0), fx = 0.5, fy = 0.5 ) cv2.imshow('Press ESC to exit', resizeShowFrame) # wait for the key key_code = cv2.waitKey(10) if key_code is KEY_SPACE: cv2.imwrite('frame'+str(i)+'.png', frame) video.write(frame) prevFrame = frame i += 1 elif key_code is KEY_ESC: break cv2.destroyAllWindows() cam.release() video.release()
Fix encoding error in Python 3.
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf()
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'w') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf()
Mark comment as safe. Otherwise it is displayed.
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return '<!-- no favicon -->' html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
Add length guard around native SG aligner input.
package abra; import abra.SemiGlobalAligner.Result; public class NativeSemiGlobalAligner { private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend); private int match = 8; private int mismatch = -32; private int gapOpen = -48; private int gapExtend = -1; private static final int MAX_CONTIG_LEN = 1998; private static final int MAX_REF_LEN = 4998; public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) { this.match = match; this.mismatch = mismatch; this.gapOpen = gapOpen; this.gapExtend = gapExtend; } public Result align(String seq1, String seq2) { if (seq1.length() > MAX_CONTIG_LEN) { throw new IllegalArgumentException("Contig too long"); } if (seq2.length() > MAX_REF_LEN) { throw new IllegalArgumentException("Ref too long"); } // Result returned in format score:secondBest:pos:endPos:cigar // 789:741:611:734:52M108I71M String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend); String[] results = res.split(":"); Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]), Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]); return result; } }
package abra; import abra.SemiGlobalAligner.Result; public class NativeSemiGlobalAligner { private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend); private int match = 8; private int mismatch = -32; private int gapOpen = -48; private int gapExtend = -1; public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) { this.match = match; this.mismatch = mismatch; this.gapOpen = gapOpen; this.gapExtend = gapExtend; } public Result align(String seq1, String seq2) { // Result returned in format score:secondBest:pos:endPos:cigar // 789:741:611:734:52M108I71M String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend); String[] results = res.split(":"); Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]), Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]); return result; } }
Add latest python to fedora
var funcs = require('./funcs.js') module.exports = function (dist, release) { var contents = funcs.replace(header, {dist: dist, release: release}) + '\n\n' contents += funcs.replace(pkgs, {pkgs: funcs.generatePkgStr(commonPkgs)}) + '\n\n' return contents } var header = 'FROM {{DIST}}:{{RELEASE}}\n' + 'MAINTAINER William Blankenship <wblankenship@nodesource.com>' var pkgs = 'RUN yum install -y \\\n' + '{{PKGS}}' + ' && yum clean all' /* Shouldn't be needed for Fedora var epel = 'RUN rpm -ivh $(curl http://dl.fedoraproject.org/pub/epel/5/x86_64/repoview/epel-release.html | grep -oE "epel-release-[0-9\-]+\.noarch\.rpm" | sed "s/^/http:\\/\\/dl.fedoraproject.org\\/pub\\/epel\\/5\\/x86_64\\//") \\\n' + ' && yum install -y python26 \\\n' + ' && yum clean all' */ var commonPkgs = [ 'automake', 'libicu', 'curl', 'gcc', 'gcc-c++', 'git', 'kernel-devel', 'make', 'perl', 'python', 'which' ]
var funcs = require('./funcs.js') module.exports = function (dist, release) { var contents = funcs.replace(header, {dist: dist, release: release}) + '\n\n' contents += funcs.replace(pkgs, {pkgs: funcs.generatePkgStr(commonPkgs)}) + '\n\n' return contents } var header = 'FROM {{DIST}}:{{RELEASE}}\n' + 'MAINTAINER William Blankenship <wblankenship@nodesource.com>' var pkgs = 'RUN yum install -y \\\n' + '{{PKGS}}' + ' && yum clean all' /* Shouldn't be needed for Fedora var epel = 'RUN rpm -ivh $(curl http://dl.fedoraproject.org/pub/epel/5/x86_64/repoview/epel-release.html | grep -oE "epel-release-[0-9\-]+\.noarch\.rpm" | sed "s/^/http:\\/\\/dl.fedoraproject.org\\/pub\\/epel\\/5\\/x86_64\\//") \\\n' + ' && yum install -y python26 \\\n' + ' && yum clean all' */ var commonPkgs = [ 'automake', 'libicu', 'curl', 'gcc', 'gcc-c++', 'git', 'kernel-devel', 'make', 'perl', 'which' ]
Add a model property to tell if credentials have expired
from django.db import models from django.contrib.auth.models import User import datetime def default_expiry_time(): return datetime.datetime.now() + datetime.timedelta(days=1) def random_string(): return User.objects.make_random_password(16) class Credentials(models.Model): "Keeps track of issued MAC credentials" user = models.ForeignKey(User) expiry = models.DateTimeField("Expires On", default=default_expiry_time) identifier = models.CharField("MAC Key Identifier", max_length=16, default=random_string) key = models.CharField("MAC Key", max_length=16, default=random_string) def __unicode__(self): return u"{0}:{1}".format(self.identifier, self.key) @property def expired(self): """Returns whether or not the credentials have expired""" if self.expiry < datetime.datetime.now(): return True return False class Nonce(models.Model): """Keeps track of any NONCE combinations that we have used""" nonce = models.CharField("NONCE", max_length=16, null=True, blank=True) timestamp = models.DateTimeField("Timestamp", auto_now_add=True) credentials = models.ForeignKey(Credentials)
from django.db import models from django.contrib.auth.models import User import datetime def default_expiry_time(): return datetime.datetime.now() + datetime.timedelta(days=1) def random_string(): return User.objects.make_random_password(16) class Credentials(models.Model): "Keeps track of issued MAC credentials" user = models.ForeignKey(User) expiry = models.DateTimeField("Expires On", default=default_expiry_time) identifier = models.CharField("MAC Key Identifier", max_length=16, default=random_string) key = models.CharField("MAC Key", max_length=16, default=random_string) def __unicode__(self): return u"{0}:{1}".format(self.identifier, self.key) class Nonce(models.Model): """Keeps track of any NONCE combinations that we have used""" nonce = models.CharField("NONCE", max_length=16, null=True, blank=True) timestamp = models.DateTimeField("Timestamp", auto_now_add=True) credentials = models.ForeignKey(Credentials)
Remove astpp from installation modules
from setuptools import setup setup( name='flaws', version='0.0.1', author='Alexander Schepanovski', author_email='suor.web@gmail.com', description='Finds flaws in your python code', long_description=open('README.rst').read(), url='http://github.com/Suor/flaws', license='BSD', packages=['flaws'], install_requires=[ 'funcy>=1.1', ], entry_points = { 'console_scripts': [ 'flaws = flaws:main', ], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Environment :: Console', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup setup( name='flaws', version='0.0.1', author='Alexander Schepanovski', author_email='suor.web@gmail.com', description='Finds flaws in your python code', long_description=open('README.rst').read(), url='http://github.com/Suor/flaws', license='BSD', py_modules=['astpp'], packages=['flaws'], install_requires=[ 'funcy>=1.1', ], entry_points = { 'console_scripts': [ 'flaws = flaws:main', ], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Environment :: Console', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Fix action logging for asyncIt.only
'use strict' /* global it */ import actionLogger from './action_logger' export const asyncIt = (description, test, config) => { const decoratedTest = _decorateTest(test, config) it(description, decoratedTest) } asyncIt.only = (description, test, config) => { const decoratedTest = _decorateTest(test, config) it.only(description, decoratedTest) } asyncIt.skip = (description, test, config) => { const decoratedTest = _decorateTest(test, config) it.skip(description, decoratedTest) } export const _decorateTest = (test, config) => { return async () => { if (config === 'debug') { actionLogger.startTestOnlyLogging() } try { await test() actionLogger.stopTestOnlyLogging() } catch (err) { actionLogger.stopTestOnlyLogging() throw err } } }
'use strict' /* global it */ import actionLogger from './action_logger' export const asyncIt = (description, test, config) => { const decoratedTest = _decorateTest(test, config) it(description, decoratedTest) } asyncIt.only = (description, test) => { const decoratedTest = _decorateTest(test) it.only(description, decoratedTest) } asyncIt.skip = (description, test) => { const decoratedTest = _decorateTest(test) it.skip(description, decoratedTest) } export const _decorateTest = (test, config) => { return async () => { if (config === 'debug') { actionLogger.startTestOnlyLogging() } try { await test() actionLogger.stopTestOnlyLogging() } catch (err) { actionLogger.stopTestOnlyLogging() throw err } } }
Add type hinting to Site Type controller manager
<?php namespace Concrete\Core\Site\Type\Controller; use Concrete\Core\Application\Application; use Concrete\Core\Support\Manager as CoreManager; class Manager extends CoreManager { /** * @var string */ protected $standardController = StandardController::class; public function __construct(Application $application) { parent::__construct($application); } /** * @return $this */ public function setStandardController(string $vaiue): self { $this->standardController = $vaiue; return $this; } /** * {@inheritdoc} * * @see \Illuminate\Support\Manager::driver() * * @throws \InvalidArgumentException * * @return \Concrete\Core\Site\Type\Controller\ControllerInterface */ public function driver($driver = null) { if (!isset($this->customCreators[$driver]) && !isset($this->drivers[$driver])) { return $this->getStandardController(); } return parent::driver($driver); } protected function getStandardController(): ControllerInterface { return $this->app->make($this->standardController); } }
<?php namespace Concrete\Core\Site\Type\Controller; use Concrete\Core\Application\Application; use Concrete\Core\Support\Manager as CoreManager; class Manager extends CoreManager { protected $standardController = StandardController::class; /** * @param mixed $standardController */ public function setStandardController($standardController) { $this->standardController = $standardController; } protected function getStandardController() { return $this->app->make($this->standardController); } public function driver($driver = null) { if (!isset($this->customCreators[$driver]) && !isset($this->drivers[$driver])) { return $this->getStandardController(); } return parent::driver($driver); } public function __construct(Application $application) { parent::__construct($application); } }
Cut fbcode_builder dep for thrift on krb5 Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up. Reviewed By: stevegury, vitaut Differential Revision: D14814205 fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final') return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.github_project_workdir('krb5/krb5', 'src'), builder.autoconf_install('krb5/krb5'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
Set up dynamic port number
const express = require('express'); const app = express(); const portNumber = process.env.PORT || 3000; const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser') if (process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const path = require('path'); const users = require('./routes/users'); const token = require('./routes/token'); const resorts = require('./routes/resorts'); const trails = require('./routes/trails'); const ratings = require('./routes/ratings'); const favorites = require('./routes/favorites'); app.use(bodyParser.json()); app.use(cookieParser()); app.use('/apidoc', express.static(path.join(__dirname, 'apidoc'))); app.use(users); app.use(token); app.use(resorts); app.use(trails); app.use(ratings); app.use(favorites); app.use((req, res) => { res.sendStatus(404); }); app.listen(portNumber, () => { console.log(`Listening on port ${portNumber}`); }); module.exports = app;
const express = require('express'); const app = express(); const portNumber = 3000; const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser') if (process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const path = require('path'); const users = require('./routes/users'); const token = require('./routes/token'); const resorts = require('./routes/resorts'); const trails = require('./routes/trails'); const ratings = require('./routes/ratings'); const favorites = require('./routes/favorites'); app.use(bodyParser.json()); app.use(cookieParser()); app.use('/apidoc', express.static(path.join(__dirname, 'apidoc'))); app.use(users); app.use(token); app.use(resorts); app.use(trails); app.use(ratings); app.use(favorites); app.use((req, res) => { res.sendStatus(404); }); app.listen(portNumber, () => { console.log(`Listening on port ${portNumber}`); }); module.exports = app;
Fix edit control assessment modal This works, because our client side verification checks only if the audit attr exists. ref: core-1643
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com from ggrc import db from .mixins import ( deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned ) from .object_document import Documentable from .object_owner import Ownable from .object_person import Personable from .relationship import Relatable from .track_object_state import HasObjectState, track_state_for_class from ggrc.models.reflection import PublishOnly class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable, Documentable, Personable, Timeboxed, Ownable, Relatable, BusinessObject, db.Model): __tablename__ = 'control_assessments' design = deferred(db.Column(db.String), 'ControlAssessment') operationally = deferred(db.Column(db.String), 'ControlAssessment') control_id = db.Column(db.Integer, db.ForeignKey('controls.id')) control = db.relationship('Control', foreign_keys=[control_id]) audit = {} # we add this for the sake of client side error checking # REST properties _publish_attrs = [ 'design', 'operationally', 'control', PublishOnly('audit') ] track_state_for_class(ControlAssessment)
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com from ggrc import db from .mixins import ( deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned ) from .object_document import Documentable from .object_owner import Ownable from .object_person import Personable from .relationship import Relatable from .track_object_state import HasObjectState, track_state_for_class from ggrc.models.reflection import PublishOnly class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable, Documentable, Personable, Timeboxed, Ownable, Relatable, BusinessObject, db.Model): __tablename__ = 'control_assessments' design = deferred(db.Column(db.String), 'ControlAssessment') operationally = deferred(db.Column(db.String), 'ControlAssessment') control_id = db.Column(db.Integer, db.ForeignKey('controls.id')) control = db.relationship('Control', foreign_keys=[control_id]) # REST properties _publish_attrs = [ 'design', 'operationally', 'control' ] track_state_for_class(ControlAssessment)
Make rpc pipeine example stable
import asyncio import aiozmq.rpc from itertools import count class Handler(aiozmq.rpc.AttrHandler): def __init__(self): self.connected = False @aiozmq.rpc.method def remote_func(self, step, a: int, b: int): self.connected = True print("HANDLER", step, a, b) @asyncio.coroutine def go(): handler = Handler() listener = yield from aiozmq.rpc.serve_pipeline( handler, bind='tcp://*:*') listener_addr = next(iter(listener.transport.bindings())) notifier = yield from aiozmq.rpc.connect_pipeline( connect=listener_addr) for step in count(0): yield from notifier.notify.remote_func(step, 1, 2) if handler.connected: break else: yield from asyncio.sleep(0.01) listener.close() yield from listener.wait_closed() notifier.close() yield from notifier.wait_closed() def main(): asyncio.get_event_loop().run_until_complete(go()) print("DONE") if __name__ == '__main__': main()
import asyncio import aiozmq.rpc class Handler(aiozmq.rpc.AttrHandler): @aiozmq.rpc.method def handle_some_event(self, a: int, b: int): pass @asyncio.coroutine def go(): listener = yield from aiozmq.rpc.serve_pipeline( Handler(), bind='tcp://*:*') listener_addr = next(iter(listener.transport.bindings())) notifier = yield from aiozmq.rpc.connect_pipeline( connect=listener_addr) yield from notifier.notify.handle_some_event(1, 2) listener.close() notifier.close() def main(): asyncio.get_event_loop().run_until_complete(go()) print("DONE") if __name__ == '__main__': main()
Check correspondances in framesets now
from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetFrameSet from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for frameset in VerbNetFrameSet.objects.all(): print("{}: {}/{}".format(frameset.name, frameset.ladl_string, frameset.lvf_string)) if frameset.ladl_string: try: parse.FrenchMapping('LADL', frameset.ladl_string).result() except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e)) if frameset.lvf_string: try: parse.FrenchMapping('LVF', frameset.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e))
from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetClass from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for vn_class in VerbNetClass.objects.all(): try: parse.get_ladl_list(vn_class.ladl_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e)) try: parse.get_lvf_list(vn_class.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e))
Fix: Add new measures for shoe -> equivalence
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; ModelingMeasureRange equivalence = null; }
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; }
Disable viewing the plasm in test.
#!/usr/bin/env python import ecto import ecto_test def test_feedback(): plasm = ecto.Plasm() g = ecto_test.Generate("Generator", step=1.0, start=1.0) add = ecto_test.Add() source,sink = ecto.EntangledPair() plasm.connect(source[:] >> add['left'], g[:] >> add['right'], add[:] >> sink[:] ) #ecto.view_plasm(plasm) plasm.execute(niter=1) assert add.outputs.out == 1 # 0 + 1 = 1 plasm.execute(niter=1) assert add.outputs.out == 3 # 1 + 2 = 3 plasm.execute(niter=1) assert add.outputs.out == 6 # 3 + 3 = 6 plasm.execute(niter=1) assert add.outputs.out == 10 # 6 + 4 = 10 if __name__ == '__main__': test_feedback()
#!/usr/bin/env python import ecto import ecto_test def test_feedback(): plasm = ecto.Plasm() g = ecto_test.Generate("Generator", step=1.0, start=1.0) add = ecto_test.Add() source,sink = ecto.EntangledPair() plasm.connect(source[:] >> add['left'], g[:] >> add['right'], add[:] >> sink[:] ) ecto.view_plasm(plasm) plasm.execute(niter=1) assert add.outputs.out == 1 # 0 + 1 = 1 plasm.execute(niter=1) assert add.outputs.out == 3 # 1 + 2 = 3 plasm.execute(niter=1) assert add.outputs.out == 6 # 3 + 3 = 6 plasm.execute(niter=1) assert add.outputs.out == 10 # 6 + 4 = 10 if __name__ == '__main__': test_feedback()
Fix layout on save config page.
<?php echo $Form->form(); ?> <p><?php echo tr('%1 could not save the configuration to the following file:', $app['name']); ?></p> <p><code><?php echo $file; ?></code></p> <?php if ($exists): ?> <p><?php echo tr('The file exists, but %1 does not have permission to write to it.', $app['name']); ?></p> <p><?php echo tr('You should change the access permission or ownership of the file to allow %1 to write to it. ', $app['name']); ?></p> <p><?php echo $Html->link(tr('Click here to get more help.', 'http://apakoh.dk')); ?></p> <p><?php echo tr('Alternatively, you can manually edit the file.')?></p> <?php else: ?> <p><?php echo tr('The file does not exists, and %1 does not have permission to create it.', $app['name']); ?> <p><?php echo tr('Please create the file with the permissions necessary for %1 to write to it, then refresh this page.', $app['name']); ?> <?php endif; ?> <h2><?php echo tr('Unsaved data'); ?></h2> <p> <textarea style="height:150px;"><?php echo h($data); ?></textarea> </p> <?php echo $Form->submit(tr('Cancel'), array('class' => 'primary')); ?> <?php echo $Form->end(); ?>
<?php $this->extend('setup/layout.html'); ?> <?php echo $Form->form(); ?> <p><?php echo tr('%1 could not save the configuration to the following file:', $app['name']); ?></p> <p><code><?php echo $file; ?></code></p> <?php if ($exists): ?> <p><?php echo tr('The file exists, but %1 does not have permission to write to it.', $app['name']); ?></p> <p><?php echo tr('You should change the access permission or ownership of the file to allow %1 to write to it. ', $app['name']); ?></p> <p><?php echo $Html->link(tr('Click here to get more help.', 'http://apakoh.dk')); ?></p> <p><?php echo tr('Alternatively, you can manually edit the file.')?></p> <?php else: ?> <p><?php echo tr('The file does not exists, and %1 does not have permission to create it.', $app['name']); ?> <p><?php echo tr('Please create the file with the permissions necessary for %1 to write to it, then refresh this page.', $app['name']); ?> <?php endif; ?> <h2><?php echo tr('Unsaved data'); ?></h2> <p> <textarea style="height:150px;"><?php echo h($data); ?></textarea> </p> <?php echo $Form->submit(tr('Cancel'), array('class' => 'primary')); ?> <?php echo $Form->end(); ?>
Make a bz2 for the release.
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): target = argv[0] t = tarfile.open(target, mode="w:bz2") for name in [ "bin/topaz", "lib-ruby", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="topaz/%s" % name) t.add( os.path.join(PROJECT_ROOT, "docs"), "topaz/docs", filter=lambda info: info if "_build" not in info.name else None ) t.close() if __name__ == "__main__": main(sys.argv[1:])
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): target = argv[0] t = tarfile.open(target, mode="w") for name in [ "bin/topaz", "lib-ruby", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="topaz/%s" % name) t.add( os.path.join(PROJECT_ROOT, "docs"), "topaz/docs", filter=lambda info: info if "_build" not in info.name else None ) t.close() if __name__ == "__main__": main(sys.argv[1:])
[+] Add 'scenes' field to the Xsplit resource
const cache = require('memory-cache') const websockets = require('../websockets')() /** * Class representing the displayed data for XSplit */ class XSplit { constructor () { "use strict"; let data = cache.get('xsplit') if (data !== null) { this.title = data.title this.picture = data.picture this.background = data.background this.logo = data.logo /** * actually, we should store the program, episode, topic and media currently playing : * that way, the client knows what to display (Media > Topic > Episode) * and the server doesn't need to tell the client what title or picture */ this.episode = data.episode this.topic = data.topic this.media = data.media this.created = data.created this.modified = data.modified this.scenes = data.scenes } else { // default values this.title = null this.picture = null this.background = null this.logo = null this.episode = null // or {} or search for playing episode in the database this.topic = null // same this.media = null // same this.scenes = [] this.created = Date.now() this.modified = Date.now() } } save() { cache.put('xsplit', this) websockets.sockets.emit('xsplit', this) } } module.exports = XSplit;
const cache = require('memory-cache') const websockets = require('../websockets')() /** * Class representing the displayed data for XSplit */ class XSplit { constructor () { "use strict"; let data = cache.get('xsplit') if (data !== null) { this.title = data.title this.picture = data.picture this.background = data.background this.logo = data.logo /** * actually, we should store the program, episode, topic and media currently playing : * that way, the client knows what to display (Media > Topic > Episode) * and the server doesn't need to tell the client what title or picture */ this.episode = data.episode this.topic = data.topic this.media = data.media this.created = data.created this.modified = data.modified } else { // default values this.title = null this.picture = null this.background = null this.logo = null this.episode = null // or {} or search for playing episode in the database this.topic = null // same this.media = null // same this.created = Date.now() this.modified = Date.now() } } save() { cache.put('xsplit', this) websockets.sockets.emit('xsplit', this) } } module.exports = XSplit;
Return "id" key to front instead of "id_".
from sqlalchemy.ext.declarative import declared_attr from blog.lib.database import db class ModelMixin(object): """A base mixin for all models.""" @declared_attr def __tablename__(cls): return cls.__name__.lower() def __str__(self): return '<{} (id={})>'.format(self.__class__.__name__, self.id_) def __repr__(self): return str(self) id_ = db.Column('id', db.Integer, primary_key=True) def get_dictionary(self): d = {} for column in self.__table__.columns: if column.key == 'id': d['id'] = getattr(self, 'id_') else: d[column.key] = getattr(self, column.key) return d def update(self, d): for column in self.__table__.columns: if column.key == 'id_': continue setattr( self, column.key, d.get( column.key, getattr(self, column.key) ) )
from sqlalchemy.ext.declarative import declared_attr from blog.lib.database import db class ModelMixin(object): """A base mixin for all models.""" @declared_attr def __tablename__(cls): return cls.__name__.lower() def __str__(self): return '<{} (id={})>'.format(self.__class__.__name__, self.id_) def __repr__(self): return str(self) id_ = db.Column('id', db.Integer, primary_key=True) def get_dictionary(self): d = {} for column in self.__table__.columns: key = 'id_' if column.key == 'id' else column.key d[key] = getattr(self, key) return d def update(self, d): for column in self.__table__.columns: if column.key == 'id_': continue setattr( self, column.key, d.get( column.key, getattr(self, column.key) ) )
Revert "Increase rest client pool size to 100"
from .base_settings import * import os INSTALLED_APPS += [ 'data_aggregator.apps.DataAggregatorConfig', 'webpack_loader', ] if os.getenv('ENV') == 'localdev': DEBUG = True DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group' DATA_AGGREGATOR_THREADING_ENABLED = False RESTCLIENTS_DAO_CACHE_CLASS = None DATA_AGGREGATOR_THREADING_ENABLED = False else: DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '') DATA_AGGREGATOR_THREADING_ENABLED = True WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'data_aggregator/bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'), } } RESTCLIENTS_CANVAS_POOL_SIZE = 50 ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
from .base_settings import * import os INSTALLED_APPS += [ 'data_aggregator.apps.DataAggregatorConfig', 'webpack_loader', ] if os.getenv('ENV') == 'localdev': DEBUG = True DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group' DATA_AGGREGATOR_THREADING_ENABLED = False RESTCLIENTS_DAO_CACHE_CLASS = None DATA_AGGREGATOR_THREADING_ENABLED = False else: DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '') DATA_AGGREGATOR_THREADING_ENABLED = True WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'data_aggregator/bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'), } } RESTCLIENTS_CANVAS_POOL_SIZE = 100 ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
Split multiple arguments for consistency
from __future__ import absolute_import #__version__ = '0.0.0' #import from data_utils from data_utils import load_csv_data from data_utils import load_Xy_one_hot_data2 from data_utils import load_Xy_data_noheader #import from file_utils from file_utils import get_file #import from default_utils from default_utils import ArgumentStruct from default_utils import Benchmark from default_utils import str2bool from default_utils import initialize_parameters from default_utils import fetch_file from default_utils import verify_path from default_utils import keras_default_config from default_utils import set_up_logger #import from keras_utils #from keras_utils import dense #from keras_utils import add_dense from keras_utils import build_initializer from keras_utils import build_optimizer from keras_utils import set_seed from keras_utils import set_parallelism_threads from generic_utils import Progbar from generic_utils import LoggingCallback from solr_keras import CandleRemoteMonitor from solr_keras import compute_trainable_params from solr_keras import TerminateOnTimeOut
from __future__ import absolute_import #__version__ = '0.0.0' #import from data_utils from data_utils import load_csv_data from data_utils import load_Xy_one_hot_data2 from data_utils import load_Xy_data_noheader #import from file_utils from file_utils import get_file #import from default_utils from default_utils import ArgumentStruct from default_utils import Benchmark from default_utils import str2bool from default_utils import initialize_parameters from default_utils import fetch_file from default_utils import verify_path from default_utils import keras_default_config from default_utils import set_up_logger #import from keras_utils #from keras_utils import dense #from keras_utils import add_dense from keras_utils import build_initializer from keras_utils import build_optimizer from keras_utils import set_seed from keras_utils import set_parallelism_threads from generic_utils import Progbar from generic_utils import LoggingCallback from solr_keras import CandleRemoteMonitor, compute_trainable_params, TerminateOnTimeOut
Update the list of scripts to install.
# -*- coding: utf-8 -*- # # setup.py # shelly # """ Package information for shelly package. """ from setuptools import setup VERSION = '0.1.0' setup( name='shelly', description="Standalone tools to make the shell better.", long_description=""" Shelly makes processing line-by-line data in the shell easier, by providing access to useful functional programming primitives and interactive tools. """, url="http://bitbucket.org/larsyencken/shelly/", version=VERSION, author="Lars Yencken", author_email="lars@yencken.org", license="BSD", scripts=[ 'drop', 'exists', 'groupby', 'max', 'min', 'random', 'range', 'subsample', 'take', 'trickle', ], )
# -*- coding: utf-8 -*- # # setup.py # shelly # """ Package information for shelly package. """ from setuptools import setup VERSION = '0.1.0' setup( name='shelly', description="Standalone tools to make the shell better.", long_description=""" Shelly makes processing line-by-line data in the shell easier, by providing access to useful functional programming primitives and interactive tools. """, url="http://bitbucket.org/larsyencken/shelly/", version=VERSION, author="Lars Yencken", author_email="lars@yencken.org", license="BSD", scripts=[ 'drop', 'take', 'groupby', 'random', 'max', 'trickle', 'min', 'range', ], )
Fix example and dynamically resize array
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; // MAIN // /** * Returns an array containing the ratio of each pair of consecutive elements in order: `X[ i+1 ] / X[ i ]`. * * @private * @param {NumberArray} X - input array * @returns {NumberArray} ratio array * * @example * var R = ratioArray( [ 1.0, 2.0, 5.0 ] ); * // returns [ 2.0, 2.5 ] */ function ratioArray( X ) { var R; var i; R = []; for ( i = 0; i < X.length-1; i++ ) { R.push( X[ i+1 ] / X[ i ] ); } return R; } // EXPORTS // module.exports = ratioArray;
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; // MAIN // /** * Returns an array containing the ratio of each pair of consecutive elements in order: `X[ i+1 ] / X[ i ]`. * * @private * @param {NumberArray} X - input array * @returns {NumberArray} ratio array * * @example * var R = ratioArray( [ 1, 2, 5 ] ); * // returns [ 0.5, 0.4 ] */ function ratioArray( X ) { var R = new Array( X.length-1 ); var i; for ( i = 0; i < R.length; i++ ) { R[ i ] = X[ i+1 ] / X[ i ]; } return R; } // EXPORTS // module.exports = ratioArray;
Update version to 0.7.0 for release
"""EVELink - Python bindings for the EVE API.""" import logging from evelink import account from evelink import api from evelink import char from evelink import constants from evelink import corp from evelink import eve from evelink import map from evelink import server __version__ = "0.7.0" # Implement NullHandler because it was only added in Python 2.7+. class NullHandler(logging.Handler): def emit(self, record): pass # Create a logger, but by default, have it do nothing _log = logging.getLogger('evelink') _log.addHandler(NullHandler()) # Update the version number used in the user-agent api._user_agent = 'evelink v%s' % __version__ __all__ = [ "account", "api", "char", "constants", "corp", "eve", "map", "parsing", "server", ]
"""EVELink - Python bindings for the EVE API.""" import logging from evelink import account from evelink import api from evelink import char from evelink import constants from evelink import corp from evelink import eve from evelink import map from evelink import server __version__ = "0.6.2" # Implement NullHandler because it was only added in Python 2.7+. class NullHandler(logging.Handler): def emit(self, record): pass # Create a logger, but by default, have it do nothing _log = logging.getLogger('evelink') _log.addHandler(NullHandler()) # Update the version number used in the user-agent api._user_agent = 'evelink v%s' % __version__ __all__ = [ "account", "api", "char", "constants", "corp", "eve", "map", "parsing", "server", ]
Stop script execution after output of json-data so content type header is correct.
<?php namespace ShinyGeoip\Responder; use ShinyGeoip\Core\Responder; class ApiRequestResponder extends Responder { /** * Echos short version of record as json encodes string. */ public function short() { $this->setContentTypeHeader('json'); $record = $this->get('record'); echo json_encode($record); exit; } /** * Echos the full record as json encoded string. */ public function full() { $this->setContentTypeHeader('json'); $record = $this->get('record')->jsonSerialize(); echo json_encode($record); exit; } /** * Echos a json encoded not found error message. */ public function notFound() { $this->setContentTypeHeader('json'); echo json_encode(['type' => 'error', 'msg' => 'No record found.']); exit; } }
<?php namespace ShinyGeoip\Responder; use ShinyGeoip\Core\Responder; class ApiRequestResponder extends Responder { /** * Echos short version of record as json encodes string. */ public function short() { $this->setContentTypeHeader('json'); $record = $this->get('record'); echo json_encode($record); } /** * Echos the full record as json encoded string. */ public function full() { $this->setContentTypeHeader('json'); $record = $this->get('record')->jsonSerialize(); echo json_encode($record); } /** * Echos a json encoded not found error message. */ public function notFound() { $this->setContentTypeHeader('json'); echo json_encode(['type' => 'error', 'msg' => 'No record found.']); } }
Add support for subcontexts too
<?php namespace swestcott\MonologExtension\Context\Initializer; use Behat\Behat\Context\Initializer\InitializerInterface, Behat\Behat\Context\ContextInterface; class MonologInitializer implements InitializerInterface { private $container; public function __construct($container) { $this->container = $container; } public function initialize(ContextInterface $context) { $loggerName = $this->container->getParameter('behat.monolog.logger_name'); $class = $this->container->getParameter('behat.monolog.service.class'); $def = $this->container->getDefinition('behat.monolog.logger'); $def->addArgument(get_class($context)); $logger = $this->container->get('behat.monolog.logger'); $handlers = $this->container->getParameter('behat.monolog.handlers'); // Register each configured handler with logger foreach($handlers as $name) { $handler = $this->container->get($name); $logger->pushHandler($handler); } $context->$loggerName = $logger; } public function supports(ContextInterface $context) { return ($context instanceof BehatContext); } }
<?php namespace swestcott\MonologExtension\Context\Initializer; use Behat\Behat\Context\Initializer\InitializerInterface, Behat\Behat\Context\ContextInterface; class MonologInitializer implements InitializerInterface { private $container; public function __construct($container) { $this->container = $container; } public function initialize(ContextInterface $context) { $loggerName = $this->container->getParameter('behat.monolog.logger_name'); $class = $this->container->getParameter('behat.monolog.service.class'); $def = $this->container->getDefinition('behat.monolog.logger'); $def->addArgument(get_class($context)); $logger = $this->container->get('behat.monolog.logger'); $handlers = $this->container->getParameter('behat.monolog.handlers'); // Register each configured handler with logger foreach($handlers as $name) { $handler = $this->container->get($name); $logger->pushHandler($handler); } $context->$loggerName = $logger; } public function supports(ContextInterface $context) { return get_class($context) === $this->container->getParameter('behat.context.class'); } }
Clean up code to appease jshint
// Casts a rating var rate = function (event) { "use strict"; event.preventDefault(); var star = event.target; var post = star.parentElement.parentElement.parentElement.dataset.post; var starNum = event.target.dataset.num; var oldRating = $('div[data-post=' + post + ']').attr('data-rating'); $('div[data-post=' + post + ']').attr('data-rating', starNum); var setStarHighlight = function () { console.log(oldRating); if ($(this).data("num") <= starNum) { $(this) .removeClass('fa-star-o rate-' + oldRating) .addClass('fa-star rate-' + starNum); } else { console.log(oldRating); $(this) .removeClass('fa-star rate-' + oldRating) .addClass('fa-star-o'); } }; $('div[data-post=' + post + '] .star').each(setStarHighlight); }; Template.feed.events({ 'click .star': rate });
// Casts a rating var rate = function (event) { "use strict"; event.preventDefault(); var star = event.target; var post = star.parentElement.parentElement.parentElement.dataset.post; var starNum = event.target.dataset.num; var oldRating = $('div[data-post=' + post + ']').attr('data-rating'); $('div[data-post=' + post + ']').attr('data-rating', starNum); var setStarHighlight = function () { console.log(oldRating); if ($(this).data("num") <= starNum) { $(this).removeClass('fa-star-o rate-' + oldRating).addClass('fa-star rate-' + starNum); } else { console.log(oldRating); $(this).removeClass('fa-star rate-' + oldRating).addClass('fa-star-o'); } } $('div[data-post=' + post + '] .star').each(setStarHighlight); }; Template.feed.events({ 'click .star': rate });
Use command-line arguments for paths.
#!/usr/bin/python from __future__ import print_function import sys from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.functions import desc if __name__ == "__main__": if len(sys.argv) < 3: print("Usage: sort-cluster-issue.py <input> <output>", file=sys.stderr) exit(-1) sc = SparkContext(appName='resort data') sqlContext = SQLContext(sc) df = sqlContext.read.load(sys.argv[1]) df.registerTempTable("newspaper") df2 = sqlContext.sql('select series, date, count(*) as cnt from newspaper group by series, date') df3 = df.join(df2, ['series', 'date']) df3.sort(desc("cnt"), "series", "date", "id", "begin", "end")\ .write.option('compression', 'gzip').json(sys.argv[2]) sc.stop()
#!/usr/bin/python from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql.functions import asc, desc if __name__ == "__main__": sc = SparkContext(appName='resort data') sqlContext = SQLContext(sc) df = sqlContext.read.load('hdfs://discovery3:9000/tmp/dasmith/c19-20160919-a50-o08/pretty.parquet') #df = sqlContext.read.load('hdfs://discovery3:9000/tmp/dasmith/c19-20160402-a50-o08/out.parquet') df.registerTempTable("newspaper") df2 = sqlContext.sql("select series, date, count(*) as cnt from newspaper group by series, date order by cnt desc") df3 = df.join(df2, ['series', 'date']) df3.sort(desc("cnt"), asc("begin"), asc("end"))\ .write.json('/gss_gpfs_scratch/xu.shao/network/resorted-pretty.json')
Check for an existing handler before registering default host-meta handler.
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta try: wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') except ValueError: pass # # resource model # class Resource(models.Model): path = models.CharField(max_length=128) content = models.TextField(blank=True) content_type = models.CharField(max_length=128, blank=True) class Meta: ordering = ('path',) def __unicode__(self): return self.path def save(self, **kwargs): self.path = self.path.strip('/') if not self.content_type: self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain' super(Resource, self).save(**kwargs) # # update resources when models are saved # def save_handler(sender, **kwargs): reg = kwargs['instance'] wellknown.register( reg.path, content=reg.content, content_type=reg.content_type, update=True ) post_save.connect(save_handler, sender=Resource)
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') # # resource model # class Resource(models.Model): path = models.CharField(max_length=128) content = models.TextField(blank=True) content_type = models.CharField(max_length=128, blank=True) class Meta: ordering = ('path',) def __unicode__(self): return self.path def save(self, **kwargs): self.path = self.path.strip('/') if not self.content_type: self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain' super(Resource, self).save(**kwargs) # # update resources when models are saved # def save_handler(sender, **kwargs): reg = kwargs['instance'] wellknown.register( reg.path, content=reg.content, content_type=reg.content_type, update=True ) post_save.connect(save_handler, sender=Resource)
Comment out favicon. No icon added to project
var express = require('express'); var routes = require('./routes'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hjs'); // app.use(express.favicon('public/images/fav.ico')); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/rt', routes.index); app.get('/rt/:stopid', routes.rt); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
var express = require('express'); var routes = require('./routes'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hjs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/rt', routes.index); app.get('/rt/:stopid', routes.rt); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Change canceling icon to 'spinning orange'
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' }, WORKER_CANCELING: { value: 824, text: 'Canceling', icon: 'icon-spin3 animate-spin', color: '#f89406' } });
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' }, WORKER_CANCELING: { value: 824, text: 'Canceling', icon: 'icon-cancel', color: '#f89406' } });
Remove extra Font Awesome resources
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var mergeTrees = require('broccoli-merge-trees'); var app = new EmberApp({ modals: { layout : true, style : true, animation : 'flip' }, emberCliFontAwesome: { includeFontAwesomeAssets: true }, minifyCSS: { enabled: true, options: {} }, }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. //app.import("bower_components/font-awesome/css/font-awesome.css"); module.exports = mergeTrees([app.toTree()], { overwrite: true });
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var mergeTrees = require('broccoli-merge-trees'); var app = new EmberApp({ modals: { layout : true, style : true, animation : 'flip' }, emberCliFontAwesome: { includeFontAwesomeAssets: false }, minifyCSS: { enabled: true, options: {} }, }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import("bower_components/font-awesome/css/font-awesome.css"); app.import("bower_components/font-awesome/fonts/fontawesome-webfont.woff", { destDir: "fonts" }); module.exports = mergeTrees([app.toTree()], { overwrite: true });
Add GET for idea and refactor vote
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def idea(request, pk): if request.method == 'GET': idea = Idea.objects.get(pk=pk) serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request, pk): if request.method == 'POST': idea = Idea.objects.get(pk=pk) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
from .models import Idea from .serializers import IdeaSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET',]) def idea_list(request): if request.method == 'GET': ideas = Idea.objects.all() serializer = IdeaSerializer(ideas, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['GET',]) def results(request): if request.method == 'GET': ideas_ordered = Idea.objects.order_by('-votes') serializer = IdeaSerializer(ideas_ordered, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @api_view(['POST',]) def vote(request): if request.method == 'POST': idea = Idea.objects.get(pk=request.data) idea.votes += 1 idea.save() serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)
Set default for General.output to tsstats.html
# -*- coding: utf-8 -*- try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser import logging logger = logging.getLogger('tsstats') DEFAULT_CONFIG = { 'General': { 'debug': False, 'log': '', 'output': 'tsstats.html', 'idmap': '', 'onlinedc': True, 'template': 'template.html', 'datetimeformat': '%x %X %Z' } } def load(path=None): ''' parse config at `config_path` :param config_path: path to config-file :type config_path: str :return: values of config :rtype: tuple ''' logger.debug('reading config') config = RawConfigParser() # use this way to set defaults, because ConfigParser.read_dict # is not available < 3.2 for section, items in DEFAULT_CONFIG.items(): if section not in config.sections(): config.add_section(section) for key, value in items.items(): config.set(section, key, str(value)) if path: config.read(path) return config
# -*- coding: utf-8 -*- try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser import logging logger = logging.getLogger('tsstats') DEFAULT_CONFIG = { 'General': { 'debug': False, 'log': '', 'output': 'output.html', 'idmap': '', 'onlinedc': True, 'template': 'template.html', 'datetimeformat': '%x %X %Z' } } def load(path=None): ''' parse config at `config_path` :param config_path: path to config-file :type config_path: str :return: values of config :rtype: tuple ''' logger.debug('reading config') config = RawConfigParser() # use this way to set defaults, because ConfigParser.read_dict # is not available < 3.2 for section, items in DEFAULT_CONFIG.items(): if section not in config.sections(): config.add_section(section) for key, value in items.items(): config.set(section, key, str(value)) if path: config.read(path) return config
Put min/max constraints on sidecar.port
/* * Copyright 2013-2015 the original author or 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 org.springframework.cloud.netflix.sidecar; import java.net.URI; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author Spencer Gibb */ @Data @ConfigurationProperties("sidecar") public class SidecarProperties { private URI healthUri; private URI homePageUri; @Max(65535) @Min(1) private int port; }
/* * Copyright 2013-2015 the original author or 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 org.springframework.cloud.netflix.sidecar; import java.net.URI; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author Spencer Gibb */ @Data @ConfigurationProperties("sidecar") public class SidecarProperties { private URI healthUri; private URI homePageUri; private int port; }
Check if the settings exist before kicking of headless chrome.
const PuppeteerDynamics365 = require('./puppeteerdynamics365'); require('dotenv').config(); (async () => { let missingSettings = ['CRM_URL','TAB_HOME','USER_SELECTOR','USER_NAME','PASSWORD_SELECTOR','PASSWORD','LOGIN_SUBMIT_SELECTOR','RUN_SHEET_FILE'] .filter(s=>!process.env[s]); if(missingSettings.length > 0){ console.log('Check if the .env file exists and the following settings exist\r\n---------------------------------'); console.log(missingSettings); return; } const pup = new PuppeteerDynamics365(process.env.CRM_URL); try{ let groups = await pup.start(); // let subgroups = await pup.navigateToGroup(groups, 'Settings'); // let commands = await pup.navigateToSubgroup(subgroups, 'Administration', {annotateText:'Administration area'}); // subgroups = await pup.navigateToGroup(groups, 'Marketing'); // commands = await pup.navigateToSubgroup(subgroups, 'Leads', {annotateText:'View all existing active leads'}); // await pup.clickCommandBarButton(commands, 'NEW', {annotateText:'Create new lead', fileName: 'Create new lead'}); // let attributes = await pup.getAttributes(); // console.log(attributes); }catch(e){ console.log(e); } pup.exit(); })();
const PuppeteerDynamics365 = require('./puppeteerdynamics365'); require('dotenv').config(); (async () => { const pup = new PuppeteerDynamics365(process.env.CRM_URL); try{ let groups = await pup.start(); // let subgroups = await pup.navigateToGroup(groups, 'Settings'); // let commands = await pup.navigateToSubgroup(subgroups, 'Administration', {annotateText:'Administration area'}); // subgroups = await pup.navigateToGroup(groups, 'Marketing'); // commands = await pup.navigateToSubgroup(subgroups, 'Leads', {annotateText:'View all existing active leads'}); // await pup.clickCommandBarButton(commands, 'NEW', {annotateText:'Create new lead', fileName: 'Create new lead'}); // let attributes = await pup.getAttributes(); // console.log(attributes); }catch(e){ console.log(e); } pup.exit(); })();
Set debugger webpack test config to development mode
const path = require("path"); const webpack = require("webpack"); const merge = require("webpack-merge"); const WriteFilePlugin = require("write-file-webpack-plugin"); const commonConfig = require("./webpack.config-common.js"); module.exports = merge(commonConfig, { mode: "development", module: { rules: [ { test: /\.(js)/, include: path.resolve("lib"), loader: "istanbul-instrumenter-loader" }, { test: /\.js$/, loader: "babel-loader", query: { presets: [["babel-preset-env", { targets: { node: "6.14" } }]], plugins: ["transform-object-rest-spread", "transform-runtime"] }, include: [ path.resolve(__dirname, "..", "lib"), path.resolve(__dirname, "..", "test") ] } ] }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("test") }), new WriteFilePlugin() ] });
const path = require("path"); const webpack = require("webpack"); const merge = require("webpack-merge"); const WriteFilePlugin = require("write-file-webpack-plugin"); const commonConfig = require("./webpack.config-common.js"); module.exports = merge(commonConfig, { module: { rules: [ { test: /\.(js)/, include: path.resolve("lib"), loader: "istanbul-instrumenter-loader" }, { test: /\.js$/, loader: "babel-loader", query: { presets: [["babel-preset-env", { targets: { node: "6.14" } }]], plugins: ["transform-object-rest-spread", "transform-runtime"] }, include: [ path.resolve(__dirname, "..", "lib"), path.resolve(__dirname, "..", "test") ] } ] }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("test") }), new WriteFilePlugin() ] });
Use camelCase for javascript variable names.
$(document).ready(function () { var contentContainer = $('.js-fixed-content-top') if (contentContainer.length > 0) { var top = $('.js-fixed-content-top').offset().top - parseFloat($('.js-fixed-content-top').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { // what the y position of the scroll is var y = $(this).scrollTop(); // whether that's below if (y >= top) { // if so, ad the fixed class $('.js-fixed-content-top').addClass('content-fixed'); } else { // otherwise remove it $('.js-fixed-content-top').removeClass('content-fixed'); } }); }; });
$(document).ready(function () { var contents_container = $('.js-fixed-content-top') if (contents_container.length > 0) { var top = $('.js-fixed-content-top').offset().top - parseFloat($('.js-fixed-content-top').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { // what the y position of the scroll is var y = $(this).scrollTop(); // whether that's below if (y >= top) { // if so, ad the fixed class $('.js-fixed-content-top').addClass('content-fixed'); } else { // otherwise remove it $('.js-fixed-content-top').removeClass('content-fixed'); } }); }; });
Move location of server start in conference
'use strict'; require('dotenv').config({path: __dirname + '/../.env'}); const NEXMO_FROM_NUMBER = process.env.NEXMO_FROM_NUMBER; const NEXMO_TO_NUMBER = process.env.NEXMO_TO_NUMBER; const app = require('express')(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/answer', (req, res) => { const ncco = [ { action: 'talk', text: 'Welcome to a Nexmo powered conference call' }, { action: 'conversation', name: 'nexmo-conference' } ]; res.json(ncco); }); app.post('/events', (req, res) => { console.log(req.body); res.status(204).end(); }); const server = app.listen(process.env.PORT || 4004, () => { console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env); });
'use strict'; require('dotenv').config({path: __dirname + '/../.env'}); const NEXMO_FROM_NUMBER = process.env.NEXMO_FROM_NUMBER; const NEXMO_TO_NUMBER = process.env.NEXMO_TO_NUMBER; const app = require('express')(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const server = app.listen(process.env.PORT || 4004, () => { console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env); }); app.get('/answer', (req, res) => { const ncco = [ { action: 'talk', text: 'Welcome to a Nexmo powered conference call' }, { action: 'conversation', name: 'nexmo-conference' } ]; res.json(ncco); }); app.post('/events', (req, res) => { console.log(req.body); res.status(204).end(); });
Update nullables and unused import
/** * Copyright 2015 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.config; import java.io.File; import java.io.IOException; import javax.annotation.Nullable; public final class AtlasDbConfigs { public static final String ATLASDB_CONFIG_ROOT = "/atlasdb"; private AtlasDbConfigs() { // uninstantiable } public static AtlasDbConfig load(File configFile) throws IOException { return load(configFile, ATLASDB_CONFIG_ROOT); } public static AtlasDbConfig load(File configFile, @Nullable String configRoot) throws IOException { ConfigFinder finder = new ConfigFinder(configRoot); return finder.getConfig(configFile); } public static AtlasDbConfig loadFromString(String fileContents, @Nullable String configRoot) throws IOException { ConfigFinder finder = new ConfigFinder(configRoot); return finder.getConfig(fileContents); } }
/** * Copyright 2015 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.config; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.JsonNode; public final class AtlasDbConfigs { public static final String ATLASDB_CONFIG_ROOT = "/atlasdb"; private AtlasDbConfigs() { // uninstantiable } public static AtlasDbConfig load(File configFile) throws IOException { return load(configFile, ATLASDB_CONFIG_ROOT); } public static AtlasDbConfig load(File configFile, String configRoot) throws IOException { ConfigFinder finder = new ConfigFinder(configRoot); return finder.getConfig(configFile); } public static AtlasDbConfig loadFromString(String fileContents, String configRoot) throws IOException { ConfigFinder finder = new ConfigFinder(configRoot); return finder.getConfig(fileContents); } }
Clean up $pre parameter description
<?php /* * Layout functions */ // `is_currentfile` // // Checks for current file. Returns boolean. function is_currentfile($file) { if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) { return true; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. // $pre => preformat feed contents, must be a boolean function feedparse($url, $pre = false) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); if ($pre) { echo '<pre>'; } echo $data; if ($pre) { echo '</pre>'; } } // `selectrandom` // // Selects a random value from array. function selectrandom($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { echo str_replace('.', '', $string); }
<?php /* * Layout functions */ // `is_currentfile` // // Checks for current file. Returns boolean. function is_currentfile($file) { if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) { return true; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. // $pre => preformat feed contents or no, must be a boolean function feedparse($url, $pre = false) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); if ($pre) { echo '<pre>'; } echo $data; if ($pre) { echo '</pre>'; } } // `selectrandom` // // Selects a random value from array. function selectrandom($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { echo str_replace('.', '', $string); }
Fix bug where folders don't show up in "save as" dialog, preventing navigation into subfolders git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@13067 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2006, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307, USA */ package edu.umd.cs.findbugs.gui2; import java.io.File; public final class FindBugsAnalysisFileFilter extends FindBugsFileFilter { public static final FindBugsAnalysisFileFilter INSTANCE = new FindBugsAnalysisFileFilter(); @Override public boolean accept(File arg0) { return arg0.getName().endsWith(".xml") || arg0.getName().endsWith(".xml.gz") || arg0.isDirectory(); } @Override public String getDescription() { return "FindBugs analysis results (.xml, *.xml.gz)"; } @Override SaveType getSaveType() { return SaveType.XML_ANALYSIS; } }
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2006, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307, USA */ package edu.umd.cs.findbugs.gui2; import java.io.File; public final class FindBugsAnalysisFileFilter extends FindBugsFileFilter { public static final FindBugsAnalysisFileFilter INSTANCE = new FindBugsAnalysisFileFilter(); @Override public boolean accept(File arg0) { boolean accept = arg0.getName().endsWith(".xml") || arg0.getName().endsWith(".xml.gz"); return accept; } @Override public String getDescription() { return "FindBugs analysis results (.xml)"; } @Override SaveType getSaveType() { return SaveType.XML_ANALYSIS; } }
Set 'Add Session' time to current time (& date). When adding a new session it's most often because I missed starting one. This means I then have to set the session time to the current time instead of it (previously, by default) arbitrarily being set to 9am of today.
/* * Copyright 2016-2019 Adrian Cotfas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.apps.adrcotfas.goodtime.Statistics.AllSessions; import org.joda.time.DateTime; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class AddEditEntryDialogViewModel extends ViewModel { public static int INVALID_SESSION_TO_EDIT_ID = -1; public MutableLiveData<Integer> duration = new MutableLiveData<>(); public MutableLiveData<DateTime> date = new MutableLiveData<>(); public MutableLiveData<String> label = new MutableLiveData<>(); public long sessionToEditId; public AddEditEntryDialogViewModel() { date.setValue(new DateTime()); label.setValue(null); sessionToEditId = INVALID_SESSION_TO_EDIT_ID; } }
/* * Copyright 2016-2019 Adrian Cotfas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.apps.adrcotfas.goodtime.Statistics.AllSessions; import org.joda.time.DateTime; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class AddEditEntryDialogViewModel extends ViewModel { public static int INVALID_SESSION_TO_EDIT_ID = -1; public MutableLiveData<Integer> duration = new MutableLiveData<>(); public MutableLiveData<DateTime> date = new MutableLiveData<>(); public MutableLiveData<String> label = new MutableLiveData<>(); public long sessionToEditId; public AddEditEntryDialogViewModel() { date.setValue(new DateTime().withHourOfDay(9).withMinuteOfHour(0)); label.setValue(null); sessionToEditId = INVALID_SESSION_TO_EDIT_ID; } }
Fix logger observer: create const chanLoggerObserverEventsBuffer
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/world" ) const chanLoggerObserverEventsBuffer = 32 type LoggerObserver struct{} func (LoggerObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { for event := range w.Events(stop, chanLoggerObserverEventsBuffer) { switch event.Type { case world.EventTypeError: if err, ok := event.Payload.(error); ok { logger.WithError(err).Error("world error") } case world.EventTypeObjectCreate, world.EventTypeObjectDelete, world.EventTypeObjectUpdate, world.EventTypeObjectChecked: logger.WithFields(logrus.Fields{ "payload": event.Payload, "type": event.Type, }).Debug("world event") } } }() }
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/world" ) type LoggerObserver struct{} func (LoggerObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { for event := range w.Events(stop, chanSnakeObserverEventsBuffer) { switch event.Type { case world.EventTypeError: if err, ok := event.Payload.(error); ok { logger.WithError(err).Error("world error") } case world.EventTypeObjectCreate, world.EventTypeObjectDelete, world.EventTypeObjectUpdate, world.EventTypeObjectChecked: logger.WithFields(logrus.Fields{ "payload": event.Payload, "type": event.Type, }).Debug("world event") } } }() }
Remove bump task from gulp file
/*globals require, __dirname */ /* jshint node:true */ 'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var karma = require('karma').server; var plato = require('gulp-plato'); var karmaConfig = __dirname + '/karma.conf.js'; var paths = require('./paths'); gulp.task('complexity', function () { return gulp.src('src/**/*.js') .pipe(plato('complexity')); }); gulp.task('test', function (done) { karma.start({ configFile: karmaConfig, singleRun: true, reporters: ['progress', 'coverage', 'threshold'] }, done); }); gulp.task('tdd', function (done) { gulp.watch(paths.all, ['lint']); karma.start({ configFile: paths.karmaConfig }, done); }); gulp.task('lint', function () { return gulp .src(paths.lint) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('default', { verbose: true })) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('default', ['lint', 'complexity', 'test']);
/*globals require, __dirname */ /* jshint node:true */ 'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var karma = require('karma').server; var bump = require('gulp-bump'); var plato = require('gulp-plato'); var karmaConfig = __dirname + '/karma.conf.js'; var paths = require('./paths'); gulp.task('bump', function () { return gulp.src(paths.bump) .pipe(bump()) .pipe(gulp.dest('./')); }); gulp.task('complexity', function () { return gulp.src('src/**/*.js') .pipe(plato('complexity')); }); gulp.task('test', function (done) { karma.start({ configFile: karmaConfig, singleRun: true, reporters: ['progress', 'coverage', 'threshold'] }, done); }); gulp.task('tdd', function (done) { gulp.watch(paths.all, ['lint']); karma.start({ configFile: paths.karmaConfig }, done); }); gulp.task('lint', function () { return gulp .src(paths.lint) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('default', { verbose: true })) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('default', ['lint', 'complexity', 'test']);
Fix banning to insert to correct table
exports.name = 'banuser'; exports.hidden = true; exports.enabled = true; exports.matchStart = true; exports.handler = function(data) { //my room is idiots //if (config.database.usedb && admincheck(data.userid)) { if (config.database.usedb && data.userid == config.admin) { //Get name and userid var givenname = data.text.substring(8); client.query('SELECT userid FROM (SELECT * FROM ' + config.database.dbname + '.' + config.database.tablenames.user + ' WHERE username LIKE ?) a ORDER BY lastseen DESC', [givenname], function select(error, results, fields) { if (results != null && results.length > 0) { addToBanList(results[0]['userid'], givenname, data.name); } }); } } function addToBanList(userid, name, bannedby) { client.query('INSERT INTO ' + config.database.dbname + '.' + config.database.tablenames.banned + ' SET userid = ?, banned_by = ?, timestamp = NOW()', [userid, bannedby]); bot.speak(name + ' (UID ' + userid + ') has been banned by ' + bannedby + '.'); bot.boot(userid, 'You have been banned by ' + bannedby + '.'); }
exports.name = 'banuser'; exports.hidden = true; exports.enabled = true; exports.matchStart = true; exports.handler = function(data) { //my room is idiots //if (config.database.usedb && admincheck(data.userid)) { if (config.database.usedb && data.userid == config.admin) { //Get name and userid var givenname = data.text.substring(8); client.query('SELECT userid FROM (SELECT * FROM ' + config.database.dbname + '.' + config.database.tablenames.user + ' WHERE username LIKE ?) a ORDER BY lastseen DESC', [givenname], function select(error, results, fields) { if (results != null && results.length > 0) { addToBanList(results[0]['userid'], givenname, data.name); } }); } } function addToBanList(userid, name, bannedby) { client.query('INSERT INTO ' + config.database.dbname + '.' + config.database.tablenames.user + ' SET userid = ?, banned_by = ?, timestamp = NOW()', [userid, bannedby]); bot.speak(name + ' (UID ' + userid + ') has been banned by ' + bannedby + '.'); bot.boot(userid, 'You have been banned by ' + bannedby + '.'); }
Create link to individual posts
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; import _ from 'lodash'; class PostsIndex extends Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, post => { return ( <li className="list-group-item" key={post.id}> <Link to={`/posts/${post.id}`}> {post.title} </Link> </li> ); }); } render() { return( <div> <div className="text-xs-right"> <Link className="btn btn-primary" to="/posts/new"> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> {this.renderPosts()} </ul> </div> ); } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; import _ from 'lodash'; class PostsIndex extends Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, post => { return ( <li className="list-group-item" key={post.id}>{post.title}</li> ); }); } render() { return( <div> <div className="text-xs-right"> <Link className="btn btn-primary" to="/posts/new"> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> {this.renderPosts()} </ul> </div> ); } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
Fix bad refactor of is_valid_unc_path
from win_unc.internal.utils import take_while from win_unc.sanitizors import sanitize_username, sanitize_unc_path def is_valid_drive_letter(string): """ Drive letters are one character in length and between "A" and "Z". Case does not matter. """ return (len(string) == 1 and string[0].isalpha()) def is_valid_unc_path(string): """ Valid UNC paths are at least three characters long, begin with exactly two backslashes, not start or end with whitepsace, and do not contain certain invalid characters (see `sanitize_unc_path`). """ return (len(string) > 2 and len(take_while(lambda c: c == '\\', string)) == 2 and string == string.strip() and string == sanitize_unc_path(string)) def is_valid_username(string): """ A valid Windows username (logon) is a non-empty string that does not start or end with whitespace, and does not contain certain invalid characters (see `sanitize_username`). """ return (len(string) > 0 and string == string.strip() and string == sanitize_username(string))
from win_unc.sanitizors import sanitize_username, sanitize_unc_path def is_valid_drive_letter(string): """ Drive letters are one character in length and between "A" and "Z". Case does not matter. """ return (len(string) == 1 and string[0].isalpha()) def is_valid_unc_path(string): """ Valid UNC paths are at least three characters long, begin with "\\", do not start or end with whitepsace, and do not contain certain invalid characters (see `sanitize_unc_path`). """ return (len(string) > 2 and string.startswith('\\\\') and string == string.strip() and string == sanitize_unc_path(string)) def is_valid_username(string): """ A valid Windows username (logon) is a non-empty string that does not start or end with whitespace, and does not contain certain invalid characters (see `sanitize_username`). """ return (len(string) > 0 and string == string.strip() and string == sanitize_username(string))
Add some new default settings
# Web server DEBUG = True HOST = '127.0.0.1' PORT = 5000 TEMPLATE = 'flot.html' SITE_TITLE = "UA Sensors Visualization" # Database location SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3' # Sensor type mapping # # - First parameter is the identifier sent from sensors in the wild # - Second parameter is the readable name of the sensor type # - Third parameter is the types of readings returned # - Semi-colon separates different sensor reading types # - Each reading type needs to specify type and unit of measurement # - For, example TYPE UNITS; TYPE UNITS -> distance meters; temperature celsius SENSOR_TYPES = ( ("d", "Water", "distance meters; temperature celsius"), ("g", "Gate", "distance meters"), ("s", "Soil", "moisture percent; temperature celsius"), ) # Maps sensor ids to more informative name. # # Not all sensors need to be named. Can be adjusted later, just remember to # restart server on config file updates # # For instance, +12223334444 is not as informative as Campbell Creek Water Sensor # # Example format: # # SENSOR_NAMES = { # '+12223334444': 'Yosemite Distance Sensor', # '+01234567890': 'Siberia Gate Sensor', # 'moteino_1': 'Arctic Ocean Moisture Sensor', # } SENSOR_NAMES = {} # Data logger error logging DATA_LOGGER_ERROR_FILE = 'log/ua_sensor.log' DATA_LOGGER_ERROR_LEVEL = 'INFO' DATA_LOGGER_ERROR_FORMAT = '%(levelname)s - %(message)s'
# Web server DEBUG = True HOST = '127.0.0.1' PORT = 5000 TEMPLATE = 'flot.html' # Database location SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3' # Sensor type mapping # # - First parameter is the identifier sent from sensors in the wild # - Second parameter is the readable name of the sensor type # - Third parameter is the types of readings returned # - Semi-colon separates different sensor reading types # - Each reading type needs to specify type and unit of measurement # - For, example TYPE UNITS; TYPE UNITS -> distance meters; temperature celsius SENSOR_TYPES = ( ("d", "Water", "distance meters; temperature celsius"), ("g", "Gate", "distance meters"), ("s", "Soil", "moisture percent; temperature celsius"), ) # Data logger error logging DATA_LOGGER_ERROR_FILE = 'log/ua_sensor.log' DATA_LOGGER_ERROR_LEVEL = 'INFO' DATA_LOGGER_ERROR_FORMAT = '%(levelname)s - %(message)s'
Replace deprecated @Cucumber.Options with @CucumberOptions
/** * 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 domainapp.integtests.specs; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; /** * Runs scenarios in all <tt>.feature</tt> files (this package and any subpackages). */ @RunWith(Cucumber.class) @CucumberOptions( format = { "html:target/cucumber-html-report" ,"json:target/cucumber.json" }, glue={"classpath:domainapp.integtests.specglue"}, strict = true, tags = { "~@backlog", "~@ignore" }) public class RunSpecs { // intentionally empty }
/** * 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 domainapp.integtests.specs; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; /** * Runs scenarios in all <tt>.feature</tt> files (this package and any subpackages). */ @RunWith(Cucumber.class) @Cucumber.Options( format = { "html:target/cucumber-html-report" ,"json:target/cucumber.json" }, glue={"classpath:domainapp.integtests.specglue"}, strict = true, tags = { "~@backlog", "~@ignore" }) public class RunSpecs { // intentionally empty }
Add ignores for certain lifecycle hooks in EventListener component
import {PureComponent as Component} from 'react' import PropTypes from 'prop-types' import {addEventListener, removeEventListener} from '@shopify/javascript-utilities/events' const propTypes = { event: PropTypes.string, capture: PropTypes.bool, passive: PropTypes.bool, handler: PropTypes.func } // see https://github.com/oliviertassinari/react-event-listener/ class EventListener extends Component { constructor () { super() this.attachListener = this.attachListener.bind(this) this.detachListener = this.detachListener.bind(this) } componentDidMount () { this.attachListener() } /* istanbul ignore next */ componentWillUpdate () { this.detachListener() } /* istanbul ignore next */ componentDidUpdate () { this.attachListener() } componentWillUnmount () { this.detachListener() } attachListener () { const {event, handler, capture, passive} = this.props addEventListener(window, event, handler, {capture, passive}) } detachListener () { const {event, handler, capture} = this.props removeEventListener(window, event, handler, capture) } render () { return null } } EventListener.propTypes = propTypes export default EventListener
import {PureComponent as Component} from 'react' import PropTypes from 'prop-types' import {addEventListener, removeEventListener} from '@shopify/javascript-utilities/events' const propTypes = { event: PropTypes.string, capture: PropTypes.bool, passive: PropTypes.bool, handler: PropTypes.func } // see https://github.com/oliviertassinari/react-event-listener/ class EventListener extends Component { constructor () { super() this.attachListener = this.attachListener.bind(this) this.detachListener = this.detachListener.bind(this) } componentDidMount () { this.attachListener() } componentWillUpdate () { this.detachListener() } componentDidUpdate () { this.attachListener() } componentWillUnmount () { this.detachListener() } attachListener () { const {event, handler, capture, passive} = this.props addEventListener(window, event, handler, {capture, passive}) } detachListener () { const {event, handler, capture} = this.props removeEventListener(window, event, handler, capture) } render () { return null } } EventListener.propTypes = propTypes export default EventListener
Use `error` in both cases, instead of `errors` sometimes
'use strict'; var Compiler = require('traceur').NodeCompiler , xtend = require('xtend') ; var traceurOptions = { modules : 'commonjs', sourceMaps : true }; exports = module.exports = function compileFile(file, contents, traceurOverrides) { var options = xtend(traceurOptions, traceurOverrides); if (typeof options.sourceMap !== 'undefined') { console.warn('es6ify: DEPRECATED options.sourceMap has changed to options.sourceMaps (plural)'); options.sourceMaps = options.sourceMap; delete options.sourceMap; } try{ var compiler = new Compiler(options); var result = compiler.compile(contents, file); var sourceMap = compiler.getSourceMap(); }catch(errors){ return { source: null, sourcemap: null, error: errors[0] }; } return { source: result, error: null, sourcemap: sourceMap ? JSON.parse(sourceMap) : null }; };
'use strict'; var Compiler = require('traceur').NodeCompiler , xtend = require('xtend') ; var traceurOptions = { modules : 'commonjs', sourceMaps : true }; exports = module.exports = function compileFile(file, contents, traceurOverrides) { var options = xtend(traceurOptions, traceurOverrides); if (typeof options.sourceMap !== 'undefined') { console.warn('es6ify: DEPRECATED options.sourceMap has changed to options.sourceMaps (plural)'); options.sourceMaps = options.sourceMap; delete options.sourceMap; } try{ var compiler = new Compiler(options); var result = compiler.compile(contents, file); var sourceMap = compiler.getSourceMap(); }catch(errors){ return { source: null, sourcemap: null, error: errors[0] }; } return { source: result, errors: null, sourcemap: sourceMap ? JSON.parse(sourceMap) : null }; };
Fix unicode error caused by ascii format string
from __future__ import absolute_import, unicode_literals from django.forms.widgets import Widget from django.utils.safestring import mark_safe class WidgetWithScript(Widget): def render(self, name, value, attrs=None): widget = super(WidgetWithScript, self).render(name, value, attrs) final_attrs = self.build_attrs(attrs, name=name) id_ = final_attrs.get('id', None) if 'id_' is None: return widget js = self.render_js_init(id_, name, value) out = '{0}<script>{1}</script>'.format(widget, js) return mark_safe(out) def render_js_init(self, id_, name, value): return ''
from django.forms.widgets import Widget from django.utils.safestring import mark_safe class WidgetWithScript(Widget): def render(self, name, value, attrs=None): widget = super(WidgetWithScript, self).render(name, value, attrs) final_attrs = self.build_attrs(attrs, name=name) id_ = final_attrs.get('id', None) if 'id_' is None: return widget js = self.render_js_init(id_, name, value) out = '{0}<script>{1}</script>'.format(widget, js) return mark_safe(out) def render_js_init(self, id_, name, value): return ''
Put environment name into environment.
""" Support for multiple environments based on python configuration files. """ from __future__ import print_function, absolute_import import os from twisted.python.filepath import FilePath from fabric.api import env, task from braid.settings import ENVIRONMENTS CONFIG_DIRS = [ '~/.config/braid', ] #FIXME: How to handle module level initialization here? def loadEnvironmentConfig(envFile): """ Loads configuration directives for the specified environment into Fabric's C{env} variable. This function tries to load a python module from each specified directory and stores all of its public uppercase attributes as attributes of Fabric's environment (all attribute names will be lowercased). """ envName = os.path.splitext(envFile.basename())[0] ENVIRONMENTS.setdefault(envName, {}) glob = { '__file__': envFile.path } exec envFile.getContent() in glob ENVIRONMENTS[envName].update(glob['ENVIRONMENT']) def loadEnvironments(directories=CONFIG_DIRS): for directory in directories: confDir = FilePath(os.path.expanduser(directory)) for envFile in confDir.globChildren('*.env'): loadEnvironmentConfig(envFile) loadEnvironments() def environment(envName): """ Load the passed environment configuration. This task can be invoked before executing the desired Fabric action. """ env.update(ENVIRONMENTS[envName]) env['environment'] = envName for envName in ENVIRONMENTS: globals()[envName] = task(name=envName)(lambda: environment(envName))
""" Support for multiple environments based on python configuration files. """ from __future__ import print_function, absolute_import import os from twisted.python.filepath import FilePath from fabric.api import env, task from braid.settings import ENVIRONMENTS CONFIG_DIRS = [ '~/.config/braid', ] def loadEnvironmentConfig(envFile): """ Loads configuration directives for the specified environment into Fabric's C{env} variable. This function tries to load a python module from each specified directory and stores all of its public uppercase attributes as attributes of Fabric's environment (all attribute names will be lowercased). """ envName = os.path.splitext(envFile.basename())[0] ENVIRONMENTS.setdefault(envName, {}) glob = { '__file__': envFile.path } exec envFile.getContent() in glob ENVIRONMENTS[envName].update(glob['ENVIRONMENT']) def loadEnvironments(directories=CONFIG_DIRS): for directory in directories: confDir = FilePath(os.path.expanduser(directory)) for envFile in confDir.globChildren('*.env'): loadEnvironmentConfig(envFile) loadEnvironments() def environment(envName): """ Load the passed environment configuration. This task can be invoked before executing the desired Fabric action. """ env.update(ENVIRONMENTS[envName]) for envName in ENVIRONMENTS: globals()[envName] = task(name=envName)(lambda: environment(envName))
Add disable/enable methods to Parallax3D
export default class Parallax3D { constructor(element, initialTransform) { this.elem = element; this.initialTransform = initialTransform; this.rotmax = 10; window.addEventListener('mousemove', e => this.update(e)); } /** Get mouse coordinates on the screen in range [-1, 1] */ static getMouse(e) { const w = window.innerWidth; const h = window.innerHeight; const halfw = w / 2; const halfh = h / 2; const x = e.clientX; const y = e.clientY; const finalx = (x - halfw) / halfw; const finaly = (y - halfh) / halfh; return [finalx, finaly]; } /** Adjust rotation based on values from -1 to 1 */ rotate(rotx, roty) { this.elem.style.transform = [ this.initialTransform, `rotateX(${rotx * this.rotmax}deg)`, `rotateY(${roty * this.rotmax}deg)`, ].join(' '); } /** Update rotation from a mouse event */ update(e) { if (!this.disabled) { // Flip mouse position and rotate by that amount this.rotate(...Parallax3D.getMouse(e).map(n => -n).reverse()); } } disable() { this.disabled = true; this.rotate(0, 0); } enable() { this.disabled = false; } }
export default class Parallax3D { constructor(element, initialTransform) { this.elem = element; this.initialTransform = initialTransform; this.rotmax = 10; window.addEventListener('mousemove', e => this.update(e)); } /** Get mouse coordinates on the screen in range [-1, 1] */ static getMouse(e) { const w = window.innerWidth; const h = window.innerHeight; const halfw = w / 2; const halfh = h / 2; const x = e.clientX; const y = e.clientY; const finalx = (x - halfw) / halfw; const finaly = (y - halfh) / halfh; return [finalx, finaly]; } /** Adjust rotation based on values from -1 to 1 */ rotate(rotx, roty) { this.elem.style.transform = [ this.initialTransform, `rotateX(${rotx * this.rotmax}deg)`, `rotateY(${roty * this.rotmax}deg)`, ].join(' '); } /** Update rotation from a mouse event */ update(e) { // Flip mouse position and rotate by that amount this.rotate(...Parallax3D.getMouse(e).map(n => -n).reverse()); } }
Upgrade to an EditorFactory, so Custom, Text, and Readonly can be written.
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ import datetime from enthought.traits.traits import Property from enthought.traits.ui.editor_factory import EditorFactory from enthought.traits.ui.toolkit import toolkit_object #-- DateEditor definition ----------------------------------------------------- class DateEditor ( EditorFactory ): """ Editor factory for date/time editors. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- # TODO: Placeholder for date-editor-specific traits. pass #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ import datetime from enthought.traits.traits import Property from enthought.traits.ui.basic_editor_factory import BasicEditorFactory from enthought.traits.ui.toolkit import toolkit_object #-- DateEditor definition ----------------------------------------------------- class DateEditor ( BasicEditorFactory ): """ Editor factory for date/time editors. Generates _DateEditor()s. """ # The editor class to be created: klass = Property #--------------------------------------------------------------------------- # Property getters #--------------------------------------------------------------------------- def _get_klass(self): """ Returns the editor class to be created. """ return toolkit_object('date_editor:_DateEditor') #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
Fix bug where timezone was not used for xaxis.
from __future__ import print_function, division import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np _to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf) def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs): """Plot function for series which is about 5 times faster than pd.Series.plot(). Parameters ---------- ax : matplotlib Axes, optional If not provided then will generate our own axes. label : str, optional The label for the plotted line. The caller is responsible for enabling the legend. date_format : str, optional, default='%d/%m/%y %H:%M:%S' """ if ax is None: fig, ax = plt.subplots(1) x = _to_ordinalf_np_vectorized(series.index.to_pydatetime()) ax.plot(x, series, label=label, **kwargs) ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format, tz=series.index.tzinfo)) ax.set_ylabel('watts') fig.autofmt_xdate() plt.draw() return ax
from __future__ import print_function, division import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np _to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf) def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs): """Plot function for series which is about 5 times faster than pd.Series.plot(). Parameters ---------- ax : matplotlib Axes, optional If not provided then will generate our own axes. label : str, optional The label for the plotted line. The caller is responsible for enabling the legend. date_format : str, optional, default='%d/%m/%y %H:%M:%S' """ if ax is None: ax = plt.gca() ax.xaxis.axis_date(tz=series.index.tzinfo) ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format)) x = _to_ordinalf_np_vectorized(series.index.to_pydatetime()) ax.plot(x, series, label=label, **kwargs) ax.set_ylabel('watts') return ax
Add link to MapConfig spec
var Crypto = require('crypto'); // Map configuration object /// API: Create MapConfig from configuration object // /// @param obj js MapConfiguration object, see /// http://github.com/CartoDB/Windshaft/wiki/MapConfig-specification /// function MapConfig(cfg) { // TODO: check configuration ? // TODO: inject defaults ? this._cfg = cfg; } var o = MapConfig.prototype; o._md5 = function(s) { return Crypto.createHash('md5').update(s).digest('hex'); }; /// API: Get serialized version of this MapConfig o.serialize = function() { return JSON.stringify(this._cfg); }; /// API: Get identifier for this MapConfig o.id = function() { return this._md5(this.serialize()); } /// API: Get configuration object of this MapConfig o.obj = function() { return this._cfg; } /// API: Get type string of given layer // /// @param num layer index (0-based) /// @returns a type string, as read from the layer /// o.layerType = function(num) { var lyr = this.getLayer(num); if ( ! lyr ) return undefined; var typ = lyr.type; if ( ! typ || typ == 'cartodb' ) typ = 'mapnik'; // TODO: check validity of other types ? return typ; } /// API: Get layer by index // /// @returns undefined on invalid index /// o.getLayer = function(num) { return this._cfg.layers[num]; } module.exports = MapConfig;
var Crypto = require('crypto'); // Map configuration object /// API: Create MapConfig from configuration object // /// @param obj js MapConfiguration object /// function MapConfig(cfg) { // TODO: check configuration ? this._cfg = cfg; } var o = MapConfig.prototype; o._md5 = function(s) { return Crypto.createHash('md5').update(s).digest('hex'); }; /// API: Get serialized version of this MapConfig o.serialize = function() { return JSON.stringify(this._cfg); }; /// API: Get identifier for this MapConfig o.id = function() { return this._md5(this.serialize()); } /// API: Get configuration object of this MapConfig o.obj = function() { return this._cfg; } /// API: Get type string of given layer // /// @param num layer index (0-based) /// @returns a type string, as read from the layer /// o.layerType = function(num) { var lyr = this.getLayer(num); if ( ! lyr ) return undefined; var typ = lyr.type; if ( ! typ || typ == 'cartodb' ) typ = 'mapnik'; // TODO: check validity of other types ? return typ; } /// API: Get layer by index // /// @returns undefined on invalid index /// o.getLayer = function(num) { return this._cfg.layers[num]; } module.exports = MapConfig;
Update docs for row constructor
import Ember from 'ember'; /** * @module Classes * @class Row */ export default class Row extends Ember.ObjectProxy.extend({ /** * @property hidden * @type {Boolean} * @default false */ hidden: false, /** * @property expanded * @type {Boolean} * @default false */ expanded: false, /** * @property selected * @type {Boolean} * @default false */ selected: false, /** * Class names to be applied to this row * * @property classNames * @type {String | Array} */ classNames: null, }) { /** * @class Row * @constructor * @param {Object} content * @param {Object} options */ constructor(content, options = {}) { if (content instanceof Row) { return content; } super(); this.setProperties(options); this.set('content', content); } }
import Ember from 'ember'; /** * @module Classes * @class Row */ export default class Row extends Ember.ObjectProxy.extend({ /** * @property hidden * @type {Boolean} * @default false */ hidden: false, /** * @property expanded * @type {Boolean} * @default false */ expanded: false, /** * @property selected * @type {Boolean} * @default false */ selected: false, /** * Class names to be applied to this row * * @property classNames * @type {String | Array} */ classNames: null, }) { /** * @class Row * @constructor * @param {Object} content */ constructor(content, options = {}) { if (content instanceof Row) { return content; } super(); this.setProperties(options); this.set('content', content); } }
Fix webpack config for latest.
let path = require('path'); let fs = require('fs'); let webpack = require('webpack'); let WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); let webpackIsomorphicToolsConfig = require('./isomorphic'); var babelrc = fs.readFileSync('./.babelrc'); var babelConfig; try { babelConfig = JSON.parse(babelrc); } catch (err) { console.error('==> ERROR: Error parsing your .babelrc.'); console.error(err); } // Inject HMR plugin for development babelConfig.env.client.presets.push('react-hmre'); let babelLoaderQuery = JSON.stringify(babelConfig.env.client); let webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(webpackIsomorphicToolsConfig).development(); module.exports = { entry: { app: [ './src/client/index.js' ] }, output: { path: path.resolve(__dirname, 'build'), publicPath: 'http://localhost:8080/assets/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel?' + babelLoaderQuery }, { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' } ] }, plugins: [ new webpack.NamedModulesPlugin(), webpackIsomorphicToolsPlugin ], devtool: 'eval-source-map' };
let path = require('path'); let fs = require('fs'); let webpack = require('webpack'); let WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); let webpackIsomorphicToolsConfig = require('./isomorphic'); var babelrc = fs.readFileSync('./.babelrc'); var babelConfig; try { babelConfig = JSON.parse(babelrc); } catch (err) { console.error('==> ERROR: Error parsing your .babelrc.'); console.error(err); } // Inject HMR plugin for development babelConfig.env.client.presets.push('react-hmre'); let babelLoaderQuery = JSON.stringify(babelConfig.env.client); let webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(webpackIsomorphicToolsConfig).development(); module.exports = { entry: { app: [ './src/client/index.js' ] }, output: { path: path.resolve(__dirname, 'build'), publicPath: 'http://localhost:8080/assets/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel?' + babelLoaderQuery }, { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' } ] }, plugins: [ new webpack.NamedModulesPlugin(), webpackIsomorphicToolsPlugin ], progress: true, devtool: 'eval-source-map', debug: true };
Use env variable for etcd endpoinst
package main import ( "github.com/codegangsta/cli" "github.com/monder/kaylee/command" "os" ) func main() { app := cli.NewApp() app.Version = "0.1.0" app.Usage = "Container orchestration system for fleet" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "etcd-endpoints", Value: "http://127.0.0.1:4001,http://127.0.0.1:2379", Usage: "a comma-delimited list of etcd endpoints", EnvVar: "ETCDCTL_ENDPOINT", }, cli.StringFlag{ Name: "etcd-prefix", Value: "/kaylee", Usage: "a keyspace for unit data in etcd", }, } app.Commands = []cli.Command{ command.Server, command.Run, } app.Run(os.Args) }
package main import ( "github.com/codegangsta/cli" "github.com/monder/kaylee/command" "os" ) func main() { app := cli.NewApp() app.Version = "0.1.0" app.Usage = "Container orchestration system for fleet" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "etcd-endpoints", Value: "http://127.0.0.1:4001,http://127.0.0.1:2379", Usage: "a comma-delimited list of etcd endpoints", }, cli.StringFlag{ Name: "etcd-prefix", Value: "/kaylee", Usage: "a keyspace for unit data in etcd", }, } app.Commands = []cli.Command{ command.Server, command.Run, } app.Run(os.Args) }
Check number of not deleted course to display in categories mind map
var appRoot = require('app-root-path'); //var mongoose = require('mongoose'); var Categories = require(appRoot + '/modules/catalogs/categories.js'); var Courses = require(appRoot + '/modules/catalogs/courses.js'); var async = require('asyncawait/async'); var await = require('asyncawait/await'); function CatCountSubNodes(){ } CatCountSubNodes.prototype.init = function(params){ this.slug = params.slug; }; CatCountSubNodes.prototype.run = async ( function(){ var self = this; var result = await( Categories.findOne({ slug: self.slug }).exec()); if (result._id) { var countAllCourses = await (Courses.find({category: result._id}).count().exec()); var countDeletedCourses = await (Courses.find({category: result._id, isDeleted:{$exists: true}}).count().exec()); var activeCourse = countAllCourses - countDeletedCourses; } //var catId = result._id; self.result = activeCourse; } ); CatCountSubNodes.prototype.render = function(){ var activeCourse = this.result; return '<div class="countCourses" style="font-size:80%; margin-top: 3px;"> <span class="badge bg-yellow"> Course Available: ' + activeCourse + '</span></div>' ; }; module.exports = CatCountSubNodes;
var appRoot = require('app-root-path'); //var mongoose = require('mongoose'); var Categories = require(appRoot + '/modules/catalogs/categories.js'); var Courses = require(appRoot + '/modules/catalogs/courses.js'); var async = require('asyncawait/async'); var await = require('asyncawait/await'); function CatCountSubNodes(){ } CatCountSubNodes.prototype.init = function(params){ this.slug = params.slug; }; CatCountSubNodes.prototype.run = async ( function(){ var self = this; var result = await( Categories.findOne({ slug: self.slug }).exec()); if (result._id) { var countCourses = await (Courses.find({category: result._id}).count().exec()); } //var catId = result._id; self.result = countCourses; } ); CatCountSubNodes.prototype.render = function(){ var countCourses = this.result; return '<div class="countCourses" style="font-size:80%; margin-top: 3px;"> <span class="badge bg-yellow"> Course Available: ' + countCourses + '</span></div>' ; }; module.exports = CatCountSubNodes;
Use ServerClass definition for server creation
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def do_POST(self): print '\n---> dummy server: got post!' print 'command:', self.command print 'path:', self.path print 'headers:\n\n', self.headers content_length = int(self.headers['Content-Length']) content = self.rfile.read(content_length) print 'content:\n\n', content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def do_POST(self): print '\n---> dummy server: got post!' print 'command:', self.command print 'path:', self.path print 'headers:\n\n', self.headers content_length = int(self.headers['Content-Length']) content = self.rfile.read(content_length) print 'content:\n\n', content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = BaseHTTPServer.HTTPServer(server_address, JsonPostResponder) httpd.serve_forever()
Remove optional lock input (I can't see when it would be useful) Document when Listener should be used
#! /usr/bin/env python import rospy from threading import Lock class Listener: def __init__(self, topic_name, topic_type): """ Listener is a wrapper around a subscriber where the callback simply records the latest msg. Listener does not consume the message (for consuming behavior, use the standard ros callback pattern) Listener does not check timestamps of message headers Parameters: topic_name (str): name of topic to subscribe to topic_type (msg_type): type of message received on topic lock (Lock): optional lock object used when setting stored data """ self.data = None self.lock = Lock() self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback) def callback(self, msg): with self.lock: self.data = msg def get(self): """ Returns the latest msg from the subscribed topic """ with self.lock: return self.data
#! /usr/bin/env python import rospy from threading import Lock class Listener: def __init__(self, topic_name, topic_type, lock=None): """ Listener is a wrapper around a subscriber where the callback simply records the latest msg. Parameters: topic_name (str): name of topic to subscribe to topic_type (msg_type): type of message received on topic lock (Lock): optional lock object used when setting stored data """ self.data = None self.lock = lock if self.lock is None: self.lock = Lock() self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback) def callback(self, msg): with self.lock: self.data = msg def get(self): """ Returns the latest msg from the subscribed topic """ with self.lock: return self.data
Fix the mistaken use of attend in the UNIQUE clause.
<?php $DATABASE_UNINSTALL = array( "drop table if exists {$CFG->dbprefix}context_map" ); $DATABASE_INSTALL = array( array( "{$CFG->dbprefix}context_map", "create table {$CFG->dbprefix}context_map ( context_id INTEGER NOT NULL, user_id INTEGER NOT NULL, lat FLOAT, lng FLOAT, color INTEGER, updated_at DATETIME NOT NULL, CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1` FOREIGN KEY (`context_id`) REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE(context_id, user_id) ) ENGINE = InnoDB DEFAULT CHARSET=utf8") );
<?php $DATABASE_UNINSTALL = array( "drop table if exists {$CFG->dbprefix}context_map" ); $DATABASE_INSTALL = array( array( "{$CFG->dbprefix}context_map", "create table {$CFG->dbprefix}context_map ( context_id INTEGER NOT NULL, user_id INTEGER NOT NULL, lat FLOAT, lng FLOAT, color INTEGER, updated_at DATETIME NOT NULL, CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1` FOREIGN KEY (`context_id`) REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE(context_id, user_id, attend) ) ENGINE = InnoDB DEFAULT CHARSET=utf8") );
Enable global by default in example.
"""This is an example app, demonstrating usage.""" import os from flask import Flask from flask_jsondash.charts_builder import charts app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=False, JSONDASH_GLOBALDASH=True, JSONDASH_GLOBAL_USER='global', ) app.debug = True app.register_blueprint(charts) def _can_edit_global(): return True def _can_delete(): return True def _can_clone(): return True def _get_username(): return 'anonymous' # Config examples. app.config['JSONDASH'] = dict( metadata=dict( created_by=_get_username, username=_get_username, ), static=dict( js_path='js/vendor/', css_path='css/vendor/', ), auth=dict( edit_global=_can_edit_global, clone=_can_clone, delete=_can_delete, ) ) @app.route('/', methods=['GET']) def index(): """Sample index.""" return '<a href="/charts">Visit the charts blueprint.</a>' if __name__ == '__main__': PORT = int(os.getenv('PORT', 5002)) app.run(debug=True, port=PORT)
"""This is an example app, demonstrating usage.""" import os from flask import Flask from flask_jsondash.charts_builder import charts app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=False, JSONDASH_GLOBALDASH=False, JSONDASH_GLOBAL_USER='global', ) app.debug = True app.register_blueprint(charts) def _can_edit_global(): return True def _can_delete(): return True def _can_clone(): return True def _get_username(): return 'anonymous' # Config examples. app.config['JSONDASH'] = dict( metadata=dict( created_by=_get_username, username=_get_username, ), static=dict( js_path='js/vendor/', css_path='css/vendor/', ), auth=dict( edit_global=_can_edit_global, clone=_can_clone, delete=_can_delete, ) ) @app.route('/', methods=['GET']) def index(): """Sample index.""" return '<a href="/charts">Visit the charts blueprint.</a>' if __name__ == '__main__': PORT = int(os.getenv('PORT', 5002)) app.run(debug=True, port=PORT)
Add cohort filter for section participants
<?php namespace Slate\Courses; class SectionParticipantsRequestHandler extends \RecordsRequestHandler { public static $recordClass = SectionParticipant::class; public static $accountLevelBrowse = 'Staff'; public static $accountLevelWrite = 'Staff'; public static $accountLevelRead = 'Staff'; public static $accountLevelAPI = 'Staff'; public static function handleBrowseRequest($options = [], $conditions = [], $responseID = null, $responseData = []) { if (!empty($_GET['course_section'])) { if (!$CourseSection = SectionsRequestHandler::getRecordByHandle($_GET['course_section'])) { return static::throwNotFoundError('Course Section not found'); } $conditions['CourseSectionID'] = $CourseSection->ID; } if (!empty($_GET['cohort'])) { $conditions['Cohort'] = $_GET['cohort']; } if (!empty($_GET['role'])) { $conditions['Role'] = [ 'values' => is_string($_GET['role']) ? explode(',', $_GET['role']) : $_GET['role'] ]; } return parent::handleBrowseRequest($options, $conditions, $responseID, $responseData); } }
<?php namespace Slate\Courses; class SectionParticipantsRequestHandler extends \RecordsRequestHandler { public static $recordClass = SectionParticipant::class; public static $accountLevelBrowse = 'Staff'; public static $accountLevelWrite = 'Staff'; public static $accountLevelRead = 'Staff'; public static $accountLevelAPI = 'Staff'; public static function handleBrowseRequest($options = [], $conditions = [], $responseID = null, $responseData = []) { if (!empty($_GET['course_section'])) { if (!$CourseSection = SectionsRequestHandler::getRecordByHandle($_GET['course_section'])) { return static::throwNotFoundError('Course Section not found'); } $conditions['CourseSectionID'] = $CourseSection->ID; } if (!empty($_GET['role'])) { $conditions['Role'] = [ 'values' => is_string($_GET['role']) ? explode(',', $_GET['role']) : $_GET['role'] ]; } return parent::handleBrowseRequest($options, $conditions, $responseID, $responseData); } }
Set a CSP to upgrade all insecure requests By setting a Content Security Policy, all HTTP requests will be now upgraded by supported browsers to HTTPS automatically. This will ensure a secure-only experience.
<?php /* Redirect to HTTPS and refuse to serve HTTP */ if($_SERVER['HTTPS'] != "on"){ $_SERVER['FULL_URL'] = 'https://'; if($_SERVER['SERVER_PORT']!='80') $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME']; else $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; if($_SERVER['QUERY_STRING']>' '){ $_SERVER['FULL_URL'] .= '?'.$_SERVER['QUERY_STRING']; } header("Location: " . $_SERVER['FULL_URL'], true, 301); exit(); } else { /* Only use HTTPS for the next year */ header("Strict-Transport-Security: max-age=31536000"); header("Content-Security-Policy: upgrade-insecure-requests;"); } ?>
<?php /* Redirect to HTTPS and refuse to serve HTTP */ if($_SERVER['HTTPS'] != "on"){ $_SERVER['FULL_URL'] = 'https://'; if($_SERVER['SERVER_PORT']!='80') $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME']; else $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; if($_SERVER['QUERY_STRING']>' '){ $_SERVER['FULL_URL'] .= '?'.$_SERVER['QUERY_STRING']; } header("Location: " . $_SERVER['FULL_URL'], true, 301); exit(); } else { /* Only use HTTPS for the next year */ header("Strict-Transport-Security: max-age=31536000"); } ?>
Support live params in the API
<?php /** * @package api * @subpackage objects.factory */ class KalturaFlavorParamsFactory { static function getFlavorParamsOutputInstance($type) { switch ($type) { case KalturaAssetType::FLAVOR: return new KalturaFlavorParamsOutput(); case KalturaAssetType::THUMBNAIL: return new KalturaThumbParamsOutput(); default: $obj = KalturaPluginManager::loadObject('KalturaFlavorParamsOutput', $type); if($obj) return $obj; return new KalturaFlavorParamsOutput(); } } static function getFlavorParamsInstance($type) { switch ($type) { case KalturaAssetType::FLAVOR: return new KalturaFlavorParams(); case KalturaAssetType::THUMBNAIL: return new KalturaThumbParams(); case KalturaAssetType::LIVE: return new KalturaLiveParams(); default: $obj = KalturaPluginManager::loadObject('KalturaFlavorParams', $type); if($obj) return $obj; return new KalturaFlavorParams(); } } }
<?php /** * @package api * @subpackage objects.factory */ class KalturaFlavorParamsFactory { static function getFlavorParamsOutputInstance($type) { switch ($type) { case KalturaAssetType::FLAVOR: return new KalturaFlavorParamsOutput(); case KalturaAssetType::THUMBNAIL: return new KalturaThumbParamsOutput(); default: $obj = KalturaPluginManager::loadObject('KalturaFlavorParamsOutput', $type); if($obj) return $obj; return new KalturaFlavorParamsOutput(); } } static function getFlavorParamsInstance($type) { switch ($type) { case KalturaAssetType::FLAVOR: return new KalturaFlavorParams(); case KalturaAssetType::THUMBNAIL: return new KalturaThumbParams(); default: $obj = KalturaPluginManager::loadObject('KalturaFlavorParams', $type); if($obj) return $obj; return new KalturaFlavorParams(); } } }
Update service provider to work with Laravel 5.4
<?php namespace Scriptotek\Sru\Providers; use Illuminate\Support\ServiceProvider; use Scriptotek\Sru\Client as SruClient; class SruServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes(array( __DIR__.'/../../config/config.php' => config_path('sru.php') )); } /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/config.php', 'sru' ); $this->app->singleton(SruClient::class, function ($app) { return new SruClient($app['config']->get('sru.endpoint'), $app['config']->get('sru')); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [SruClient::class]; } }
<?php namespace Scriptotek\Sru\Providers; use Illuminate\Support\ServiceProvider; use Scriptotek\Sru\Client as SruClient; class SruServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes(array( __DIR__.'/../../config/config.php' => config_path('sru.php') )); } /** * Register the service provider. * * @return void */ public function register() { $app = $this->app; $this->mergeConfigFrom( __DIR__.'/../../config/config.php', 'sru' ); $app['sru-client'] = $app->share(function ($app) { return new SruClient($app['config']->get('sru.endpoint'), $app['config']->get('sru')); }); $app->alias('sru-client', SruClient::class); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('sru-client'); } }
Make locale tests into one test
import test from "ava"; const fs = require("fs"); const path = require("path"); const localesPath = path.join(__dirname, "..", "locales"); const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/; test("locale files are valid", t => { const filenames = fs.readdirSync(localesPath); filenames.forEach(filename => { /* test filename */ if (!filenameRegex.test(filename)) t.fail(`locale filename "${filename}" is invalid`); /* test file json */ const content = fs.readFileSync(path.join(localesPath, filename), { encoding: "utf8" }); let valid = false; try { JSON.parse(content); valid = true; } catch (e) {} if (!valid) t.fail(`locale file "${filename}" is invalid`); }); t.pass(); // if nothing has failed so far });
import test from "ava"; const fs = require("fs"); const path = require("path"); const localesPath = path.join(__dirname, "..", "locales"); fs.readdir(localesPath, (err, filenames) => { if (err) throw err; const filenameRegex = /^[a-z][a-z](_[A-Z]+)*\.json$/; filenames.forEach(filename => { test(`locale filename "${filename}" is valid`, t => { t.true(filenameRegex.test(filename)); }); }); filenames.forEach(filename => { const content = fs.readFileSync(path.join(localesPath, filename), { encoding: "utf8" }); let valid = false; try { JSON.parse(content); valid = true; } catch (e) {} test(`locale file "${filename}" is valid`, t => t.true(valid)); }); });