text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add more tests for findWhere util function
import { findWhere } from './utils'; describe('Utils', () => { describe('findWhere', () => { it('finds the first item in a list where a predicate matches', () => { const list = [1, 2, 3, 4, 5, 6, 7, 8]; const result = findWhere(list, item => item * item === 16); expect(result).toBe(4); }); it('returns null if it cannot find an element where the predicate matches', () => { const list = [1, 2, 3, 5, 6, 7, 8]; const result = findWhere(list, item => item * item === 16); expect(result).toBe(null); }); it('works for objects', () => { const list = [{ findMe: false, id: 0 }, { findMe: true, id: 1 }, { findMe: false, id: 2 }]; expect(findWhere(list, element => element.findMe)).toBe(list[1]); }); it('handles empty arguments', () => { expect(findWhere()).toBe(null); expect(findWhere([0, 1, 2, 3])).toBe(1); expect(findWhere([false, false, true, false])).toBe(true); expect(findWhere(undefined, () => true)).toBe(null); }); }); });
import { findWhere } from './utils'; describe('Utils', () => { describe('findWhere', () => { it('finds the first item in a list where a predicate matches', () => { const list = [1, 2, 3, 4, 5, 6, 7, 8]; const result = findWhere(list, item => item * item === 16); expect(result).toBe(4); }); it('returns null if it cannot find an element where the predicate matches', () => { const list = [1, 2, 3, 5, 6, 7, 8]; const result = findWhere(list, item => item * item === 16); expect(result).toBe(null); }); it('handles empty arguments', () => { expect(findWhere()).toBe(null); expect(findWhere([0, 1, 2, 3])).toBe(1); expect(findWhere([false, false, true, false])).toBe(true); expect(findWhere(undefined, () => true)).toBe(null); }); }); });
Remove outdated and redundant encoding specifier
""" Move Tab Plugin for Sublime Text to move tabs around Copyright (c) 2012 Frédéric Massart - FMCorz.net Licensed under The MIT License Redistributions of files must retain the above copyright notice. http://github.com/FMCorz/MoveTab """ import sublime_plugin class MoveTabCommand(sublime_plugin.WindowCommand): def run(self, position): view = self.window.active_view() group, index = self.window.get_view_index(view) if index < 0: return count = len(self.window.views_in_group(group)) if isinstance(position, str) and position[0] in '-+': position = (index + int(position)) % count else: position = min(count - 1, max(0, int(position))) # Avoid flashing tab when moving to same index if position != index: self.window.set_view_index(view, group, position) self.window.focus_view(view) def is_enabled(self): (group, index) = self.window.get_view_index(self.window.active_view()) return -1 not in (group, index) and len(self.window.views_in_group(group)) > 1
# -*- coding: utf-8 -*- """ Move Tab Plugin for Sublime Text to move tabs around Copyright (c) 2012 Frédéric Massart - FMCorz.net Licensed under The MIT License Redistributions of files must retain the above copyright notice. http://github.com/FMCorz/MoveTab """ import sublime_plugin class MoveTabCommand(sublime_plugin.WindowCommand): def run(self, position): view = self.window.active_view() group, index = self.window.get_view_index(view) if index < 0: return count = len(self.window.views_in_group(group)) if isinstance(position, str) and position[0] in '-+': position = (index + int(position)) % count else: position = min(count - 1, max(0, int(position))) # Avoid flashing tab when moving to same index if position != index: self.window.set_view_index(view, group, position) self.window.focus_view(view) def is_enabled(self): (group, index) = self.window.get_view_index(self.window.active_view()) return -1 not in (group, index) and len(self.window.views_in_group(group)) > 1
:new: Add pretty printing support to writeJSON
/* @flow */ import FS from 'fs' import promisify from 'sb-promisify' import mkdirp from 'mkdirp' import rimraf from 'rimraf' import ncp from 'ncp' export const copy = promisify(ncp) export const unlink = promisify(FS.unlink) export const readFile = promisify(FS.readFile) export const writeFile = promisify(FS.writeFile) export function mkdir(target: string): Promise { return new Promise(function(resolve, reject) { mkdirp(target, function(error) { if (error) { reject(error) } else resolve() }) }) } export function rm(target: string): Promise { return new Promise(function(resolve, reject) { rimraf(target, { disableGlob: true }, function(error) { if (error) { reject(error) } else resolve() }) }) } export async function readJSON(filePath: string, encoding: string = 'utf8'): Promise { const contents = await readFile(filePath) return JSON.parse(contents.toString(encoding)) } export async function writeJSON( filePath: string, contents: Object, pretty: boolean = false ): Promise { const serialized = pretty ? JSON.stringify(contents, null, 4) : JSON.stringify(contents) await writeFile(filePath, serialized) } export function exists(filePath: string): Promise<boolean> { return new Promise(function(resolve) { FS.access(filePath, FS.R_OK, function(error) { resolve(error === null) }) }) }
/* @flow */ import FS from 'fs' import promisify from 'sb-promisify' import mkdirp from 'mkdirp' import rimraf from 'rimraf' import ncp from 'ncp' export const copy = promisify(ncp) export const unlink = promisify(FS.unlink) export const readFile = promisify(FS.readFile) export const writeFile = promisify(FS.writeFile) export function mkdir(target: string): Promise { return new Promise(function(resolve, reject) { mkdirp(target, function(error) { if (error) { reject(error) } else resolve() }) }) } export function rm(target: string): Promise { return new Promise(function(resolve, reject) { rimraf(target, { disableGlob: true }, function(error) { if (error) { reject(error) } else resolve() }) }) } export async function readJSON(filePath: string, encoding: string = 'utf8'): Promise { const contents = await readFile(filePath) return JSON.parse(contents.toString(encoding)) } export async function writeJSON(filePath: string, contents: Object): Promise { await writeFile(filePath, JSON.stringify(contents)) } export function exists(filePath: string): Promise<boolean> { return new Promise(function(resolve) { FS.access(filePath, FS.R_OK, function(error) { resolve(error === null) }) }) }
Adjust hashtag to be consistently one word
from django.conf import settings from django.db import models class Hashtag(models.Model): # The hash tag length can't be more than the body length minus the `#` text = models.CharField(max_length=139) def __str__(self): return self.text class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages") text = models.CharField(max_length=140) created_at = models.DateTimeField(auto_now_add=True) stars = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True) tagged_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True) hash_tags = models.ManyToManyField(HashTag, blank=True) def __str__(self): return self.text
from django.conf import settings from django.db import models class HashTag(models.Model): # The hash tag length can't be more than the body length minus the `#` text = models.CharField(max_length=139) def __str__(self): return self.text class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages") text = models.CharField(max_length=140) created_at = models.DateTimeField(auto_now_add=True) stars = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True) tagged_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True) hash_tags = models.ManyToManyField(HashTag, blank=True) def __str__(self): return self.text
Refactor validator tests with black Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com>
import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import ( DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA, ) from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ["a", "b", "c", "d", "e"] assert validator._search(vector=vec, searched_value="c") def test_verify_intents(validator): valid_intents = ["greet", "goodbye", "affirm"] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ['a', 'b', 'c', 'd', 'e'] assert validator._search(vector=vec, searched_value='c') def test_verify_intents(validator): valid_intents = ['greet', 'goodbye', 'affirm'] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default'] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
Rename item.js to bookmark_item.js Part.2
import {element} from 'deku'; import BookmarkItem from './bookmark_item'; import BoxTemplate from './box_template'; import Search from './search'; function render({props, state}) { const boxClasses = ['panel', 'panel-width']; const mainBoxes = []; const subBoxes = []; const treeItemsList = []; props.trees.forEach((treeInfo, treeIndex) => { const childrenInfo = treeInfo.children; const isRootTree = treeIndex === 0; const treeItemsIndex = isRootTree ? 0 : treeIndex - 1; childrenInfo.forEach((itemInfo) => { if (!treeItemsList[treeItemsIndex]) { treeItemsList[treeItemsIndex] = []; } treeItemsList[treeItemsIndex].push(<BookmarkItem itemInfo={itemInfo} />); }); }); treeItemsList.forEach((treeItems, treeItemsIndex) => { const targetBox = treeItemsIndex % 2 === 0 ? mainBoxes : subBoxes; const treeIndex = treeItemsIndex + 1; const treeInfo = props.trees[treeIndex]; targetBox.push( <BoxTemplate treeInfo={treeInfo} treeItems={treeItems} /> ); }); return ( <div> <div id='sub' class={boxClasses}> {subBoxes} </div> <div id='main' class={boxClasses}> <Search /> {mainBoxes} </div> </div> ); } export default {render};
import {element} from 'deku'; import BoxTemplate from './box_template'; import BookmarkItem from './bookmark_item'; import Search from './search'; function render({props, state}) { const boxClasses = ['panel', 'panel-width']; const mainBoxes = []; const subBoxes = []; const treeItemsList = []; props.trees.forEach((treeInfo, treeIndex) => { const childrenInfo = treeInfo.children; const isRootTree = treeIndex === 0; const treeItemsIndex = isRootTree ? 0 : treeIndex - 1; childrenInfo.forEach((itemInfo) => { if (!treeItemsList[treeItemsIndex]) { treeItemsList[treeItemsIndex] = []; } treeItemsList[treeItemsIndex].push(<BookmarkItem itemInfo={itemInfo} />); }); }); treeItemsList.forEach((treeItems, treeItemsIndex) => { const targetBox = treeItemsIndex % 2 === 0 ? mainBoxes : subBoxes; const treeIndex = treeItemsIndex + 1; const treeInfo = props.trees[treeIndex]; targetBox.push( <BoxTemplate treeInfo={treeInfo} treeItems={treeItems} /> ); }); return ( <div> <div id='sub' class={boxClasses}> {subBoxes} </div> <div id='main' class={boxClasses}> <Search /> {mainBoxes} </div> </div> ); } export default {render};
Fix an error in the formula used to calculate an arithmetic series.
<?php namespace tomzx\ProjectEuler; use LogicException; class Series { /** * @param int $n number of terms * @param float $a1 first term value * @param float $a2 last term value * @return float */ public static function arithmetic($n, $a1, $a2) { if ($n < 0) { new LogicException('n cannot be negative.'); } return $n * ($a1 + $a2) / 2; } /** * @param float $r common ratio * @param int $n number of terms * @param int $a scale factor * @return float */ public static function geometric($r, $n, $a = 1) { if ($r === 1) { new LogicException('r cannot be equal to 1.'); } if ($n < 0) { new LogicException('n cannot be negative.'); } return $a * (1 - pow($r, $n)) / (1 - $r); } }
<?php namespace tomzx\ProjectEuler; use LogicException; class Series { /** * @param int $n number of terms * @param float $a1 first term value * @param float $a2 last term value * @return float */ public static function arithmetic($n, $a1, $a2) { if ($n < 0) { new LogicException('n cannot be negative.'); } return $n * ($a1 * $a2) / 2; } /** * @param float $r common ratio * @param int $n number of terms * @param int $a scale factor * @return float */ public static function geometric($r, $n, $a = 1) { if ($r === 1) { new LogicException('r cannot be equal to 1.'); } if ($n < 0) { new LogicException('n cannot be negative.'); } return $a * (1 - pow($r, $n)) / (1 - $r); } }
Clarify redux form input binding
import React, { PropTypes } from 'react'; import TextField from 'material-ui/TextField'; const LongTextInput = ({ input, label, meta: { touched, error }, options }) => ( <TextField value={input.value} onChange={input.onChange} {...options} multiLine fullWidth floatingLabelText={label} errorText={touched && error} /> ); LongTextInput.propTypes = { includesLabel: PropTypes.bool.isRequired, input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object, name: PropTypes.string, options: PropTypes.object, validation: PropTypes.object, }; LongTextInput.defaultProps = { includesLabel: true, input: {}, options: {}, }; export default LongTextInput;
import React, { PropTypes } from 'react'; import TextField from 'material-ui/TextField'; const LongTextInput = ({ input, label, meta: { touched, error }, options }) => ( <TextField value={input.value} onChange={input.onChange} {...options} multiLine fullWidth floatingLabelText={label} errorText={touched && error} /> ); LongTextInput.propTypes = { includesLabel: PropTypes.bool.isRequired, input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object, name: PropTypes.string, options: PropTypes.object, validation: PropTypes.object, }; LongTextInput.defaultProps = { includesLabel: true, input: {}, options: {}, includesLabel: true, }; export default LongTextInput;
Use py_modules instead of packages. This is necessary when only having a "root package".
import codecs from setuptools import setup, find_packages def long_description(): with codecs.open('README.rst', encoding='utf8') as f: return f.read() setup( name='django-querysetsequence', py_modules=['queryset_sequence'], version='0.1', description='Chain together multiple (disparate) QuerySets to treat them as a single QuerySet.', long_description=long_description(), author='Percipient Networks, LLC', author_email='support@percipientnetworks.com', url='https://github.com/percipient/django-querysetsequence', download_url='https://github.com/percipient/django-querysetsequence', keywords=['django', 'queryset', 'chain', 'multi', 'multiple', 'iterable'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'License :: OSI Approved :: ISC License (ISCL)', ], install_requires=[ 'django>=1.8.0', ], )
import codecs from setuptools import setup, find_packages def long_description(): with codecs.open('README.rst', encoding='utf8') as f: return f.read() setup( name='django-querysetsequence', packages=find_packages(), version='0.1', description='Chain together multiple (disparate) QuerySets to treat them as a single QuerySet.', long_description=long_description(), author='Percipient Networks, LLC', author_email='support@percipientnetworks.com', url='https://github.com/percipient/django-querysetsequence', download_url='https://github.com/percipient/django-querysetsequence', keywords=['django', 'queryset', 'chain', 'multi', 'multiple', 'iterable'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'License :: OSI Approved :: ISC License (ISCL)', ], install_requires=[ 'django>=1.8.0', ], )
Use context managers to build detailed_description.
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version_classifiers = ['Programming Language :: Python :: %s' % version for version in ['2', '2.5', '2.6', '2.7']] other_classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: OS Independent', 'Topic :: Software Development :: Testing', ] with open('README', 'rt') as file_obj: detailed_description = file_obj.read() with open('CHANGELOG', 'rt') as file_obj: detailed_description += file_obj.read() setup( name="nosy", version="1.1.1", description="""\ Run the nose test discovery and execution tool whenever a source file is changed. """, long_description=detailed_description, author="Doug Latornell", author_email="djl@douglatornell.ca", url="http://douglatornell.ca/software/python/Nosy/", license="New BSD License", classifiers=version_classifiers + other_classifiers, packages=find_packages(), entry_points={'console_scripts':['nosy = nosy.nosy:main']} )
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version_classifiers = ['Programming Language :: Python :: %s' % version for version in ['2', '2.5', '2.6', '2.7']] other_classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: OS Independent', 'Topic :: Software Development :: Testing', ] readme_file = open('README', 'rt') try: detailed_description = readme_file.read() finally: readme_file.close() setup( name="nosy", version="1.1.1", description="""\ Run the nose test discovery and execution tool whenever a source file is changed. """, long_description=detailed_description, author="Doug Latornell", author_email="djl@douglatornell.ca", url="http://douglatornell.ca/software/python/Nosy/", license="New BSD License", classifiers=version_classifiers + other_classifiers, packages=find_packages(), entry_points={'console_scripts':['nosy = nosy.nosy:main']} )
Allow insecure oauth transport in development.
import os DOMAIN = { "texts": { "schema": { "name": { "type": "string", "required": True, "unique": True, }, "fulltext": { "type": "string", "required": True, }, } } } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET"] DEBUG = os.environ.get("EVE_DEBUG", False) if DEBUG: os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" APP_SECRET_KEY = os.environ["APP_SECRET_KEY"] OAUTH_CLIENT_ID = (os.environ["OAUTH_CLIENT_ID"]) OAUTH_CLIENT_SECRET = os.environ["OAUTH_CLIENT_SECRET"] OAUTH_REDIRECT_URI = os.environ["OAUTH_REDIRECT_URI"] OAUTH_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' OAUTH_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' OAUTH_USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' OAUTH_SCOPE = 'email'
import os DOMAIN = { "texts": { "schema": { "name": { "type": "string", "required": True, "unique": True, }, "fulltext": { "type": "string", "required": True, }, } } } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET"] DEBUG = os.environ.get("EVE_DEBUG", False) APP_SECRET_KEY = os.environ["APP_SECRET_KEY"] OAUTH_CLIENT_ID = (os.environ["OAUTH_CLIENT_ID"]) OAUTH_CLIENT_SECRET = os.environ["OAUTH_CLIENT_SECRET"] OAUTH_REDIRECT_URI = os.environ["OAUTH_REDIRECT_URI"] OAUTH_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' OAUTH_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' OAUTH_USER_INFO = 'https://www.googleapis.com/userinfo/v2/me' OAUTH_SCOPE = 'email'
Allow specification of multiple subpath_segments
from pyramid.security import has_permission def includeme(config): config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate) config.add_view_predicate('additional_permission', AdditionalPermissionPredicate) class SubpathSegmentsPredicate(object): def __init__(self, val, config): if isinstance(val, int): val = (val,) self.val = frozenset(val) def text(self): return 'subpath_segments in %r' % sorted(self.val) phash = text def __call__(self, context, request): return len(request.subpath) in self.val class AdditionalPermissionPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'additional_permission = %r' % self.val phash = text def __call__(self, context, request): return has_permission(self.val, context, request)
from pyramid.security import has_permission def includeme(config): config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate) config.add_view_predicate('additional_permission', AdditionalPermissionPredicate) class SubpathSegmentsPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'subpath_segments = %r' % self.val phash = text def __call__(self, context, request): return len(request.subpath) == self.val class AdditionalPermissionPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'additional_permission = %r' % self.val phash = text def __call__(self, context, request): return has_permission(self.val, context, request)
DPRO-435: Comment out console.log for IE compatibility
/* * Querying the ALM API. */ (function ($) { function validateDOI(doi) { if (doi == null) { throw new Error('DOI is null.'); } doi = encodeURI(doi); return doi.replace(new RegExp('/', 'g'), '%2F').replace(new RegExp(':', 'g'), '%3A'); } /** * Query for one article's ALM summary. * @param doi the article's DOI * @param callback the callback to which to send the summary */ $.fn.getArticleSummary = function (doi, callback) { var config = ALM_CONFIG; // expect to import value from alm_config.js if (config.host == null) { // TODO: Replace with better console logging // console.log('ALM API is not configured'); return; } doi = validateDOI(doi); var requestUrl = config.host + '?api_key=' + config.apiKey + '&ids=' + doi; $.ajax({ url: requestUrl, jsonp: 'callback', dataType: 'jsonp', success: function (response) { callback(response.data[0]); }, failure: function () { // TODO: Replace with better console logging // console.log('ALM request failed: ' + requestUrl); } }) }; /* * TODO: Support querying for multiple article summaries in efficient batches. * See getArticleSummaries in legacy Ambra. */ })(jQuery);
/* * Querying the ALM API. */ (function ($) { function validateDOI(doi) { if (doi == null) { throw new Error('DOI is null.'); } doi = encodeURI(doi); return doi.replace(new RegExp('/', 'g'), '%2F').replace(new RegExp(':', 'g'), '%3A'); } /** * Query for one article's ALM summary. * @param doi the article's DOI * @param callback the callback to which to send the summary */ $.fn.getArticleSummary = function (doi, callback) { var config = ALM_CONFIG; // expect to import value from alm_config.js if (config.host == null) { console.log('ALM API is not configured'); return; } doi = validateDOI(doi); var requestUrl = config.host + '?api_key=' + config.apiKey + '&ids=' + doi; $.ajax({ url: requestUrl, jsonp: 'callback', dataType: 'jsonp', success: function (response) { callback(response.data[0]); }, failure: function () { console.log('ALM request failed: ' + requestUrl); } }) }; /* * TODO: Support querying for multiple article summaries in efficient batches. * See getArticleSummaries in legacy Ambra. */ })(jQuery);
Add units to brady and tachy strings.
def summarizeECG(instHR, avgHR, brady, tachy): """Create txt file summarizing ECG analysis :param instHR: (int) :param avgHR: (int) :param brady: (int) :param tachy: (int) """ #Calls hrdetector() to get instantaneous heart rate #instHR = findInstHR() #Calls findAvgHR() to get average heart rate #avgHR = findAvgHR() #Calls bradyTimes() to get times when bradycardia occurred #brady = bradyTimes() #Calls tachtimes() to get times when tachycardia occurred #tachy = tachyTimes() #Writes the output of the ECG analysis to an output file named ecgOutput.txt ecgResults = open('ecgOutput.txt','w') instHRstr = "Estimated instantaneous heart rate: %s" % str(instHR) avgHRstr = "Estimated average heart rate: %s" % str(avgHR) bradystr = "Bradycardia occurred at: %s" % str(brady) tachystr = "Tachycardia occurred at: %s" % str(tachy) ecgResults.write(instHRstr + ' BPM\n' + avgHRstr + ' BPM\n' + bradystr + ' sec\n' + tachystr + ' sec') ecgResults.close()
def summarizeECG(instHR, avgHR, brady, tachy): """Create txt file summarizing ECG analysis :param instHR: (int) :param avgHR: (int) :param brady: (int) :param tachy: (int) """ #Calls hrdetector() to get instantaneous heart rate #instHR = findInstHR() #Calls findAvgHR() to get average heart rate #avgHR = findAvgHR() #Calls bradyTimes() to get times when bradycardia occurred #brady = bradyTimes() #Calls tachtimes() to get times when tachycardia occurred #tachy = tachyTimes() #Writes the output of the ECG analysis to an output file named ecgOutput.txt ecgResults = open('ecgOutput.txt','w') instHRstr = "Estimated instantaneous heart rate: %s" % str(instHR) avgHRstr = "Estimated average heart rate: %s" % str(avgHR) bradystr = "Bradycardia occurred at: %s" % str(brady) tachystr = "Tachycardia occurred at: %s" % str(tachy) ecgResults.write(instHRstr + ' BPM\n' + avgHRstr + ' BPM\n' + bradystr + '\n' + tachystr) ecgResults.close()
Extend test to check for the exit code and for an exception
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 'tox.ini'), '-e', 'py' ]) except subprocess.CalledProcessError as e: pytest.fail(e) def test_run_cookiecutter_and_plugin_tests(cookies): """Create a new plugin via cookiecutter and run its tests.""" result = cookies.bake() assert result.exit_code == 0 assert result.exception is None assert result.project.basename == 'pytest-foobar' assert result.project.isdir() run_tox(str(result.project))
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 'tox.ini'), '-e', 'py' ]) except subprocess.CalledProcessError as e: pytest.fail(e) def test_run_cookiecutter_and_plugin_tests(cookies): """Create a new plugin via cookiecutter and run its tests.""" result = cookies.bake() assert result.project.basename == 'pytest-foobar' assert result.project.isdir() run_tox(str(result.project))
Fix site:doctor to work with generator-statisk
'use strict'; const gulp = require('gulp'); const shell = require('shelljs'); const size = require('gulp-size'); const argv = require('yargs').argv; // 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory // to be processed gulp.task('site:tmp', () => gulp.src(['src/**/*', '!src/assets/**/*', '!src/assets']) .pipe(gulp.dest('.tmp/src')) .pipe(size({title: 'Jekyll'})) ); // 'gulp jekyll' -- builds your site with development settings // 'gulp jekyll --prod' -- builds your site with production settings gulp.task('site', done => { if (!argv.prod) { shell.exec('jekyll build'); done(); } else if (argv.prod) { shell.exec('jekyll build --config _config.yml,_config.build.yml'); done(); } }); // 'gulp doctor' -- literally just runs jekyll doctor gulp.task('site:check', done => { shell.exec('jekyll doctor'); done(); });
'use strict'; const gulp = require('gulp'); const shell = require('shelljs'); const size = require('gulp-size'); const argv = require('yargs').argv; // 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory // to be processed gulp.task('site:tmp', () => gulp.src(['src/**/*', '!src/assets/**/*', '!src/assets']) .pipe(gulp.dest('.tmp/src')) .pipe(size({title: 'Jekyll'})) ); // 'gulp jekyll' -- builds your site with development settings // 'gulp jekyll --prod' -- builds your site with production settings gulp.task('site', done => { if (!argv.prod) { shell.exec('jekyll build'); done(); } else if (argv.prod) { shell.exec('jekyll build --config _config.yml,_config.build.yml'); done(); } }); // 'gulp doctor' -- literally just runs jekyll doctor gulp.task('site:doctor', done => { shell.exec('jekyll doctor'); done(); });
Call upstream accept method with the correct convention.
var mime = require('mime'); module.exports = function(config) { 'use strict'; var cfg = config || {}; var prefix = cfg.prefix || 'original'; var ext = cfg.extensionName || 'requestExtension'; var accepts = function() { var re = mime.lookup(this[ext]); for (var i = 0; i < arguments.length; i++) { var t = arguments[i]; if (this[ext] == t || re == t) return t; } return this[prefix + 'Accepts'].apply(this, arguments); }; var middleware = function*(next) { var m = this.path.match(/(.*)\.(.*)$/); if (m) { this[prefix + 'Accepts'] = this.accepts; this.accepts = accepts; this[ext] = m[2].toLowerCase(); this[prefix + 'Path'] = this.oath; this.path = m[1]; } yield next; }; return middleware; };
var mime = require('mime'); module.exports = function(config) { 'use strict'; var cfg = config || {}; var prefix = cfg.prefix || 'original'; var ext = cfg.extensionName || 'requestExtension'; var accepts = function() { var re = mime.lookup(this[ext]); for (var i = 0; i < arguments.length; i++) { var t = arguments[i]; if (this[ext] == t || re == t) return t; } return this[prefix + 'Accepts'].call(this, arguments); }; var middleware = function*(next) { var m = this.path.match(/(.*)\.(.*)$/); if (m) { this[prefix + 'Accepts'] = this.accepts; this.accepts = accepts; this[ext] = m[2].toLowerCase(); this[prefix + 'Path'] = this.oath; this.path = m[1]; } yield next; }; return middleware; };
Make sure error is a handled error
const create = require('./index') describe('rpc/create', () => { it('should create a new user', async () => { const email = 'test@test.com' const id = '12345' const insertResult = { insertedId: id } const db = { insertOne: jest.fn(() => Promise.resolve(insertResult)) } const result = await create({email}, {db}) expect(db.insertOne) .toBeCalledWith({ email, verified: false }) expect(result) .toEqual({ id }) }) it('show throw an error if email is missing', async () => { try { await create({}, {}) } catch (err) { expect(err.message) .toBe('Missing Input Parameter') expect(err.handled) .toBe(true) } }) })
const create = require('./index') describe('rpc/create', () => { it('should create a new user', async () => { const email = 'test@test.com' const id = '12345' const insertResult = { insertedId: id } const db = { insertOne: jest.fn(() => Promise.resolve(insertResult)) } const result = await create({email}, {db}) expect(db.insertOne) .toBeCalledWith({ email, verified: false }) expect(result) .toEqual({ id }) }) it('show throw an error if email is missing', async () => { try { await create({}, {}) } catch (err) { expect(err.message) .toBe('Missing Input Parameter') } }) })
Fix event detail variable key lookup
import boto3 iam = boto3.client('iam') def lambda_handler(event, context): details = event['detail']['check-item-detail'] username = details['User Name (IAM or Root)'] access_key_id = details['Access Key ID'] exposed_location = details['Location'] print('Deleting exposed access key pair...') delete_exposed_key_pair(username, access_key_id) return { "username": username, "deleted_key": access_key_id, "exposed_location": exposed_location } def delete_exposed_key_pair(username, access_key_id): try: iam.delete_access_key( UserName=username, AccessKeyId=access_key_id ) except Exception as e: print(e) print('Unable to delete access key "{}" for user "{}".'.format(access_key_id, username)) raise(e)
import boto3 iam = boto3.client('iam') def lambda_handler(event, context): details = event['check-item-detail'] username = details['User Name (IAM or Root)'] access_key_id = details['Access Key ID'] exposed_location = details['Location'] print('Deleting exposed access key pair...') delete_exposed_key_pair(username, access_key_id) return { "username": username, "deleted_key": access_key_id, "exposed_location": exposed_location } def delete_exposed_key_pair(username, access_key_id): try: iam.delete_access_key( UserName=username, AccessKeyId=access_key_id ) except Exception as e: print(e) print('Unable to delete access key "{}" for user "{}".'.format(access_key_id, username)) raise(e)
Remove session info and driver info of webdriverexception.
import re __author__ = 'karl.gong' filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)") class EasyiumException(Exception): def __init__(self, msg=None, context=None): # Remove Session info and Driver info of the message. self.msg = filter_msg_regex.sub("", msg) self.message = self.msg self.context = context def __str__(self): exception_msg = "" if self.msg is not None: exception_msg = self.msg if self.context is not None: exception_msg += "\n" + str(self.context) return exception_msg class TimeoutException(EasyiumException): pass class ElementTimeoutException(TimeoutException): pass class WebDriverTimeoutException(TimeoutException): pass class NoSuchElementException(EasyiumException): pass class NotPersistException(EasyiumException): pass class LatePersistException(EasyiumException): pass class UnsupportedWebDriverTypeException(EasyiumException): pass class InvalidLocatorException(EasyiumException): pass class UnsupportedOperationException(EasyiumException): pass
__author__ = 'karl.gong' class EasyiumException(Exception): def __init__(self, msg=None, context=None): self.msg = msg self.message = self.msg self.context = context def __str__(self): exception_msg = "" if self.msg is not None: exception_msg = self.msg if self.context is not None: exception_msg += "\n" + str(self.context) return exception_msg class TimeoutException(EasyiumException): pass class ElementTimeoutException(TimeoutException): pass class WebDriverTimeoutException(TimeoutException): pass class NoSuchElementException(EasyiumException): pass class NotPersistException(EasyiumException): pass class LatePersistException(EasyiumException): pass class UnsupportedWebDriverTypeException(EasyiumException): pass class InvalidLocatorException(EasyiumException): pass class UnsupportedOperationException(EasyiumException): pass
Fix trl: Don't access filesystem, file doesn't get written when using dev-server
'use strict'; var HtmlWebpackPlugin = require('html-webpack-plugin'); var fs = require('fs'); class TrlHtmlWebpackPlugin extends HtmlWebpackPlugin { htmlWebpackPluginAssets(compilation, chunks) { let language = this.options.language; let ret = super.htmlWebpackPluginAssets(compilation, chunks); chunks.forEach(chunk => { chunk.files.forEach(file => { if (compilation.assets[language + '.' + file]) { ret.js.unshift(ret.publicPath + language + '.' + file); } }) }); return ret; } } module.exports = TrlHtmlWebpackPlugin;
'use strict'; var HtmlWebpackPlugin = require('html-webpack-plugin'); var fs = require('fs'); class TrlHtmlWebpackPlugin extends HtmlWebpackPlugin { htmlWebpackPluginAssets(compilation, chunks) { let language = this.options.language; let ret = super.htmlWebpackPluginAssets(compilation, chunks); chunks.forEach(chunk => { chunk.files.forEach(file => { if (fs.existsSync(compilation.options.output.path+'/' + language + '.' + file)) { ret.js.unshift(ret.publicPath + language + '.' + file); } }) }); return ret; } } module.exports = TrlHtmlWebpackPlugin;
Fix: Return of boolean expressions should not be wrapped into an "if-then-else" statement (squid:S1126)
package se.vidstige.jadb; /** * Created by vidstige on 2014-03-20 */ public class RemoteFile { private final String path; public RemoteFile(String path) { this.path = path; } public String getName() { throw new UnsupportedOperationException(); } public int getSize() { throw new UnsupportedOperationException(); } public long getLastModified() { throw new UnsupportedOperationException(); } public boolean isDirectory() { throw new UnsupportedOperationException(); } public String getPath() { return path;} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteFile that = (RemoteFile) o; return path.equals(that.path); } @Override public int hashCode() { return path.hashCode(); } }
package se.vidstige.jadb; /** * Created by vidstige on 2014-03-20 */ public class RemoteFile { private final String path; public RemoteFile(String path) { this.path = path; } public String getName() { throw new UnsupportedOperationException(); } public int getSize() { throw new UnsupportedOperationException(); } public long getLastModified() { throw new UnsupportedOperationException(); } public boolean isDirectory() { throw new UnsupportedOperationException(); } public String getPath() { return path;} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteFile that = (RemoteFile) o; if (!path.equals(that.path)) return false; return true; } @Override public int hashCode() { return path.hashCode(); } }
Revert "reopen port to 80" This reverts commit 3cfed3456cbed7f6f4a71c114b2645a278b27979.
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: false, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 80, autoOpenBrowser: false, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
Increase max connections to 300 for mariadb
package org.synyx.urlaubsverwaltung; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.MariaDBContainer; import static org.testcontainers.containers.MariaDBContainer.NAME; public abstract class TestContainersBase { static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5") .withCommand("--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci", "--max-connections=300"); @DynamicPropertySource static void mariaDBProperties(DynamicPropertyRegistry registry) { mariaDB.start(); registry.add("spring.datasource.url", mariaDB::getJdbcUrl); registry.add("spring.datasource.username", mariaDB::getUsername); registry.add("spring.datasource.password", mariaDB::getPassword); } }
package org.synyx.urlaubsverwaltung; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.MariaDBContainer; import static org.testcontainers.containers.MariaDBContainer.NAME; public abstract class TestContainersBase { static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5") .withCommand("--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"); @DynamicPropertySource static void mariaDBProperties(DynamicPropertyRegistry registry) { mariaDB.start(); registry.add("spring.datasource.url", mariaDB::getJdbcUrl); registry.add("spring.datasource.username", mariaDB::getUsername); registry.add("spring.datasource.password", mariaDB::getPassword); } }
Fix for pydocstyle > 1.1.1
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2015-2016 The SublimeLinter Community # Copyright (c) 2013-2014 Aparajita Fishman # # License: MIT # """This module exports the Pydocstyle plugin linter class.""" from SublimeLinter.lint import PythonLinter, highlight, util class Pydocstyle(PythonLinter): """Provides an interface to the pydocstyle python module/script.""" syntax = 'python' if PythonLinter.which('pydocstyle'): cmd = 'pydocstyle@python' else: cmd = 'pep257@python' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.3.0' regex = r'^.+?:(?P<line>\d+).*:\r?\n\s*(?P<message>.+)$' multiline = True default_type = highlight.WARNING error_stream = util.STREAM_BOTH line_col_base = (0, 0) # pydocstyle uses one-based line and zero-based column numbers tempfile_suffix = 'py' defaults = { '--add-ignore=': '' } inline_overrides = ('add-ignore')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2015-2016 The SublimeLinter Community # Copyright (c) 2013-2014 Aparajita Fishman # # License: MIT # """This module exports the Pydocstyle plugin linter class.""" from SublimeLinter.lint import PythonLinter, highlight, util class Pydocstyle(PythonLinter): """Provides an interface to the pydocstyle python module/script.""" syntax = 'python' if PythonLinter.which('pydocstyle'): cmd = 'pydocstyle@python' else: cmd = 'pep257@python' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.3.0' regex = r'^.+?:(?P<line>\d+).*:\r?\n\s*(?P<message>.+)$' multiline = True default_type = highlight.WARNING error_stream = util.STREAM_STDERR line_col_base = (0, 0) # pydocstyle uses one-based line and zero-based column numbers tempfile_suffix = 'py' defaults = { '--add-ignore=': '' } inline_overrides = ('add-ignore')
Clear language build console before building.
package org.metaborg.spoofax.eclipse.meta.build; import java.io.PrintStream; import org.apache.tools.ant.DefaultLogger; import org.eclipse.ui.console.MessageConsole; import org.metaborg.spoofax.eclipse.util.ConsoleUtils; public class SpoofaxAntBuildLogger extends DefaultLogger { private final MessageConsole console; private final PrintStream stream; public SpoofaxAntBuildLogger() { super(); console = ConsoleUtils.get("Spoofax language build"); stream = new PrintStream(console.newMessageStream()); console.clearConsole(); console.activate(); } @Override protected void printMessage(String message, PrintStream unusedStream, int priority) { /* * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our * streams. */ super.printMessage(message, stream, priority); } }
package org.metaborg.spoofax.eclipse.meta.build; import java.io.PrintStream; import org.apache.tools.ant.DefaultLogger; import org.eclipse.ui.console.MessageConsole; import org.metaborg.spoofax.eclipse.util.ConsoleUtils; public class SpoofaxAntBuildLogger extends DefaultLogger { private final MessageConsole console; private final PrintStream stream; public SpoofaxAntBuildLogger() { super(); console = ConsoleUtils.get("Spoofax language build"); stream = new PrintStream(console.newMessageStream()); console.activate(); } @Override protected void printMessage(String message, PrintStream unusedStream, int priority) { /* * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our * streams. */ super.printMessage(message, stream, priority); } }
Replace == with === to test for equality
(function($) { $.fn.extend({ hotwire: function(delegate) { var target = this, args = $.makeArray(arguments), events = args.slice(1, args.length); $(events).each(function(i, eventName) { var words = $(eventName.split(/[_:]/)), titleized = words.map(function(i, word) { if (i === 0) { return word; } var firstChar = word.charAt(0).toUpperCase(), rest = word.slice(1, word.length); return firstChar + rest; }).toArray().join(""), handler = delegate[titleized]; target.bind(eventName, handler); }); return this; } }); })(jQuery);
(function($) { $.fn.extend({ hotwire: function(delegate) { var target = this, args = $.makeArray(arguments), events = args.slice(1, args.length); $(events).each(function(i, eventName) { var words = $(eventName.split(/[_:]/)), titleized = words.map(function(i, word) { if (i == 0) { return word; } var firstChar = word.charAt(0).toUpperCase(), rest = word.slice(1, word.length); return firstChar + rest; }).toArray().join(""), handler = delegate[titleized]; target.bind(eventName, handler); }); return this; } }); })(jQuery);
Fix documentation generating script to work with Python 3
# -*- coding: utf-8 -*- #!/usr/bin/python3 import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.abspath(os.path.dirname(__file__)) p1 = Popen('python -m sphinx -v -b html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, '_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0].decode('utf-8') if not result or 'build succeeded' not in result: raise RuntimeError('sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, 'documentation') if os.path.isdir(final_folder_path): shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, '_build') , final_folder_path)
# -*- coding: utf-8 -*- #!/usr/bin/python import os from subprocess import Popen, PIPE import shutil docs_folder_path = os.path.join(os.path.dirname(__file__)) p1 = Popen(u'sphinx-build -M html {src} {dst}'.format( src=docs_folder_path, dst=os.path.join(docs_folder_path, u'_build') ), shell=True, stdin=PIPE, stdout=PIPE) result = p1.communicate()[0] if not result or u'build succeeded' not in result: raise RuntimeError(u'sphinx-build failed') final_folder_path = os.path.join(docs_folder_path, u'documentation') shutil.rmtree(final_folder_path) shutil.copytree(os.path.join(docs_folder_path, u'_build', u'html') , final_folder_path)
Fix chld-show command line usage
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(program.file, function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
Solve bug, now it shows the new avatar uploaded
<?php /** * Created by PhpStorm. * User: Catalin * Date: 03-Jun-17 * Time: 13:59 */ include ("../../BACK/conectare_db.php"); $username = $_SESSION["username"]; $stid = oci_parse($connection, 'SELECT LINK FROM player WHERE username = :username'); oci_bind_by_name($stid, ':username', $username); oci_execute($stid); $row = oci_fetch_array($stid, OCI_BOTH); $link = $row[0]; oci_free_statement($stid); if (strcmp($link,'k') == 0) echo '<img src="../../../IMG/OTHER/user_icon.jpg' . filemtime($link) .'" style="max-width:100%; max-height:100%;" alt="alt">'; else echo '<img src="../'. $link . '" style="max-width:100%; max-height:100%;" alt="alt">';
<?php /** * Created by PhpStorm. * User: Catalin * Date: 03-Jun-17 * Time: 13:59 */ include ("../../BACK/conectare_db.php"); $username = $_SESSION["username"]; $stid = oci_parse($connection, 'SELECT LINK FROM player WHERE username = :username'); oci_bind_by_name($stid, ':username', $username); oci_execute($stid); $row = oci_fetch_array($stid, OCI_BOTH); $link = $row[0]; oci_free_statement($stid); if (strcmp($link,'k') == 0) echo '<img src="../../../IMG/OTHER/user_icon.jpg" style="max-width:100%; max-height:100%;" alt="alt">'; else echo '<img src="../'. $link . '" style="max-width:100%; max-height:100%;" alt="alt">';
Optimize SASS and JS output
'use strict' const { resolve } = require('path') const sass = require('rosid-handler-sass') const js = require('rosid-handler-js') const preload = require('../preload') const html = require('../ui/index') const optimize = process.env.NODE_ENV !== 'development' const index = async () => { return html() } const styles = async () => { const filePath = resolve(__dirname, '../ui/styles/index.scss') return sass(filePath, { optimize }) } const scripts = async () => { console.log(process.env.NODE_ENV !== 'development') const filePath = resolve(__dirname, '../ui/scripts/index.js') const babel = { presets: [ [ '@babel/preset-env', { targets: { browsers: [ 'last 2 Safari versions', 'last 2 Chrome versions', 'last 2 Opera versions', 'last 2 Firefox versions' ] } } ] ], babelrc: false } return js(filePath, { optimize, babel }) } module.exports = { index: optimize === true ? preload(index) : index, styles: optimize === true ? preload(styles) : styles, scripts: optimize === true ? preload(scripts) : scripts }
'use strict' const path = require('path') const sass = require('rosid-handler-sass') const js = require('rosid-handler-js') const preload = require('../preload') const html = require('../ui/index') const index = async () => { return html() } const styles = async () => { const filePath = path.resolve(__dirname, '../ui/styles/index.scss') const opts = { optimize: true } return sass(filePath, opts) } const scripts = async () => { const filePath = path.resolve(__dirname, '../ui/scripts/index.js') const babel = { presets: [ [ '@babel/preset-env', { targets: { browsers: [ 'last 2 Safari versions', 'last 2 Chrome versions', 'last 2 Opera versions', 'last 2 Firefox versions' ] } } ] ], babelrc: false } const opts = { optimize: false, browserify: {}, babel } return js(filePath, opts) } module.exports = { index: process.env.NODE_ENV === 'development' ? index : preload(index), styles: process.env.NODE_ENV === 'development' ? styles : preload(styles), scripts: process.env.NODE_ENV === 'development' ? scripts : preload(scripts) }
Fix dust driver to include innerHTML
'use strict' const fs = require('fs') const escapeHTML = require('escape-html') module.exports = createDustRenderer function createDustRenderer () { const dust = require('dustjs-linkedin') dust.config.cache = false dust.helpers.component = component dust.onLoad = onLoad return function render (name, opts = {}) { return new Promise((resolve, reject) => { dust.render(name, opts, (err, content) => { if (err) return reject(err) resolve(content) }) }) } function component (chunk, context, bodies, params) { const props = params const name = props.name const tagName = props.tagName || 'div' delete props.name delete props.tagName chunk.write( `<${tagName} \ data-component='${name}' \ data-props='${escapeHTML(JSON.stringify(props))}'>` ) if (bodies.block) chunk.render(bodies.block, context) chunk.write(`</${tagName}>`) } function onLoad (templateName, opts, callback) { fs.readFile(templateName + '.html', 'utf8', (err, src) => { if (err) return callback(err) let compiled try { compiled = dust.compile(src, templateName) } catch (err) { return callback(err) } callback(null, dust.loadSource(compiled)) }) } }
'use strict' const fs = require('fs') const { resolve } = require('url') const escapeHTML = require('escape-html') module.exports = createDustRenderer function createDustRenderer () { const dust = require('dustjs-linkedin') dust.config.cache = false dust.helpers.component = component dust.onLoad = onLoad return function render (name, opts = {}) { return new Promise((resolve, reject) => { dust.render(name, opts, (err, content) => { if (err) return reject(err) resolve(content) }) }) } function component (chunk, context, bodies, params) { const props = params const name = props.name const tagName = props.tagName || 'div' delete props.name delete props.tagName chunk.write( `<${tagName} \ data-component='${name}' \ data-props='${escapeHTML(JSON.stringify(props))}'></${tagName}>` ) } function onLoad (templateName, opts, callback) { fs.readFile(templateName + '.html', 'utf8', (err, src) => { if (err) return callback(err) let compiled try { compiled = dust.compile(src, templateName) } catch (err) { return callback(err) } callback(null, dust.loadSource(compiled)) }) } }
build: Copy only required files to bower dist * Prevents the images from being copied also.
var gulp = require('gulp'); var gutil = require('gulp-util'); var exec = require('gulp-exec'); var less = require('gulp-less'); var minifycss = require('gulp-minify-css'); //var jshint = require('gulp-jshint'); var uglify = require('gulp-uglify'); //var imagemin = require('gulp-imagemin'); var rename = require('gulp-rename'); var clean = require('gulp-clean'); var concat = require('gulp-concat'); var cache = require('gulp-cache'); var livereload = require('gulp-livereload'); var lr = require('tiny-lr'); var server = lr(); gulp.task('default', function() { // place code for your default task here }); gulp.task('script-dev', function() { return gulp.src('src/*.js') .pipe(livereload(server)); }); gulp.task('css-dev', function() { return gulp.src('src/css/*.css') .pipe(livereload(server)); }); gulp.task('watch', function() { server.listen(35729, function(err) { if (err) { return console.log(err); } gulp.watch('src/*.js', ['script-dev']); gulp.watch('src/css/*.css', ['css-dev']); }); }); gulp.task('dist', function() { gulp.src(['src/*.js', 'src/**/*.css']) .pipe(gulp.dest('bower')); });
var gulp = require('gulp'); var gutil = require('gulp-util'); var exec = require('gulp-exec'); var less = require('gulp-less'); var minifycss = require('gulp-minify-css'); //var jshint = require('gulp-jshint'); var uglify = require('gulp-uglify'); //var imagemin = require('gulp-imagemin'); var rename = require('gulp-rename'); var clean = require('gulp-clean'); var concat = require('gulp-concat'); var cache = require('gulp-cache'); var livereload = require('gulp-livereload'); var lr = require('tiny-lr'); var server = lr(); gulp.task('default', function() { // place code for your default task here }); gulp.task('script-dev', function() { return gulp.src('src/*.js') .pipe(livereload(server)); }); gulp.task('css-dev', function() { return gulp.src('src/css/*.css') .pipe(livereload(server)); }); gulp.task('watch', function() { server.listen(35729, function(err) { if (err) { return console.log(err); } gulp.watch('src/*.js', ['script-dev']); gulp.watch('src/css/*.css', ['css-dev']); }); }); gulp.task('dist', function() { gulp.src('src/**/*') .pipe(gulp.dest('bower')); });
Enable full repo name search
'use strict'; angular.module('visualizerApp') .controller('ExploreController', ['$scope', '$upload', '$location', '$http', '$timeout', '$filter', 'jsonFactory', function ($scope, $upload, $location, $http, $timeout, $filter, jsonFactory) { $scope.fileApiSupport = jsonFactory.fileApiSupport; $scope.repos = []; $scope.filteredRepos = []; $scope.perColumn = 0; $scope.searchText = ''; jsonFactory.init .success(function() { $scope.repos = jsonFactory.repositories.map(function(r) { return { owner: r.owner, repo: r.repo, name: r.owner + '/' + r.repo }; }); filterRepos(); }); track(); /* Filter */ $scope.$watch('searchText', filterRepos); $scope.onFileClick = function onFileClick(repo) { $location.path('/display/' + repo.owner + '/' + repo.repo); }; $scope.openProject = function openProject() { if ($scope.filteredRepos.length > 0) { $scope.onFileClick($scope.filteredRepos[0]); } }; function filterRepos(value) { $scope.filteredRepos = $filter('filter')($scope.repos, {$:value}); $scope.perColumn = Math.ceil($scope.filteredRepos.length / 3); } function track() { ga('send', 'pageview', {'page': $location.path()}); } }]);
'use strict'; angular.module('visualizerApp') .controller('ExploreController', ['$scope', '$upload', '$location', '$http', '$timeout', '$filter', 'jsonFactory', function ($scope, $upload, $location, $http, $timeout, $filter, jsonFactory) { $scope.fileApiSupport = jsonFactory.fileApiSupport; $scope.repos = []; $scope.filteredRepos = []; $scope.perColumn = 0; $scope.searchText = ''; jsonFactory.init .success(function() { $scope.repos = jsonFactory.repositories.map(function(r) { return { owner: r.owner, repo: r.repo }; }); filterRepos(); }); track(); /* Filter */ $scope.$watch('searchText', filterRepos); $scope.onFileClick = function onFileClick(repo) { $location.path('/display/' + repo.owner + '/' + repo.repo); }; $scope.openProject = function openProject() { if ($scope.filteredRepos.length > 0) { $scope.onFileClick($scope.filteredRepos[0]); } }; function filterRepos(value) { $scope.filteredRepos = $filter('filter')($scope.repos, {$:value}); $scope.perColumn = Math.ceil($scope.filteredRepos.length / 3); } function track() { ga('send', 'pageview', {'page': $location.path()}); } }]);
Add same shortcut on submenu
<?php use PhpSchool\CliMenu\Builder\SplitItemBuilder; use PhpSchool\CliMenu\CliMenu; use PhpSchool\CliMenu\Builder\CliMenuBuilder; require_once(__DIR__ . '/../vendor/autoload.php'); $itemCallable = function (CliMenu $menu) { echo $menu->getSelectedItem()->getText(); }; $menu = (new CliMenuBuilder) ->setTitle('Basic CLI Menu') ->addItem('[F]irst Item', $itemCallable) ->addItem('Se[c]ond Item', $itemCallable) ->addItem('Third [I]tem', $itemCallable) ->addSubMenu('[O]ptions', function (CliMenuBuilder $b) { $b->setTitle('CLI Menu > Options') ->addItem('[F]irst option', function (CliMenu $menu) { echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); }) ->addLineBreak('-'); }) ->addSplitItem(function (SplitItemBuilder $b) { $b->addItem('Split Item [1]', function() { echo 'Split Item 1!'; }) ->addItem('Split Item [2]', function() { echo 'Split Item 2!'; }) ->addItem('Split Item [3]', function() { echo 'Split Item 3!'; }); }) ->addLineBreak('-') ->build(); $menu->open();
<?php use PhpSchool\CliMenu\Builder\SplitItemBuilder; use PhpSchool\CliMenu\CliMenu; use PhpSchool\CliMenu\Builder\CliMenuBuilder; require_once(__DIR__ . '/../vendor/autoload.php'); $itemCallable = function (CliMenu $menu) { echo $menu->getSelectedItem()->getText(); }; $menu = (new CliMenuBuilder) ->setTitle('Basic CLI Menu') ->addItem('[F]irst Item', $itemCallable) ->addItem('Se[c]ond Item', $itemCallable) ->addItem('Third [I]tem', $itemCallable) ->addSubMenu('[O]ptions', function (CliMenuBuilder $b) { $b->setTitle('CLI Menu > Options') ->addItem('First option', function (CliMenu $menu) { echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); }) ->addLineBreak('-'); }) ->addSplitItem(function (SplitItemBuilder $b) { $b->addItem('Split Item [1]', function() { echo 'Split Item 1!'; }) ->addItem('Split Item [2]', function() { echo 'Split Item 2!'; }) ->addItem('Split Item [3]', function() { echo 'Split Item 3!'; }); }) ->addLineBreak('-') ->build(); $menu->open();
Set cookie also if "What is.." is clicked.
$(function() { var cookieName = '_wheelmap_splash_seen'; if(!$.cookie(cookieName)) { width = 600; // splash width // calculate left edge so it is centered left = (0.5 - (width / 2)/($(window).width())) * 100 + '%'; $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: width + 'px' } }); var clickHandler = function() { $.unblockUI(); $.cookie(cookieName, true); return false; }; $("#splash .unblock-splash").click(clickHandler); $('.blockOverlay').css('cursor', 'auto').click(clickHandler); $('a.whatis').click(function() { $.cookie(cookieName, true); return true; }); } })
$(function() { var cookieName = '_wheelmap_splash_seen'; if(!$.cookie(cookieName)) { wwidth = $(window).width(); left = (0.5 - 300/wwidth) * 100 + '%'; $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: '600px' } }); $("#splash .unblock-splash").click($.unblockUI) $('.blockOverlay').css('cursor', 'auto').click(function() { $.unblockUI(); $.cookie(cookieName, true) }); } })
Switch from hstore to jsonb
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInfoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('info',function(Blueprint $table) { $table->increments('infoID'); $table->jsonb('info'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::drop('info'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInfoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('info',function(Blueprint $table) { $table->increments('infoID'); $table->hstore('info'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::drop('info'); } }
Fix RichTextField form field generation. All standard properties that would affect formfield were being ignored (such as blank=True).
from django import forms from django.db import models class RichTextFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): super(RichTextFormField, self).__init__(*args, **kwargs) css_class = self.widget.attrs.get('class', '') css_class += ' item-richtext' self.widget.attrs['class'] = css_class def clean(self, value): # TODO add cleansing here? return super(RichTextFormField, self).clean(value) class RichTextField(models.TextField): """ Drop-in replacement for Django's ``models.TextField`` which allows editing rich text instead of plain text in the item editor. """ def formfield(self, form_class=RichTextFormField, **kwargs): return super(RichTextField, self).formfield(form_class=form_class, **kwargs) try: from south.modelsinspector import add_introspection_rules RichTextField_introspection_rule = ( (RichTextField,), [], {}, ) add_introspection_rules(rules=[RichTextField_introspection_rule], patterns=["^feincms\.contrib\.richtext"]) except ImportError: pass
from django import forms from django.db import models class RichTextFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): super(RichTextFormField, self).__init__(*args, **kwargs) css_class = self.widget.attrs.get('class', '') css_class += ' item-richtext' self.widget.attrs['class'] = css_class def clean(self, value): # TODO add cleansing here? return super(RichTextFormField, self).clean(value) class RichTextField(models.TextField): """ Drop-in replacement for Django's ``models.TextField`` which allows editing rich text instead of plain text in the item editor. """ formfield = RichTextFormField try: from south.modelsinspector import add_introspection_rules RichTextField_introspection_rule = ( (RichTextField,), [], {}, ) add_introspection_rules(rules=[RichTextField_introspection_rule], patterns=["^feincms\.contrib\.richtext"]) except ImportError: pass
Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args
Debug info is no longer returned automatically with every exception. Use Factual::debug() instead.
<?php /** * Represents an Exception that happened while communicating with Factual. * Includes information about the request that triggered the problem. * This is a refactoring of the Factual Driver by Aaron: https://github.com/Factual/factual-java-driver * @author Tyler * @package Factual * @license Apache 2.0 */ class FactualApiException extends Exception { protected $info; //debug array protected $helpUrl = "https://github.com/Factual/factual-php-driver/wiki/Debugging-and-Support"; public function __construct($info) { $this->info = $info; $this->message = $info['message']; $this->message .= " Use Factual::debug() to echo detailed debug info to stdout, " . "or use FactualApiException::debug() to obtain debug information " . "programatically. See ". $this->helpUrl. " for information on " . "debug mode, submitting issues, and figuring out, generally, WTF is going on"; } public function debug(){ return $this->info; } } ?>
<?php /** * Represents an Exception that happened while communicating with Factual. * Includes information about the request that triggered the problem. * This is a refactoring of the Factual Driver by Aaron: https://github.com/Factual/factual-java-driver * @author Tyler * @package Factual * @license Apache 2.0 */ class FactualApiException extends Exception { protected $info; //debug array protected $helpUrl = "https://github.com/Factual/factual-php-driver#help-debugging--testing"; public function __construct($info) { $this->info = $info; $this->message = $info['message']." Details:\n".print_r($info,true)."\n use FactualApiException::debug()" . " to obtain this information programatically. See ". $this->helpUrl. " for information on submitting bugs and questions.\n\n"; } public function debug(){ return $this->info; } } ?>
Fix bug : Reuse connection pool
package com.qubole.streamx.s3.wal; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.kafka.connect.errors.ConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.PropertyVetoException; import java.util.HashMap; public class ConnectionPool { private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class); private static HashMap<String, ComboPooledDataSource> dataSources = new HashMap<>(); public static ComboPooledDataSource getDatasource(String connectionUrl, String user, String password) { if(dataSources.containsKey(connectionUrl)) { return dataSources.get(connectionUrl); } else { try { ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver cpds.setJdbcUrl(connectionUrl); cpds.setUser(user); cpds.setPassword(password); cpds.setMaxConnectionAge(18000);//5 hours dataSources.put(connectionUrl, cpds); return cpds; } catch (PropertyVetoException e) { log.error("Error while creating c3p0 ComboPooledDataSource" + e); throw new ConnectException(e); } } } }
package com.qubole.streamx.s3.wal; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.kafka.connect.errors.ConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.PropertyVetoException; import java.util.HashMap; public class ConnectionPool { private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class); private static HashMap<String, ComboPooledDataSource> dataSources = new HashMap<>(); public static ComboPooledDataSource getDatasource(String connectionUrl, String user, String password) { if(dataSources.containsKey(connectionUrl)) { return dataSources.get(connectionUrl); } else { try { ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver cpds.setJdbcUrl(connectionUrl); cpds.setUser(user); cpds.setPassword(password); cpds.setMaxConnectionAge(18000);//5 hours return cpds; } catch (PropertyVetoException e) { log.error("Error while creating c3p0 ComboPooledDataSource" + e); throw new ConnectException(e); } } } }
Change a URL to a ftp file in the ftp staging test.
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.uconn.edu/48_hour/file_test_cpt.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
Rename some copy pasted variable.
from graphql.core.type import GraphQLScalarType class ScalarMeta(type): def __new__(mcs, name, bases, attrs): if attrs.pop('abstract', False): return super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs) registry = mcs._get_registry() cls = super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs) cls._registry = registry instance = cls() serialize = getattr(instance, 'serialize') parse_literal = getattr(instance, 'parse_literal') parse_value = getattr(instance, 'parse_value') mcs._register(GraphQLScalarType( name=name, description=attrs.get('__doc__', None), serialize=serialize, parse_value=parse_value, parse_literal=parse_literal )) @staticmethod def _register(scalar): raise NotImplementedError('_register must be implemented in the sub-metaclass') @staticmethod def _get_registry(): raise NotImplementedError('_get_registry must be implemented in the sub-metaclass')
from graphql.core.type import GraphQLScalarType class ScalarMeta(type): def __new__(mcs, name, bases, attrs): if attrs.pop('abstract', False): return super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs) registry = mcs._get_registry() cls = super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs) cls._registry = registry instance = cls() serialize = getattr(instance, 'serialize') parse_literal = getattr(instance, 'parse_literal') parse_value = getattr(instance, 'parse_value') mcs._register(GraphQLScalarType( name=name, description=attrs.get('__doc__', None), serialize=serialize, parse_value=parse_value, parse_literal=parse_literal )) @staticmethod def _register(mutation): raise NotImplementedError('_register must be implemented in the sub-metaclass') @staticmethod def _get_registry(): raise NotImplementedError('_get_registry must be implemented in the sub-metaclass')
Move attribute to "selector" in defaults from "syntax", as suggested by SublimeLinter
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, util, highlight class PugLint(NodeLinter): """Provides an interface to pug-lint.""" npm_name = 'pug-lint' cmd = 'pug-lint @ *' executable = None version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.1.1' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH config_file = ('--config', '.pug-lintrc', '.pug-lint.json', '.jade-lintrc', '.jade-lint.json', '~') defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = highlight.WARNING
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, util, highlight class PugLint(NodeLinter): """Provides an interface to pug-lint.""" npm_name = 'pug-lint' syntax = ('pug', 'jade') cmd = 'pug-lint @ *' executable = None version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.1.1' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH config_file = ('--config', '.pug-lintrc', '.pug-lint.json', '.jade-lintrc', '.jade-lint.json', '~') defaults = {'--reporter=': 'inline'} default_type = highlight.WARNING
Remove explicit unicode encoding on strings
from wtforms import Field from wtforms.widgets import TextInput class TagListField(Field): """ Field for comma-separated list of tags. """ widget = TextInput() def _value(self): if self.data: try: # The data is a list of strings return ', '.join(self.data) except TypeError: # The data is a list of Tag objects return ', '.join([tag.name for tag in self.data]) else: return '' def process_formdata(self, valuelist): if valuelist: try: # The data is a string self.data = [x.strip() for x in valuelist[0].split(',') if x] except AttributeError: # The data is a list of Tag objects self.data = [tag.name for tag in valuelist[0]] else: self.data = []
from wtforms import Field from wtforms.widgets import TextInput class TagListField(Field): """ Field for comma-separated list of tags. From http://wtforms.readthedocs.org/en/latest/fields.html#custom-fields """ widget = TextInput() def _value(self): if self.data: try: # The data is a list of strings return u', '.join(self.data) except TypeError: # The data is a list of Tag objects return u', '.join([tag.name for tag in self.data]) else: return u'' def process_formdata(self, valuelist): if valuelist: try: # The data is a string self.data = [x.strip() for x in valuelist[0].split(',') if x] except AttributeError: # The data is a list of Tag objects self.data = [tag.name for tag in valuelist[0]] else: self.data = []
Refactor out applying function. Throw if invalid.
var _ = require('underscore'); SYMBOL_TABLE = {} exports.define = function (sym, val) { SYMBOL_TABLE[sym] = val; } exports.apply = function (fn, args, stack_frame) { if (typeof fn != 'function') throw "cannot evaluate non-function value: " + fn; args.unshift(stack_frame); return fn.apply(undefined, args); } exports.eval = function eval(form, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } if (_.isEqual(form, null)) { return null; } if (form.type == 'id') return stack_frame[form.name]; else if (_.isArray(form)) { var func = eval(form[0], stack_frame); var args = form.slice(1); return exports.apply(func, args, stack_frame); } else { return form; } } exports.evalAll = function (forms, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } var results = []; for (var i = 0; i < forms.length; i++) { results[i] = exports.eval(forms[i], stack_frame); } return results[results.length - 1]; // return last form } exports.define('stack', function (_s) { console.log(_s); }); exports.define('sym', function () { console.log(SYMBOL_TABLE); });
var _ = require('underscore'); SYMBOL_TABLE = {} exports.define = function (sym, val) { SYMBOL_TABLE[sym] = val; } exports.eval = function eval(form, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } if (_.isEqual(form, null)) { return null; } if (form.type == 'id') return stack_frame[form.name]; else if (_.isArray(form)) { var func = eval(form[0], stack_frame); var args = form.slice(1); args.unshift(stack_frame); return func.apply(undefined, args); } else { return form; } } exports.evalAll = function (forms, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } var results = []; for (var i = 0; i < forms.length; i++) { results[i] = exports.eval(forms[i], stack_frame); } return results[results.length - 1]; // return last form } exports.define('stack', function (_s) { console.log(_s); }); exports.define('sym', function () { console.log(SYMBOL_TABLE); });
Use tools/tsan.supp for TSAN suppressions. BUG=skia: R=borenet@google.com, mtklein@google.com Author: mtklein@chromium.org Review URL: https://codereview.chromium.org/266393003
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Utilities for ASAN,TSAN,etc. build steps. """ from default_build_step_utils import DefaultBuildStepUtils from utils import shell_utils import os LLVM_PATH = '/home/chrome-bot/llvm-3.4/Release+Asserts/bin/' class XsanBuildStepUtils(DefaultBuildStepUtils): def Compile(self, target): # Run the xsan_build script. os.environ['PATH'] = LLVM_PATH + ':' + os.environ['PATH'] shell_utils.run(['which', 'clang']) shell_utils.run(['clang', '--version']) os.environ['GYP_DEFINES'] = self._step.args['gyp_defines'] print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES'] cmd = [ os.path.join('tools', 'xsan_build'), self._step.args['sanitizer'], target, 'BUILDTYPE=%s' % self._step.configuration, ] cmd.extend(self._step.default_make_flags) cmd.extend(self._step.make_flags) shell_utils.run(cmd) def RunFlavoredCmd(self, app, args): os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp' return shell_utils.run([self._PathToBinary(app)] + args)
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Utilities for ASAN,TSAN,etc. build steps. """ from default_build_step_utils import DefaultBuildStepUtils from utils import shell_utils import os LLVM_PATH = '/home/chrome-bot/llvm-3.4/Release+Asserts/bin/' class XsanBuildStepUtils(DefaultBuildStepUtils): def Compile(self, target): # Run the xsan_build script. os.environ['PATH'] = LLVM_PATH + ':' + os.environ['PATH'] shell_utils.run(['which', 'clang']) shell_utils.run(['clang', '--version']) os.environ['GYP_DEFINES'] = self._step.args['gyp_defines'] print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES'] cmd = [ os.path.join('tools', 'xsan_build'), self._step.args['sanitizer'], target, 'BUILDTYPE=%s' % self._step.configuration, ] cmd.extend(self._step.default_make_flags) cmd.extend(self._step.make_flags) shell_utils.run(cmd)
Add fancy commas to member and guild counts
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Gets the current guild and UNIQUE member counts. * * @param {CommandoClient} client - The Discord.JS-Commando Client object * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts. */ exports.getGuildsAndMembers = client => { // Algorithm provided by CyberPon3 // https://github.com/CyberPon3 let members = client.guilds.reduce( (acc, guild) => { guild.members .filter(member => !member.user.bot) .forEach(member => acc.add(member.id)); return acc; }, new Set() ).size; let guilds = client.guilds.array().length; return { members: members.toLocaleString(), guilds: guilds.toLocaleString() }; }; exports.setGame = client => { let { members, guilds } = this.getGuildsAndMembers(client); client.user.setPresence({ game: { name:`for ${client.commandPrefix || client.options.commandPrefix}help | ${members} members across ${guilds} guilds`, type: 'WATCHING' } }); };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Gets the current guild and UNIQUE member counts. * * @param {CommandoClient} client - The Discord.JS-Commando Client object * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts. */ exports.getGuildsAndMembers = client => { // Algorithm provided by CyberPon3 // https://github.com/CyberPon3 let members = client.guilds.reduce( (acc, guild) => { guild.members .filter(member => !member.user.bot) .forEach(member => acc.add(member.id)); return acc; }, new Set() ).size; let guilds = client.guilds.array().length; return { members: members, guilds: guilds }; }; exports.setGame = client => { let { members, guilds } = this.getGuildsAndMembers(client); client.user.setPresence({ game: { name:`for ${client.commandPrefix || client.options.commandPrefix}help | ${members} members across ${guilds} guilds`, type: 'WATCHING' } }); };
Add link for simple-prefs doc
// see: // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/hotkeys // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/simple-prefs // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/windows#BrowserWindow var self = require('sdk/self'); var { Hotkey } = require("sdk/hotkeys"); var hopUpKey = Hotkey({ combo: "accel-alt-shift-]", onPress: function() { hopTabs("up"); } }); var hopDownKey = Hotkey({ combo: "accel-alt-shift-[", onPress: function() { hopTabs("down"); } }); function hopTabs(direction) { var window = require("sdk/windows").browserWindows.activeWindow; var hop = require('sdk/simple-prefs').prefs['tabhopperHop']; if (direction == "down") { hop = -hop; } var nextTab = window.tabs.activeTab.index + hop; if (nextTab >= window.tabs.length) { nextTab = window.tabs.length - 1; } else if (nextTab < 0) { nextTab = 0; } window.tabs[nextTab].activate(); }
// see: // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/hotkeys // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs // https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/windows#BrowserWindow var self = require('sdk/self'); var { Hotkey } = require("sdk/hotkeys"); var hopUpKey = Hotkey({ combo: "accel-alt-shift-]", onPress: function() { hopTabs("up"); } }); var hopDownKey = Hotkey({ combo: "accel-alt-shift-[", onPress: function() { hopTabs("down"); } }); function hopTabs(direction) { var window = require("sdk/windows").browserWindows.activeWindow; var hop = require('sdk/simple-prefs').prefs['tabhopperHop']; if (direction == "down") { hop = -hop; } var nextTab = window.tabs.activeTab.index + hop; if (nextTab >= window.tabs.length) { nextTab = window.tabs.length - 1; } else if (nextTab < 0) { nextTab = 0; } window.tabs[nextTab].activate(); }
Fix type in Payment call
<?php class Ontic_NoFraud_Model_Sales_Order_Observer { /* * Observer for the order saved event */ public function sales_order_place_after( $observer ) { try { $order = $observer->getOrder(); $cardnumber = $order->getPayment()->getCcNumber(); $host = Mage::getStoreConfig('ontic/nofraud/host'); // core_config_data $username = Mage::getStoreConfig('ontic/nofraud/username'); $password = Mage::getStoreConfig('ontic/nofraud/password'); $data = array( 'credit_card' => $cardnumber ); $json = json_encode($data); $client = new Zend_Http_Client($host); $client->setAuth($username, $password, Zend_Http_Client::AUTH_BASIC); $client->setRawData($json, 'application/json'); $result = $client->request(Zend_Http_Client::POST)->getBody(); Mage::log('Response: '.$result); } catch ( Exception $e ) { Mage::log( "Error processing NoFraud transaction: " . $e->getMessage() ); } } } ?>
<?php class Ontic_NoFraud_Model_Sales_Order_Observer { /* * Observer for the order saved event */ public function sales_order_place_after( $observer ) { try { $order = $observer->getOrder(); $cardnumber = $order->getPayment->getCcNumber(); $host = Mage::getStoreConfig('ontic/nofraud/host'); // core_config_data $username = Mage::getStoreConfig('ontic/nofraud/username'); $password = Mage::getStoreConfig('ontic/nofraud/password'); $data = array( 'credit_card' => $cardnumber ); $json = json_encode($data); $client = new Zend_Http_Client($host); $client->setAuth($username, $password, Zend_Http_Client::AUTH_BASIC); $client->setRawData($json, 'application/json'); $result = $client->request(Zend_Http_Client::POST)->getBody(); Mage::log('Response: '.$result); } catch ( Exception $e ) { Mage::log( "Error processing NoFraud transaction: " . $e->getMessage() ); } } } ?>
Move filter inheritance code below `inherits` call
/* * hub.js * * Copyright (c) 2012-2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var inherits = require('inherits'); var Filter = require('glob-filter').Filter; var AsyncEmitter = require('async-glob-events').AsyncEmitter; function defaultCallback(err) { if (err) { throw err; } } function Hub() { AsyncEmitter.call(this); Filter.call(this, { reverse : true }); } inherits(Hub, AsyncEmitter); Object.keys(Filter.prototype).forEach(function (key) { if (key !== 'emit') { Hub.prototype[key] = Filter.prototype[key]; } }); var emit = Filter.prototype.emit; var invoke = AsyncEmitter.prototype.invoke; Hub.prototype.invoke = function (iterator, scope, callback) { emit.call(this, scope, function (cb) { invoke.call(this, iterator, scope, cb); }, callback || defaultCallback); }; Hub.prototype.removeAll = function (event) { this.removeAllFilters(event); this.removeAllListeners(event); }; exports.Hub = Hub;
/* * hub.js * * Copyright (c) 2012-2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var inherits = require('inherits'); var Filter = require('glob-filter').Filter; var AsyncEmitter = require('async-glob-events').AsyncEmitter; function defaultCallback(err) { if (err) { throw err; } } function Hub() { AsyncEmitter.call(this); Filter.call(this, { reverse : true }); } inherits(Hub, AsyncEmitter); var emit = Filter.prototype.emit; var invoke = AsyncEmitter.prototype.invoke; Hub.prototype.invoke = function (iterator, scope, callback) { emit.call(this, scope, function (cb) { invoke.call(this, iterator, scope, cb); }, callback || defaultCallback); }; Object.keys(Filter.prototype).forEach(function (key) { if (key !== 'emit') { Hub.prototype[key] = Filter.prototype[key]; } }); Hub.prototype.removeAll = function (event) { this.removeAllFilters(event); this.removeAllListeners(event); }; exports.Hub = Hub;
Use Infinity blockScrolling for ace editor
class ModelController { constructor($rootScope, $parse) { this.$parse = $parse; this.listener = $rootScope.$on('render', (event, component) => { this.render(event, component); }); this.settings = { mode: 'json', useWrapMode : true, // showGutter: false, onLoad: this.onEditorChange.bind(this), $blockScrolling: Infinity } this.$rootScope = $rootScope; this.inFirst = true; } $onDestroy() { this.listener(); } onEditorChange(editor) { let session = editor.getSession(); session.on("change", (e) => { this.broadcastModel(session.getValue()); }); } broadcastModel(model) { if (this.inFirst) { this.inFirst = false; return; } try { let v = JSON.parse(model); this.$rootScope.$broadcast('model', v); } catch(e) {} } render(event, component) { this.model = JSON.stringify(component.model, null, Number(4)); } } export default ModelController;
class ModelController { constructor($rootScope, $parse) { this.$parse = $parse; this.listener = $rootScope.$on('render', (event, component) => { this.render(event, component); }); this.settings = { mode: 'json', useWrapMode : true, // showGutter: false, onLoad: this.onEditorChange.bind(this) } this.$rootScope = $rootScope; this.inFirst = true; } $onDestroy() { this.listener(); } onEditorChange(editor) { let session = editor.getSession(); session.on("change", (e) => { this.broadcastModel(session.getValue()); }); } broadcastModel(model) { if (this.inFirst) { this.inFirst = false; return; } try { let v = JSON.parse(model); this.$rootScope.$broadcast('model', v); } catch(e) {} } render(event, component) { this.model = JSON.stringify(component.model, null, Number(4)); } } export default ModelController;
Update Gravatar to use protocol relative URL Stops warnings over SSL.
/** * @ngdoc directive * @name umbraco.directives.directive:umbAvatar * @restrict E **/ function avatarDirective() { return { restrict: "E", // restrict to an element replace: true, // replace the html element with the template templateUrl: 'views/directives/umb-avatar.html', scope: { name: '@', email: '@', hash: '@' }, link: function(scope, element, attr, ctrl) { scope.$watch("hash", function (val) { //set the gravatar url scope.gravatar = "//www.gravatar.com/avatar/" + val + "?s=40"; }); } }; } angular.module('umbraco.directives').directive("umbAvatar", avatarDirective);
/** * @ngdoc directive * @name umbraco.directives.directive:umbAvatar * @restrict E **/ function avatarDirective() { return { restrict: "E", // restrict to an element replace: true, // replace the html element with the template templateUrl: 'views/directives/umb-avatar.html', scope: { name: '@', email: '@', hash: '@' }, link: function(scope, element, attr, ctrl) { scope.$watch("hash", function (val) { //set the gravatar url scope.gravatar = "http://www.gravatar.com/avatar/" + val + "?s=40"; }); } }; } angular.module('umbraco.directives').directive("umbAvatar", avatarDirective);
[UnitTest] Fix incorrect datatype on argument
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018-2019, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit / App / System / Core / Classes */ declare(strict_types=1); namespace PH7\Test\Unit\App\System\Core\Classes; require_once PH7_PATH_SYS . 'core/classes/UserBirthDateCore.php'; use PH7\UserBirthDateCore; use PHPUnit\Framework\TestCase; class UserBirthDateCoreTest extends TestCase { /** * @dataProvider invalidBirthDateProvider */ public function testInvalidAgeFromBirthDate(?string $sBirthDate): void { $iAge = UserBirthDateCore::getAgeFromBirthDate($sBirthDate); $this->assertSame($iAge, UserBirthDateCore::DEFAULT_AGE); } public function invalidBirthDateProvider(): array { return [ ['01902'], ['01-20-2919-29'], [null] ]; } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018-2019, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit / App / System / Core / Classes */ declare(strict_types=1); namespace PH7\Test\Unit\App\System\Core\Classes; require_once PH7_PATH_SYS . 'core/classes/UserBirthDateCore.php'; use PH7\UserBirthDateCore; use PHPUnit\Framework\TestCase; class UserBirthDateCoreTest extends TestCase { /** * @dataProvider invalidBirthDateProvider */ public function testInvalidAgeFromBirthDate(string $sBirthDate): void { $iAge = UserBirthDateCore::getAgeFromBirthDate($sBirthDate); $this->assertSame($iAge, UserBirthDateCore::DEFAULT_AGE); } public function invalidBirthDateProvider(): array { return [ ['01902'], ['01-20-2919-29'], [null] ]; } }
Clear spaces - fix indent
/* TRUNK */ package bingo; import java.util.ArrayList; public class BingoCard { //private int[] cardNumbers = new int[24]; //NumberCollection nc =new NumberCollection(); private ArrayList<Integer> cardNumbers = new ArrayList<Integer>(); public BingoCard(){ generateNumbers(24); } private void generateNumbers(int n){ } public void stampNumber(int n){} public boolean containsNumber(int n){ return false; } public int numbersStamped(){ return 0; } public NumberCollection numberMissing(){ NumberCollection nc =new NumberCollection(); return nc; } }
/* TRUNK */ package bingo; import java.util.ArrayList; public class BingoCard { //private int[] cardNumbers = new int[24]; //NumberCollection nc =new NumberCollection(); private ArrayList<Integer> cardNumbers = new ArrayList<Integer>(); public BingoCard(){ generateNumbers(24); } private void generateNumbers(int n){ } public void stampNumber(int n){} public boolean containsNumber(int n){ return false; } public int numbersStamped(){ return 0; } public NumberCollection numberMissing(){ NumberCollection nc =new NumberCollection(); return nc; } }
Add sql query which returns a specific trait accoring to its cvterm_id
<?php namespace ajax\details; use \PDO as PDO; /** * Web Service. * Returns Trait informatio */ class Traits extends \WebService { /** * @param $querydata[] * @returns array of traits */ public function execute($querydata) { global $db; $type_cvterm_id = $querydata['type_cvterm_id']; $placeholders = implode(',', array_fill(0, count($type_cvterm_id), '?')); $query_get_trait = <<<EOF SELECT * FROM trait_cvterm WHERE trait_cvterm_id IN ($placeholders) EOF; $stm_get_trait= $db->prepare($query_get_trait); $stm_get_trait->execute(array($type_cvterm_id)); $result = array(); while ($row = $stm_get_trait->fetch(PDO::FETCH_ASSOC)) { $result = $row; } return $result; } } ?>
<?php namespace ajax\details; use \PDO as PDO; /** * Web Service. * Returns Trait informatio */ class Traits extends \WebService { /** * @param $querydata[] * @returns array of traits */ public function execute($querydata) { global $db; $trait_cvterm_id = $querydata['trait_cvterm_id']; $placeholders = implode(',', array_fill(0, count($trait_cvterm_id), '?')); $query_get_trait = <<<EOF SELECT * FROM trait_cvterm WHERE trait_cvterm_id IN ($placeholders) EOF; $stm_get_trait= $db->prepare($query_get_trait); $stm_get_trait->execute(array($trait_cvterm_id)); $result = array(); while ($row = $stm_get_trait->fetch(PDO::FETCH_ASSOC)) { $result = $row; } return $result; } } ?>
Change how we get election ID
<?php require_once('config.php'); global $config; require_once('page_template_dash_head.php'); require_once('page_template_dash_sidebar.php'); $stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?"); $stmt->bindParam(1, $_GET['id']); $stmt->execute(); $election_name = $stmt->fetch(PDO::FETCH_NUM)[0]; ?> <div class="content-wrapper"> <section class="content-header"> <h1> Edit Election <small><?php echo $election_name; ?></small> </h1> <ol class="breadcrumb"> <li><i class="fa fa-th-list"></i> Elections</li> <li class="active"><?php echo $election_name; ?></li> </ol> </section> <section class="content"> <!-- Your Page Content Here --> </section> </div> <?php require_once('page_template_dash_foot.php'); ?>
<?php require_once('config.php'); global $config; require_once('page_template_dash_head.php'); require_once('page_template_dash_sidebar.php'); $stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?"); $stmt->bindParam(1, $row["election"]); $stmt->execute(); $election_name = $stmt->fetch(PDO::FETCH_NUM)[0]; ?> <div class="content-wrapper"> <section class="content-header"> <h1> Edit Election <small><?php echo $election_name; ?></small> </h1> <ol class="breadcrumb"> <li><i class="fa fa-th-list"></i> Elections</li> <li class="active"><?php echo $election_name; ?></li> </ol> </section> <section class="content"> <!-- Your Page Content Here --> </section> </div> <?php require_once('page_template_dash_foot.php'); ?>
Use Mongo's $or in Feature.search()
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: String, examples: [{ technology: String, snippets: [String] }] }); featureSchema.statics.search = function (query, callback) { this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(function (err, docs) { callback(docs); }); }; module.exports = mongoose.model('Feature', featureSchema);
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: String, examples: [{ technology: String, snippets: [String] }] }); featureSchema.statics.search = function (query, callback) { this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { technology: new RegExp(query, 'i') }}}, { examples: { $elemMatch: { snippets: new RegExp(query, 'i') }}} ]}) .lean() .select('-__v -_id -examples._id') .exec(function (err, docs) { callback(docs); }); }; module.exports = mongoose.model('Feature', featureSchema);
Fix the skip to match plugins
# Copyright 2017 Andrea Frittoli # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import config from tempest import test CONF = config.CONF class HeatDriverNeutronDNSIntegration(test.BaseTestCase): @classmethod def skip_checks(cls): super(HeatDriverNeutronDNSIntegration, cls).skip_checks() if not getattr(CONF.service_available, 'designate', False): raise cls.skipException('Designate support is required') if not getattr(CONF.service_available, 'heat_plugin', False): raise cls.skipException('Heat support is required') def test_port_on_extenal_net_to_dns(self): pass def test_floating_ip_with_name_from_port_to_dns(self): pass def test_floating_ip_with_own_name_to_dns(self): pass
# Copyright 2017 Andrea Frittoli # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import config from tempest import test CONF = config.CONF class HeatDriverNeutronDNSIntegration(test.BaseTestCase): @classmethod def skip_checks(cls): super(HeatDriverNeutronDNSIntegration, cls).skip_checks() if not getattr(CONF.service_available, 'dns', False): raise cls.skipException('Designate support is required') if not getattr(CONF.service_available, 'orchestration', False): raise cls.skipException('Heat support is required') def test_port_on_extenal_net_to_dns(self): pass def test_floating_ip_with_name_from_port_to_dns(self): pass def test_floating_ip_with_own_name_to_dns(self): pass
Fix due to Flask-Login version up
#!/usr/bin/env python # -*- encoding: utf-8 -*- from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and user.is_authenticated } app.context_processor(backends)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and not user.is_anonymous() } app.context_processor(backends)
Update join(String, String...) and add method to append a String to a String[]
package net.hexid; import java.util.List; import java.io.File; public class Utils { /** * Combine strings with a common string * @param glue * @param str * @return A single string */ public static String join(String glue, String... str) { if(str.length > 0) { StringBuilder sb = new StringBuilder(str[0]); for(int i = 1; i < str.length; i++) sb.append(glue).append(str[i]); return sb.toString(); } else return ""; } /** * Combine a list of strings with a common string * @param glue * @param str * @return {@link #join(String,String...)} */ public static String join(String glue, List<String> str) { return join(glue, str.toArray(new String[0])); } public static String joinFile(String... str) { return join(File.separator, str); } /** * Get the directory that the application is being run from * @return directory */ public static File getPWD() { return new File(Utils.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile(); } public static String[] appendStrToArray(String[] arr, String str) { String[] array = new String[arr.length+1]; for(int i = 0; i < arr.length-1; i++) { array[i] = arr[i]; } array[arr.length] = str; return array; } }
package net.hexid; import java.util.List; import java.io.File; public class Utils { /** * Combine strings with a common string * @param glue * @param str * @return A single string */ public static String join(String glue, String... str) { StringBuilder sb = new StringBuilder(); int i; for(i = 0; i < str.length-1; i++) sb.append(str[i] + glue); return sb.toString() + str[i]; } /** * Combine a list of strings with a common string * @param glue * @param str * @return {@link #join(String,String...)} */ public static String join(String glue, List<String> str) { return join(glue, str.toArray(new String[0])); } public static String joinFile(String... str) { return join(File.separator, str); } /** * Get the directory that the application is being run from * @return directory */ public static File getPWD() { return new File(Utils.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile(); } }
tests/helper: Make regex helper accept more types
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern
Fix import order picked up by isort
from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
Add Github link for contributing
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Model */ namespace PH7; class GeoIpCoreModel extends Framework\Mvc\Model\Engine\Model { /* * In development. Feel free to help me! <https://github.com/pH7Software/pH7-Social-Dating-CMS> */ public function getCountry($sWhere) { return $this->orm->select('GeoCountry', 'countryId, countryTitle')->find('countryId', $sWhere)->orderBy('countryTitle')->execute(); } public function getState($sWhere) { return $this->orm->select('GeoState', 'stateId, stateTitle')->find('stateId', $sWhere)->orderBy('stateTitle')->execute(); } public function getCity($sWhere) { return $this->orm->select('GeoCity', 'cityId, cityTitle')->find('cityId', $sWhere)->orderBy('cityTitle')->execute(); } }
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Model */ namespace PH7; class GeoIpCoreModel extends Framework\Mvc\Model\Engine\Model { /* * In developing */ public function getCountry($sWhere) { return $this->orm->select('GeoCountry', 'countryId, countryTitle')->find('countryId', $sWhere)->orderBy('countryTitle')->execute(); } public function getState($sWhere) { return $this->orm->select('GeoState', 'stateId, stateTitle')->find('stateId', $sWhere)->orderBy('stateTitle')->execute(); } public function getCity($sWhere) { return $this->orm->select('GeoCity', 'cityId, cityTitle')->find('cityId', $sWhere)->orderBy('cityTitle')->execute(); } }
Add test for pop and adjust element init test
import pytest from stack import Element from stack import Stack def test_element_init(): n = Element() assert n.val is None assert n.previous is None m = Element(3) assert m.val == 3 assert m.previous is None def test_stack_init(): l = Stack() assert l.top is None def test_stack_push(): l = Stack() e = Element(10) l.push(e) assert l.top == e assert l.top.previous is None f = Element("String") l.push(f) assert l.top == f assert l.top.previous == e assert l.top.previous.previous is None def test_stack_pop(): l = Stack() e = Element(10) l.push(e) f = Element("String") l.push(f) assert l.pop() == f.val assert l.top == e assert l.top.previous is None assert l.pop() == e.val assert l.top is None with pytest.raises(ValueError): l.pop()
import pytest from stack import Element from stack import Stack def test_element_init(): n = Element() assert n.val is None assert n.next is None n = Element(3) assert n.val == 3 assert n.next is None def test_stack_init(): l = Stack() assert l.top is None def test_stack_push(): l = Stack() e = Element(10) l.push(e) assert l.top == e assert l.top.previous is None f = Element("String") l.push(f) assert l.top == f assert l.top.previous == e assert l.top.previous.previous is None # def test_stack_pop(): # l = stack() # a = l.pop() # assert a is None
refactor(Files): Update view for change in viewset
from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse from django.shortcuts import render from projects.api.views.files import ProjectsFilesViewSet @login_required def list(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Get a list of project files. The trailing part of the URL becomes the `prefix` query parameter, consistent with API ending e.g. /<account>/<project>/files/sub?search=foo is equivalent to: /api/projects/<project>/files?prefix=sub&search=foo """ request.GET = request.GET.copy() request.GET["prefix"] = kwargs.get("prefix") viewset = ProjectsFilesViewSet.init("list", request, args, kwargs) project = viewset.get_project() files = viewset.get_queryset(project) context = viewset.get_response_context(queryset=files) return render( request, "projects/files/list.html", dict(project=project, **context), )
from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse from django.shortcuts import render from projects.api.views.files import ProjectsFilesViewSet @login_required def list(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Get a list of project files. The trailing part of the URL becomes the `prefix` query parameter, consistent with API ending e.g. /<account>/<project>/files/sub?search=foo is equivalent to: /api/projects/<project>/files?prefix=sub&search=foo """ prefix = kwargs.get("prefix") if prefix and not prefix.endswith("/"): prefix += "/" request.GET = request.GET.copy() request.GET["prefix"] = prefix request.GET["aggregate"] = True viewset = ProjectsFilesViewSet.init("list", request, args, kwargs) project = viewset.get_project() files = viewset.get_queryset(project) # List of tuples for directory breadcrumbs dirs = [("root", "")] path = "" for name in prefix.split("/"): if name: path += name + "/" dirs.append((name, path)) return render( request, "projects/files/list.html", dict(prefix=prefix, dirs=dirs, files=files, project=project,), )
Make the theme compatible with the new version of RN tagcloud. git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@2286 653ae4dd-d31e-0410-96ef-6bf7bf53c507
</div> <div id="bottom-secondary"> <div id="tags"><?php if (Plugins::is_loaded('tagcloud')) $theme->tag_cloud(); else $theme->show_tags();?></div> </div> <div id="footer"> <p> <?php printf( _t('%1$s is powered by %2$s'), Options::get('title'),' <a href="http://www.habariproject.org/" title="Habari">Habari ' . Version::HABARI_VERSION . '</a>' ); ?> - <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e( 'Atom Entries' ); ?></a><?php _e( ' and ' ); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e( 'Atom Comments' ); ?></a> </p> </div> <div class="clear"></div> </div> </div> <?php $theme->footer(); ?> </body> </html>
</div> <div id="bottom-secondary"> <div id="tags"><?php if (Plugins::is_loaded('tagcloud')) echo $tag_cloud; else $theme->show_tags();?></div> </div> <div id="footer"> <p> <?php printf( _t('%1$s is powered by %2$s'), Options::get('title'),' <a href="http://www.habariproject.org/" title="Habari">Habari ' . Version::HABARI_VERSION . '</a>' ); ?> - <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e( 'Atom Entries' ); ?></a><?php _e( ' and ' ); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e( 'Atom Comments' ); ?></a> </p> </div> <div class="clear"></div> </div> </div> <?php $theme->footer(); ?> </body> </html>
Allow to add contact to logged in users.
from ajax_select import LookupChannel from django.core.exceptions import PermissionDenied from django.utils.html import escape from django.db.models import Q from .models import Person class PersonLookup(LookupChannel): model = Person def get_query(self, q, request): return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q)) # .order_by('name') def get_result(self, obj): u""" result is the simple text that is the completion of what the person typed """ return obj.mixed_name def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return self.format_item_display(obj) def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return u"%s<div></div>" % (escape(obj.mixed_name)) def check_auth(self, request): """Return results only to logged users.""" if not request.user.is_authenticated(): raise PermissionDenied
from ajax_select import LookupChannel from django.utils.html import escape from django.db.models import Q from .models import Person class PersonLookup(LookupChannel): model = Person def get_query(self, q, request): return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q)) # .order_by('name') def get_result(self, obj): u""" result is the simple text that is the completion of what the person typed """ return obj.mixed_name def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return self.format_item_display(obj) def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return u"%s<div></div>" % (escape(obj.mixed_name))
Fix type in client error codes
'use strict'; const http = require('http'); let request = {}; request.get = function(url) { return new Promise((resolve, reject) => { let req = http.get(url, (res) => { if ([400, 401, 403, 404].includes(res.statusCode)) { reject(new Error(`GET request to ${url} failed, status: ${res.statusCode}`)); } let body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => resolve(body.join(''))); }); req.on('error', (err) => reject(err)); }); }; request.post = function(options, data) { return new Promise((resolve, reject) => { let req = http.request(options, (res) => { res.setEncoding('utf8'); console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); let body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => resolve(body.join(''))); }); req.on('error', (err) => reject(err)); req.write(data); req.end(); }); }; module.exports = request;
'use strict'; const http = require('http'); let request = {}; request.get = function(url) { return new Promise((resolve, reject) => { let req = http.get(url, (res) => { if ([400, 401, 03, 404].includes(res.statusCode)) { reject(new Error(`GET request to ${url} failed, status: ${res.statusCode}`)); } let body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => resolve(body.join(''))); }); req.on('error', (err) => reject(err)); }); }; request.post = function(options, data) { return new Promise((resolve, reject) => { let req = http.request(options, (res) => { res.setEncoding('utf8'); console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); let body = []; res.on('data', (chunk) => body.push(chunk)); res.on('end', () => resolve(body.join(''))); }); req.on('error', (err) => reject(err)); req.write(data); req.end(); }); }; module.exports = request;
Fix the home sending worker being too generic on how it sends people home
package com.graywolf336.trailingperspective.workers; import org.bukkit.ChatColor; import com.graywolf336.trailingperspective.TrailingPerspectiveMain; import com.graywolf336.trailingperspective.enums.Settings; import com.graywolf336.trailingperspective.interfaces.ITrailer; import com.graywolf336.trailingperspective.interfaces.ITrailerWorker; public class HomeSendingWorker implements ITrailerWorker { private TrailingPerspectiveMain pl; public HomeSendingWorker(TrailingPerspectiveMain plugin) { this.pl = plugin; this.pl.getLogger().info("HomeSendingWorker started."); } public void run() { if(Settings.HOME_LOCATION.asLocation() == null) return; for(ITrailer trailer : this.pl.getTrailerManager().getTrailers()) { if(trailer.isOnline() && !trailer.isCurrentlyTrailingSomeone() && !trailer.wasSentHome() && this.pl.getServer().getOnlinePlayers().size() <= this.pl.getTrailerManager().getTrailers().size()) { trailer.getPlayer().teleport(Settings.HOME_LOCATION.asLocation()); trailer.setWhetherTheyHaveBeenSentHome(true); trailer.getPlayer().sendMessage(ChatColor.AQUA + "You've been sent home as there is no one to trail currently."); } } } }
package com.graywolf336.trailingperspective.workers; import org.bukkit.ChatColor; import com.graywolf336.trailingperspective.TrailingPerspectiveMain; import com.graywolf336.trailingperspective.enums.Settings; import com.graywolf336.trailingperspective.interfaces.ITrailer; import com.graywolf336.trailingperspective.interfaces.ITrailerWorker; public class HomeSendingWorker implements ITrailerWorker { private TrailingPerspectiveMain pl; public HomeSendingWorker(TrailingPerspectiveMain plugin) { this.pl = plugin; this.pl.getLogger().info("HomeSendingWorker started."); } public void run() { if(Settings.HOME_LOCATION.asLocation() == null) return; for(ITrailer trailer : this.pl.getTrailerManager().getTrailers()) { if(trailer.isOnline() && !trailer.isCurrentlyTrailingSomeone() && !trailer.wasSentHome()) { trailer.getPlayer().teleport(Settings.HOME_LOCATION.asLocation()); trailer.setWhetherTheyHaveBeenSentHome(true); trailer.getPlayer().sendMessage(ChatColor.AQUA + "You've been sent home as there is no one to trail currently."); } } } }
Fix URLs in KB service calls
package jp.ac.nii.prl.mape.controller.service; import java.net.URI; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import jp.ac.nii.prl.mape.controller.model.MAPEKComponent; @Service("knowledgeBaseService") public class KnowledgeBaseServiceImpl implements KnowledgeBaseService { /* (non-Javadoc) * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#put(java.lang.String, java.lang.String) */ @Override public void put(MAPEKComponent kb, String bx, String view) { RestTemplate template = new RestTemplate(); URI location = template.postForLocation(kb.getUrl() + "/get/" + bx, view); view = template.getForObject(location, String.class); } /* (non-Javadoc) * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#get(java.lang.String) */ @Override public String get(MAPEKComponent kb, String bx) { RestTemplate template = new RestTemplate(); System.out.println(kb.getUrl() + "/get/" + bx); String view = template.getForObject(kb.getUrl() + "/get/" + bx, String.class); return view; } }
package jp.ac.nii.prl.mape.controller.service; import java.net.URI; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import jp.ac.nii.prl.mape.controller.model.MAPEKComponent; @Service("knowledgeBaseService") public class KnowledgeBaseServiceImpl implements KnowledgeBaseService { /* (non-Javadoc) * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#put(java.lang.String, java.lang.String) */ @Override public void put(MAPEKComponent kb, String bx, String view) { RestTemplate template = new RestTemplate(); URI location = template.postForLocation(kb.getBaseUrl() + "/bx", view); view = template.getForObject(location, String.class); } /* (non-Javadoc) * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#get(java.lang.String) */ @Override public String get(MAPEKComponent kb, String bx) { RestTemplate template = new RestTemplate(); String view = template.getForObject(kb.getBaseUrl() + "/bx", String.class); return view; } }
Remove unnecessary API call on location set.
import {takeLatest} from 'redux-saga'; import {call, fork, put} from 'redux-saga/effects'; import {arrayOf} from 'normalizr'; import {receiveAddress} from './actions'; import {mapActions} from './constants'; import {receiveUnits, setFetchError} from '../unit/actions'; import {getFetchUnitsRequest} from '../unit/helpers'; import {unitSchema} from '../unit/constants'; import {createUrl, createRequest, callApi, normalizeEntityResults} from '../api/helpers'; function* onSetLocation({payload: position}: FetchAction) { const addressParams = { lat: position[0], lon: position[1], page_size: 1 }; const addressRequest = createRequest(createUrl('address/', addressParams)); const {bodyAsJson: addressJson} = yield call(callApi, addressRequest); const addressData = addressJson.results ? addressJson.results[0] : null; yield put(receiveAddress(addressData)); } function* watchSetLocation() { yield takeLatest(mapActions.SET_LOCATION, onSetLocation); } export default function* saga() { return [ yield fork(watchSetLocation) ]; }
import {takeLatest} from 'redux-saga'; import {call, fork, put} from 'redux-saga/effects'; import {arrayOf} from 'normalizr'; import {receiveAddress} from './actions'; import {mapActions} from './constants'; import {receiveUnits, setFetchError} from '../unit/actions'; import {getFetchUnitsRequest} from '../unit/helpers'; import {unitSchema} from '../unit/constants'; import {createUrl, createRequest, callApi, normalizeEntityResults} from '../api/helpers'; function* onSetLocation({payload: position}: FetchAction) { const addressParams = { lat: position[0], lon: position[1], page_size: 1 }; const addressRequest = createRequest(createUrl('address/', addressParams)); const {bodyAsJson: addressJson} = yield call(callApi, addressRequest); const addressData = addressJson.results ? addressJson.results[0] : null; yield put(receiveAddress(addressData)); const unitParams = { }; const unitRequest = getFetchUnitsRequest(unitParams); const {response, bodyAsJson: unitJson} = yield call(callApi, unitRequest); if(response.status === 200) { const data = normalizeEntityResults(unitJson.results, arrayOf(unitSchema)); yield put(receiveUnits(data)); } else { yield put(setFetchError(unitJson.results)); } } function* watchSetLocation() { yield takeLatest(mapActions.SET_LOCATION, onSetLocation); } export default function* saga() { return [ yield fork(watchSetLocation) ]; }
Check on the EOL chars in ,cover gold files.
# Check files for incorrect newlines import fnmatch, os def check_file(fname): for n, line in enumerate(open(fname, "rb")): if "\r" in line: print "%s@%d: CR found" % (fname, n) return def check_files(root, patterns): for root, dirs, files in os.walk(root): for f in files: fname = os.path.join(root, f) for p in patterns: if fnmatch.fnmatch(fname, p): check_file(fname) break if '.svn' in dirs: dirs.remove('.svn') check_files("coverage", ["*.py"]) check_files("test", ["*.py", "*,cover"]) check_file("setup.py")
# Check files for incorrect newlines import fnmatch, os def check_file(fname): for n, line in enumerate(open(fname, "rb")): if "\r" in line: print "%s@%d: CR found" % (fname, n) return def check_files(root, patterns): for root, dirs, files in os.walk(root): for f in files: fname = os.path.join(root, f) for p in patterns: if fnmatch.fnmatch(fname, p): check_file(fname) break if '.svn' in dirs: dirs.remove('.svn') check_files("coverage", ["*.py"]) check_files("test", ["*.py"]) check_file("setup.py")
Fix to suit latest Yahoo changes
# pipeitembuilder.py # import urllib from pipe2py import util def pipe_itembuilder(context, _INPUT, conf, **kwargs): """This source builds an item. Keyword arguments: context -- pipeline context _INPUT -- source generator conf: attrs -- key, value pairs Yields (_OUTPUT): item """ attrs = conf['attrs'] if not isinstance(attrs, list): attrs = [attrs] for item in _INPUT: d = {} for attr in attrs: try: key = util.get_value(attr['key'], item, **kwargs) value = util.get_value(attr['value'], item, **kwargs) except KeyError: continue #ignore if the item is referenced but doesn't have our source or target field (todo: issue a warning if debugging?) util.set_value(d, key, value) yield d if item == True: #i.e. this is being fed forever, i.e. not in a loop, so we just yield our item once break
# pipeitembuilder.py # import urllib from pipe2py import util def pipe_itembuilder(context, _INPUT, conf, **kwargs): """This source builds an item. Keyword arguments: context -- pipeline context _INPUT -- source generator conf: attrs -- key, value pairs Yields (_OUTPUT): item """ attrs = conf['attrs'] for item in _INPUT: d = {} for attr in attrs: try: key = util.get_value(attr['key'], item, **kwargs) value = util.get_value(attr['value'], item, **kwargs) except KeyError: continue #ignore if the item is referenced but doesn't have our source or target field (todo: issue a warning if debugging?) util.set_value(d, key, value) yield d if item == True: #i.e. this is being fed forever, i.e. not in a loop, so we just yield our item once break
Allow removal of track data git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@205 cb33b658-6c9e-41a7-9690-cba343611204
/** * */ package org.mwc.cmap.core.DataTypes.TrackData; import Debrief.Tools.Tote.WatchableList; /** * @author ian.mayo * */ public interface TrackDataProvider { public static interface TrackDataListener { /** find out that the primary has changed * * @param primary the primary track */ public void primaryUpdated(WatchableList primary); /** find out that the secondaries have changed * * @param secondaries list of secondary tracks */ public void secondariesUpdated(WatchableList[] secondaries); } /** declare that we want to be informed about changes * in selected tracks */ public void addTrackDataListener(TrackDataListener listener); /** forget that somebody wants to know about track changes * */ public void removeTrackDataListener(TrackDataListener listener); /** find out what the primary track is * */ public WatchableList getPrimaryTrack(); /** find out what the secondary track is * */ public WatchableList[] getSecondaryTracks(); }
/** * */ package org.mwc.cmap.core.DataTypes.TrackData; import Debrief.Tools.Tote.WatchableList; /** * @author ian.mayo * */ public interface TrackDataProvider { public static interface TrackDataListener { /** find out that the primary has changed * * @param primary the primary track */ public void primaryUpdated(WatchableList primary); /** find out that the secondaries have changed * * @param secondaries list of secondary tracks */ public void secondariesUpdated(WatchableList[] secondaries); } /** declare that we want to be informed about changes * in selected tracks */ public void addTrackDataListener(TrackDataListener listener); /** find out what the primary track is * */ public WatchableList getPrimaryTrack(); /** find out what the secondary track is * */ public WatchableList[] getSecondaryTracks(); }
BB-1334: Add STI for audit - fix migrations
<?php namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_6; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Types\Type; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class SetNotNullable implements Migration, OrderedMigrationInterface { /** {@inheritdoc} */ public function getOrder() { return 30; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { $auditTable = $schema->getTable('oro_audit'); $auditTable->getColumn('type') ->setType(Type::getType(Type::STRING)) ->setOptions(['length' => 255, 'notnull' => true]); $auditTable->addIndex(['type'], 'idx_oro_audit_type'); $auditFieldTable = $schema->getTable('oro_audit_field'); $auditFieldTable->getColumn('type') ->setType(Type::getType(Type::STRING)) ->setOptions(['length' => 255, 'notnull' => true]); $auditFieldTable->addIndex(['type'], 'idx_oro_audit_field_type'); } }
<?php namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_6; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Types\Type; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class SetNotNullable implements Migration, OrderedMigrationInterface { /** {@inheritdoc} */ public function getOrder() { return 30; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { $auditTable = $schema->getTable('oro_audit'); $auditTable->getColumn('type')->setType(Type::getType(Type::STRING))->setOptions(['length' => 255]); $auditTable->addIndex(['type'], 'idx_oro_audit_type'); $auditFieldTable = $schema->getTable('oro_audit_field'); $auditFieldTable->getColumn('type')->setType(Type::getType(Type::STRING))->setOptions(['length' => 255]); $auditFieldTable->addIndex(['type'], 'idx_oro_audit_field_type'); } }
Test should not break when no internet connection
package eu.europa.ec.markt.dss.validation102853.tsl; import java.net.UnknownHostException; import org.junit.Assert; import org.junit.Test; import eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader; public class TrustedListCertificateSourceTest { @Test public void test1() throws Exception { try { TrustedListsCertificateSource source = new TrustedListsCertificateSource(); source.setDataLoader(new CommonsDataLoader()); source.setLotlCertificate("classpath://ec.europa.eu.crt"); source.setLotlUrl("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml"); source.setTslRefreshPolicy(TSLRefreshPolicy.NEVER); source.setCheckSignature(false); source.init(); Assert.assertTrue(source.getCertificates().size() > 0); } catch (Exception e) { if(!(e.getCause() instanceof UnknownHostException)) { throw e; } // Internet failure is not test failure } } }
package eu.europa.ec.markt.dss.validation102853.tsl; import org.junit.Assert; import org.junit.Test; import eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader; public class TrustedListCertificateSourceTest { @Test public void test1() throws Exception { TrustedListsCertificateSource source = new TrustedListsCertificateSource(); source.setDataLoader(new CommonsDataLoader()); source.setLotlCertificate("classpath://ec.europa.eu.crt"); source.setLotlUrl("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml"); source.setTslRefreshPolicy(TSLRefreshPolicy.NEVER); source.setCheckSignature(false); source.init(); Assert.assertTrue(source.getCertificates().size() > 0); } }
Make this slightly less as simple as possible
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\Metadata; use PHPUnit\Util\Metadata\Annotation\Registry as AnnotationRegistry; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class AnnotationParser implements Parser { /** * @psalm-param class-string $className */ public function forClass(string $className): MetadataCollection { $result = []; foreach (AnnotationRegistry::getInstance()->forClassName($className)->symbolAnnotations() as $annotation) { } return MetadataCollection::fromArray($result); } /** * @psalm-param class-string $className */ public function forMethod(string $className, string $methodName): MetadataCollection { $result = []; foreach (AnnotationRegistry::getInstance()->forMethod($className, $methodName)->symbolAnnotations() as $annotation) { } return MetadataCollection::fromArray($result); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\Metadata; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class AnnotationParser implements Parser { /** * @psalm-param class-string $className */ public function forClass(string $className): MetadataCollection { $result = []; return MetadataCollection::fromArray($result); } /** * @psalm-param class-string $className */ public function forMethod(string $className, string $methodName): MetadataCollection { $result = []; return MetadataCollection::fromArray($result); } }
Revert "Set audio quality default value" This reverts commit e4adca4840dc444259d50c1395f6fe5e3c0dbacb.
import {merge, pick} from 'lodash' const kStorageKey = 'wukong' export function open(state = {}) { try { return merge({ user: { preferences: { listenOnly: false, connection: 0, audioQuality: 0, theme: 0 } } }, JSON.parse(localStorage.getItem(kStorageKey)), state) } catch (error) { return state } } export function save(state = {}) { try { localStorage.setItem(kStorageKey, JSON.stringify(pick(state, [ 'user.preferences', 'song.playlist', 'player.volume' ]))) } catch (error) { localStorage.removeItem(kStorageKey) } }
import {merge, pick} from 'lodash' const kStorageKey = 'wukong' export function open(state = {}) { try { return merge({ user: { preferences: { listenOnly: false, connection: 0, audioQuality: 2, theme: 0 } } }, JSON.parse(localStorage.getItem(kStorageKey)), state) } catch (error) { return state } } export function save(state = {}) { try { localStorage.setItem(kStorageKey, JSON.stringify(pick(state, [ 'user.preferences', 'song.playlist', 'player.volume' ]))) } catch (error) { localStorage.removeItem(kStorageKey) } }
Add dependency on keypress event
/* --- script: Shortcuts.js description: Add command key listeners to the widget license: Public domain (http://unlicense.org). authors: Yaroslaff Fedin requires: - Ext/Shortcuts - Ext/Element.Events.keypress - LSD.Module - LSD.Module.Events provides: - LSD.Module.Shortcuts ... */ LSD.Module.Shortcuts = new Class({ Implements: Shortcuts, addShortcut: function() { LSD.Module.Events.setEventsByRegister.call(this, 'shortcuts', LSD.Module.Shortcuts.events); return Shortcuts.prototype.addShortcut.apply(this, arguments); }, removeShortcut: function() { LSD.Module.Events.setEventsByRegister.call(this, 'shortcuts', LSD.Module.Shortcuts.events); return Shortcuts.prototype.removeShortcut.apply(this, arguments); } }); LSD.Module.Events.addEvents.call(LSD.Module.Shortcuts.prototype, { focus: 'enableShortcuts', blur: 'disableShortcuts' }); LSD.Options.shortcuts = { add: 'addShortcut', remove: 'removeShortcut', process: 'bind', iterate: true };
/* --- script: Shortcuts.js description: Add command key listeners to the widget license: Public domain (http://unlicense.org). authors: Yaroslaff Fedin requires: - Ext/Shortcuts - LSD.Module - LSD.Module.Events provides: - LSD.Module.Shortcuts ... */ LSD.Module.Shortcuts = new Class({ Implements: Shortcuts, addShortcut: function() { LSD.Module.Events.setEventsByRegister.call(this, 'shortcuts', LSD.Module.Shortcuts.events); return Shortcuts.prototype.addShortcut.apply(this, arguments); }, removeShortcut: function() { LSD.Module.Events.setEventsByRegister.call(this, 'shortcuts', LSD.Module.Shortcuts.events); return Shortcuts.prototype.removeShortcut.apply(this, arguments); } }); LSD.Module.Events.addEvents.call(LSD.Module.Shortcuts.prototype, { focus: 'enableShortcuts', blur: 'disableShortcuts' }); LSD.Options.shortcuts = { add: 'addShortcut', remove: 'removeShortcut', process: 'bind', iterate: true };
Use gulp-util.log instead of console.warn
var es = require('event-stream'); var gutil = require('gulp-util'); var path = require('path'); var ect = require('ect'); module.exports = function (opt) { opt = opt || {}; if (!opt.ext) opt.ext = '.ect'; if (!opt.outExt) opt.outExt = '.html'; return es.map(function (file, callback) { try { var filePath = file.base; var fileName = gutil.replaceExtension(path.basename(file.path), ""); var html = ect({ root: filePath, ext: opt.ext }); html.render(fileName, function (error, html) { file.contents = new Buffer(html); file.path = gutil.replaceExtension(file.path, opt.outExt); }); } catch (e) { gutil.log(gutil.colors.red('Error gulp-ect: ' + e.message)); } callback(null, file); }); };
var es = require('event-stream'); var gutil = require('gulp-util'); var path = require('path'); var ect = require('ect'); module.exports = function (opt) { opt = opt || {}; if (!opt.ext) opt.ext = '.ect'; if (!opt.outExt) opt.outExt = '.html'; return es.map(function (file, callback) { try { var filePath = file.base; var fileName = gutil.replaceExtension(path.basename(file.path), ""); var html = ect({ root: filePath, ext: opt.ext }); html.render(fileName, function (error, html) { file.contents = new Buffer(html); file.path = gutil.replaceExtension(file.path, opt.outExt); }); } catch (e) { console.warn('Error gulp-ect: ' + e.message); } callback(null, file); }); };
Tidy up server side error/confirmation messages
const models = require('../models/index') const insecurity = require('../lib/insecurity') module.exports.upgradeToDeluxe = function upgradeToDeluxe () { return async (req, res, next) => { if (req.body.payUsingWallet) { await models.Wallet.decrement({ balance: 49 }, { where: { UserId: req.body.UserId } }) } const user = await models.User.update({ role: insecurity.roles.deluxe }, { where: { id: req.body.UserId, role: insecurity.roles.customer } }) if (user[0] !== 0) { res.status(200).json({ status: 'success', data: { confirmation: 'Congratulations! You are now a deluxe member!' } }) } else { res.status(400).json({ status: 'error', error: 'Something went wrong. Please try again!' }) } } } module.exports.deluxeMembershipStatus = function deluxeMembershipStatus () { return (req, res, next) => { if (insecurity.isCustomer(req)) { res.status(200).json({ status: 'success', data: { membershipCost: 49 } }) } else if (insecurity.isDeluxe(req)) { res.status(400).json({ status: 'error', error: 'You are already a deluxe member!' }) } else { res.status(400).json({ status: 'error', error: 'You are not eligible for deluxe membership!' }) } } }
const models = require('../models/index') const insecurity = require('../lib/insecurity') module.exports.upgradeToDeluxe = function upgradeToDeluxe () { return async (req, res, next) => { if (req.body.payUsingWallet) { await models.Wallet.decrement({ balance: 49 }, { where: { UserId: req.body.UserId } }) } const user = await models.User.update({ role: insecurity.roles.deluxe }, { where: { id: req.body.UserId, role: insecurity.roles.customer } }) if (user[0] !== 0) { res.status(200).json({ status: 'success', data: { confirmation: 'Congratulations, you are now a deluxe customer.' } }) } else { res.status(400).json({ status: 'error', error: 'Please try again.' }) } } } module.exports.deluxeMembershipStatus = function deluxeMembershipStatus () { return (req, res, next) => { if (insecurity.isCustomer(req)) { res.status(200).json({ status: 'success', data: { membershipCost: 49 } }) } else if (insecurity.isDeluxe(req)) { res.status(400).json({ status: 'error', error: 'Congratulations! You are a deluxe member.' }) } else { res.status(400).json({ status: 'error', error: 'You are not eligible for deluxe membership.' }) } } }
Fix bug with removing saved job from bookmarks
import React from 'react'; import { withScrollToTop } from '../hocs/withScrollToTop'; import FeaturedItems from '../FeaturedItems'; import { Header, Status } from './styled'; const Bookmarks = props => { const { savedJobs = [], data, loggedIn } = props; const jobs = savedJobs.reduce((acc, id) => { const job = data.find(job => job._id === id); if (job) acc.push(job); return acc; }, []); const status = !jobs.length ? `You haven't saved any jobs yet` : `You have ${jobs.length} saved job${jobs.length === 1 ? '' : 's'}`; if (!loggedIn || !data) { return null; } return ( <div> <Header>My saved jobs</Header> <Status>{status}</Status> <FeaturedItems {...props} data={jobs} />; </div> ); }; export default withScrollToTop(Bookmarks);
import React from 'react'; import { withScrollToTop } from '../hocs/withScrollToTop'; import FeaturedItems from '../FeaturedItems'; import { Header, Status } from './styled'; const Bookmarks = ({ savedJobs = [], data, loggedIn, ...props }) => { const jobs = savedJobs.reduce((acc, id) => { const job = data.find(job => job._id === id); if (job) acc.push(job); return acc; }, []); const status = !jobs.length ? `You haven't saved any jobs yet` : `You have ${jobs.length} saved job${jobs.length === 1 ? '' : 's'}`; if (!loggedIn || !data) { return null; } return ( <div> <Header>My saved jobs</Header> <Status>{status}</Status> <FeaturedItems {...props} data={jobs} savedJobs={savedJobs} />; </div> ); }; export default withScrollToTop(Bookmarks);
Set return type to Integer
package com.faforever.api.data.domain; import com.yahoo.elide.annotation.Include; import lombok.Setter; import org.hibernate.annotations.Immutable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Setter @Table(name = "map_statistics") @Include(type = MapStatistics.TYPE_NAME) @Immutable public class MapStatistics { public static final String TYPE_NAME = "mapStatistics"; private Integer id; private Integer downloads; private Integer plays; private Integer draws; private Map map; @Id @Column(name = "map_id") public Integer getId() { return id; } @Column(name = "downloads") public Integer getDownloads() { return downloads; } @Column(name = "plays") public Integer getPlays() { return plays; } @Column(name = "draws") public Integer getDraws() { return draws; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "map_id", insertable = false, updatable = false) public Map getMap() { return map; } }
package com.faforever.api.data.domain; import com.yahoo.elide.annotation.Include; import lombok.Setter; import org.hibernate.annotations.Immutable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Setter @Table(name = "map_statistics") @Include(type = MapStatistics.TYPE_NAME) @Immutable public class MapStatistics { public static final String TYPE_NAME = "mapStatistics"; private Integer id; private Integer downloads; private Integer plays; private Integer draws; private Map map; @Id @Column(name = "map_id") public int getId() { return id; } @Column(name = "downloads") public int getDownloads() { return downloads; } @Column(name = "plays") public int getPlays() { return plays; } @Column(name = "draws") public int getDraws() { return draws; } @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "map_id", insertable = false, updatable = false) public Map getMap() { return map; } }
Fix warning about transitionTo being deprecated
import EditorControllerMixin from 'ghost/mixins/editor-base-controller'; var EditorNewController = Ember.ObjectController.extend(EditorControllerMixin, { actions: { /** * Redirect to editor after the first save */ save: function () { var self = this; this._super().then(function (model) { if (model.get('id')) { self.transitionToRoute('editor.edit', model); } return model; }); } } }); export default EditorNewController;
import EditorControllerMixin from 'ghost/mixins/editor-base-controller'; var EditorNewController = Ember.ObjectController.extend(EditorControllerMixin, { actions: { /** * Redirect to editor after the first save */ save: function () { var self = this; this._super().then(function (model) { if (model.get('id')) { self.transitionTo('editor.edit', model); } return model; }); } } }); export default EditorNewController;
Update the userdata migration for address and phone The user address and phone number do not need to be unique. This fixes an issue where the data is null. It is also possible for applicants to be at the same address and phone. Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com>
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUserDataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('user_data', function (Blueprint $table) { $table->increments('id'); $table->string('burner_name')->nullable(); $table->string('real_name')->nullable(); $table->string('address'); $table->string('phone'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::drop('user_data'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUserDataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('user_data', function (Blueprint $table) { $table->increments('id'); $table->string('burner_name')->nullable(); $table->string('real_name')->nullable(); $table->string('address')->unique(); $table->string('phone')->unique(); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::drop('user_data'); } }
Switch request for next -- clearer terminology
'use strict'; module.exports = { name: require('./package.json').name, version: require('./package.json').version, register: function (plugin, options, next) { plugin.ext('onPreResponse', function (request, next) { var Hapi = plugin.hapi, response = request.response; if (response.variety === 'plain' && typeof response.source.then === 'function') { return response.source.then(function (res) { return next(res); }, function (err) { if (!err.isBoom) { err = Hapi.error.internal(err.message, err); } return next(err); }); } next(); }); next(); } };
'use strict'; module.exports = { name: require('./package.json').name, version: require('./package.json').version, register: function (plugin, options, next) { plugin.ext('onPreResponse', function (request, reply) { var Hapi = plugin.hapi, response = request.response; if (response.variety === 'plain' && typeof response.source.then === 'function') { return response.source.then(function (res) { return reply(res); }, function (err) { if (!err.isBoom) { err = Hapi.error.internal(err.message, err); } return reply(err); }); } reply(); }); next(); } };
Fix missing header causing crash
'use strict'; module.exports = function(config, ircbot, utils) { ircbot.emit('registerHttp', 'post', '/hooks/github', function(req, res) { const crypto = require('crypto'); if (!('x-hub-signature' in req.headers)) { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Bad request'); return; } const signature = req.headers['x-hub-signature']; const algo = signature.substr(0, signature.indexOf('=')); const expectedSignature = algo + '=' + crypto.createHmac(algo, config.secret).update(req.body).digest('hex'); if (signature !== expectedSignature) { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Bad request'); return; } const event = req.headers['x-github-event']; const payload = JSON.parse(req.body); res.writeHead(204, { 'Content-Type': 'text/plain' }); res.end(); ircbot.say(config.channel, utils.githubHook.formatMessage(event, payload)); }); };
'use strict'; module.exports = function(config, ircbot, utils) { ircbot.emit('registerHttp', 'post', '/hooks/github', function(req, res) { const crypto = require('crypto'); const signature = req.headers['x-hub-signature']; const algo = signature.substr(0, signature.indexOf('=')); const expectedSignature = algo + '=' + crypto.createHmac(algo, config.secret).update(req.body).digest('hex'); if (signature !== expectedSignature) { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Bad request'); return; } const event = req.headers['x-github-event']; const payload = JSON.parse(req.body); res.writeHead(204, { 'Content-Type': 'text/plain' }); res.end(); ircbot.say(config.channel, utils.githubHook.formatMessage(event, payload)); }); };
Fix label on angular example's describe block [ci skip]
'use strict'; var expect = require('chai').expect; var sinon = require('sinon'); var sinonAsPromised = require('sinon-as-promised'); var angular = require('angular'); describe('sinon-as-promised angular example', function () { var $timeout; beforeEach(angular.mock.inject(function ($rootScope, $q, _$timeout_) { sinonAsPromised($q); sinonAsPromised.setScheduler(function (fn) { $rootScope.$evalAsync(fn); }); $timeout = _$timeout_; })); it('can create a stub that resolves', function () { var stub = sinon.stub().resolves('value'); var fulfilled = false; stub().then(function (value) { fulfilled = true; expect(value).to.equal('value'); }); expect(fulfilled).to.be.false; $timeout.flush(); expect(fulfilled).to.be.true; }); });
'use strict'; var expect = require('chai').expect; var sinon = require('sinon'); var sinonAsPromised = require('sinon-as-promised'); var angular = require('angular'); describe('sinon-as-promised node example', function () { var $timeout; beforeEach(angular.mock.inject(function ($rootScope, $q, _$timeout_) { sinonAsPromised($q); sinonAsPromised.setScheduler(function (fn) { $rootScope.$evalAsync(fn); }); $timeout = _$timeout_; })); it('can create a stub that resolves', function () { var stub = sinon.stub().resolves('value'); var fulfilled = false; stub().then(function (value) { fulfilled = true; expect(value).to.equal('value'); }); expect(fulfilled).to.be.false; $timeout.flush(); expect(fulfilled).to.be.true; }); });
Add an example for Mapbox.
package com.github.tdesjardins.ol3.demo.client.example; /** * Provided example types. * * @author Tino Desjardins * */ public enum OL3ExampleType { AnimationExample(new AnimationExample()), ArcGISExample(new ArcGISExample()), GeoJSONExample(new GeoJSONExample()), GraticuleExample(new GraticuleExample()), ImageExample(new StaticImageExample()), MapBoxExample(new MapboxExample()), MapEventsExample(new MapEventsExample()), MapGuideExample(new MapGuideExample()), MarkerExample(new MarkerExample()), MeasureExample(new MeasureExample()), OsmExample(new OsmExample()), OverlayExample(new OverlayExample()), SelectFeatureExample(new SelectFeaturesExample()), TileExample(new TileExample()), TileWmsExample(new TileWmsExample()), WmsExample(new WmsExample()), WmtsExample(new WmtsExample()), XyzExample(new XyzExample()); private transient Example example; OL3ExampleType(Example example) { this.example = example; } public Example getExample() { return this.example; } }
package com.github.tdesjardins.ol3.demo.client.example; /** * Provided example types. * * @author Tino Desjardins * */ public enum OL3ExampleType { AnimationExample(new AnimationExample()), ArcGISExample(new ArcGISExample()), GeoJSONExample(new GeoJSONExample()), GraticuleExample(new GraticuleExample()), ImageExample(new StaticImageExample()), MapEventsExample(new MapEventsExample()), MapGuideExample(new MapGuideExample()), MarkerExample(new MarkerExample()), MeasureExample(new MeasureExample()), OsmExample(new OsmExample()), OverlayExample(new OverlayExample()), SelectFeatureExample(new SelectFeaturesExample()), TileExample(new TileExample()), TileWmsExample(new TileWmsExample()), WmsExample(new WmsExample()), WmtsExample(new WmtsExample()), XyzExample(new XyzExample()); private transient Example example; OL3ExampleType(Example example) { this.example = example; } public Example getExample() { return this.example; } }
Make everything a percentage of the total
#!/usr/bin/env python import sys if sys.argv.__len__() < 3: print "Usage : Enter time needed for each portion of the code" print " % overhead <advance> <exchange> <regrid>" sys.exit(); a = float(sys.argv[1]) e = float(sys.argv[2]) r = float(sys.argv[3]) o = r + e + a print " " # print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a) # print "%40s %6.1f%%" % ("Overhead as percentage of total",100.0*o/(a + o)) print "%40s %6.1f%%" % ("ADVANCE as percentage of total",100.0*a/o) print "%40s %6.1f%%" % ("EXCHANGE as percentage of total",100.0*e/o) print "%40s %6.1f%%" % ("REGRID as percentage of total",100.0*r/o) print " " print "Grid advances take %5.2f times as long as exchange and regridding" % (a/o) print " "
#!/usr/bin/env python import sys if sys.argv.__len__() < 3: print "Usage : Enter time needed for each portion of the code" print " % overhead <advance> <exchange> <regrid>" sys.exit(); a = float(sys.argv[1]) e = float(sys.argv[2]) r = float(sys.argv[3]) o = r + e print " " # print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a) # print "%40s %6.1f%%" % ("Overhead as percentage of total",100.0*o/(a + o)) print "%40s %6.1f%%" % ("ADVANCE as percentage of total",100.0*a/o) print "%40s %6.1f%%" % ("EXCHANGE as percentage of total",100.0*e/o) print "%40s %6.1f%%" % ("REGRID as percentage of total",100.0*r/o) print " " print "Grid advances take %5.2f times as long as exchange and regridding" % (a/o) print " "
Move initialization of logger and cfg parser to separate function.
#!/usr/bin/python import xmlrpclib, logging from ConfigParser import SafeConfigParser def init(): # Configure logging. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m/%d %H:%M:%S', filename='/tmp/kts46_rpc_client.log', filemode='w') # Define a handler for console message with mode simple format. console = logging.StreamHandler() console.setFormatter( logging.Formatter('L:%(levelname)-6s %(message)s') ) logger = logging.getLogger('kts46.rpc_client') logger.addHandler(console) # Create configuration. logger.debug('Reading configuration.') cfg = SafeConfigParser() cfg.read(('rpc_client.ini',)) return (cfg, logger) cfg, logger = init() # Create proxy. host = cfg.get('connection', 'server') port = cfg.getint('connection', 'port') connString = 'http://%s:%i' % (host, port) logger.info('Connecting to server %s' % connString) sp = xmlrpclib.ServerProxy(connString) # Say hello and print available functions. print sp.hello('Hello Mr. Server!')
#!/usr/bin/python import xmlrpclib, logging from ConfigParser import SafeConfigParser # Configure logging. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m/%d %H:%M:%S', filename='/tmp/kts46_rpc_client.log', filemode='w') # Define a handler for console message with mode simple format. console = logging.StreamHandler() console.setFormatter( logging.Formatter('L:%(levelname)-6s %(message)s') ) logger = logging.getLogger('kts46.rpc_client') logger.addHandler(console) # Create configuration. logger.debug('Reading configuration.') cfg = SafeConfigParser() cfg.read(('rpc_client.ini',)) # Create proxy. host = cfg.get('connection', 'server') port = cfg.getint('connection', 'port') connString = 'http://%s:%i' % (host, port) logger.info('Connecting to server %s' % connString) sp = xmlrpclib.ServerProxy(connString) # Say hello and print available functions. print sp.hello('Hello Mr. Server!')
Fix tests to now include the questions, which are now in the menu
# -*- coding: utf-8 -*- from __future__ import unicode_literals from aldryn_faq.menu import FaqCategoryMenu from .test_base import AldrynFaqTest, CMSRequestBasedTest class TestMenu(AldrynFaqTest, CMSRequestBasedTest): def test_get_nodes(self): # Test that the EN version of the menu has only category1 and its # question1, and is shown in English. request = self.get_page_request(None, self.user, '/en/') menu = FaqCategoryMenu() category1 = self.reload(self.category1, 'en') question1 = self.reload(self.question1, 'en') self.assertEqualItems( [menuitem.title for menuitem in menu.get_nodes(request)], [category1.name, question1.title] ) # Test that the DE version has 2 categories and their questions that # they are shown in German. request = self.get_page_request(None, self.user, '/de/') menu = FaqCategoryMenu() nodes = menu.get_nodes(request) self.assertEqualItems( [menuitem.title for menuitem in nodes], [self.category1.name, self.category2.name, self.question1.title, self.question2.title] )
# -*- coding: utf-8 -*- from __future__ import unicode_literals from aldryn_faq.menu import FaqCategoryMenu from django.utils.translation import ( get_language_from_request, ) from .test_base import AldrynFaqTest, CMSRequestBasedTest class TestMenu(AldrynFaqTest, CMSRequestBasedTest): def test_get_nodes(self): # Test that the EN version of the menu has only category1 and is shown # in English. request = self.get_page_request(None, self.user, '/en/') menu = FaqCategoryMenu() category1 = self.reload(self.category1, 'en') self.assertEqualItems( [menuitem.title for menuitem in menu.get_nodes(request)], [category1.name] ) # Test that the DE version has 2 categories and that they are shown in # German. request = self.get_page_request(None, self.user, '/de/') menu = FaqCategoryMenu() category1 = self.reload(self.category1, 'de') category2 = self.reload(self.category2, 'de') nodes = menu.get_nodes(request) self.assertEqualItems( [menuitem.title for menuitem in nodes], [category1.name, category2.name] )
Include YAML data file in the package
from setuptools import setup, find_packages import versioneer with open('requirements.txt') as f: requirements = f.read().splitlines() requirements = ['setuptools'] + requirements setup( name='pyxrf', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author='Brookhaven National Laboratory', url='https://github.com/NSLS-II/PyXRF', packages=find_packages(), entry_points={'console_scripts': ['pyxrf = pyxrf.gui:run']}, package_data={'pyxrf.view': ['*.enaml'], 'configs': ['*.json'], 'pyxrf.core': ['*.yaml']}, include_package_data=True, install_requires=requirements, python_requires='>=3.6', license='BSD', classifiers=['Development Status :: 3 - Alpha', "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries", "Intended Audience :: Science/Research"] )
from setuptools import setup, find_packages import versioneer with open('requirements.txt') as f: requirements = f.read().splitlines() requirements = ['setuptools'] + requirements setup( name='pyxrf', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author='Brookhaven National Laboratory', url='https://github.com/NSLS-II/PyXRF', packages=find_packages(), entry_points={'console_scripts': ['pyxrf = pyxrf.gui:run']}, package_data={'pyxrf.view': ['*.enaml'], 'configs': ['*.json']}, include_package_data=True, install_requires=requirements, python_requires='>=3.6', license='BSD', classifiers=['Development Status :: 3 - Alpha', "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Software Development :: Libraries", "Intended Audience :: Science/Research"] )
Add ability to limit products and taxons when looking for name part
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Taxonomy\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\Taxonomy\Model\TaxonInterface; interface TaxonRepositoryInterface extends RepositoryInterface { /** * @return array|TaxonInterface[] */ public function findChildren(string $parentCode, ?string $locale = null): array; /** * @return array|TaxonInterface[] */ public function findRootNodes(): array; public function findOneBySlug(string $slug, string $locale): ?TaxonInterface; /** * @return array|TaxonInterface[] */ public function findByName(string $name, string $locale): array; /** * @return array|TaxonInterface[] */ public function findByNamePart(string $phrase, ?string $locale = null, ?int $limit = null): array; public function createListQueryBuilder(): QueryBuilder; }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Taxonomy\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\Taxonomy\Model\TaxonInterface; interface TaxonRepositoryInterface extends RepositoryInterface { /** * @return array|TaxonInterface[] */ public function findChildren(string $parentCode, ?string $locale = null): array; /** * @return array|TaxonInterface[] */ public function findRootNodes(): array; public function findOneBySlug(string $slug, string $locale): ?TaxonInterface; /** * @return array|TaxonInterface[] */ public function findByName(string $name, string $locale): array; /** * @return array|TaxonInterface[] */ public function findByNamePart(string $phrase, ?string $locale = null): array; public function createListQueryBuilder(): QueryBuilder; }
Convert the output to numbers, not strings
// ---------------------------------------------------------------------------- // // cigar-plugin-device // // Copyright 2013 Andrew Chilton. All Rights Reserved. // // License: MIT // // ---------------------------------------------------------------------------- // core var exec = require('child_process').exec; // ---------------------------------------------------------------------------- function convertToInt(field) { field = field.substr(0, field.length-1); return parseInt(field, 10); } module.exports = function(opts, callback) { // just get the df stats for this device opts.unit = opts.unit || 'G'; exec('df -B' + opts.unit + ' ' + opts.device + ' | tail -1', function (err, stdout, stderr) { if (err) return callback(err); var fields = stdout.split(/\s+/); var data = { used : convertToInt(fields[2]), free : convertToInt(fields[3]), total : convertToInt(fields[1]), }; callback(null, data); }); }; // ----------------------------------------------------------------------------
// ---------------------------------------------------------------------------- // // cigar-plugin-device // // Copyright 2013 Andrew Chilton. All Rights Reserved. // // License: MIT // // ---------------------------------------------------------------------------- // core var exec = require('child_process').exec; // ---------------------------------------------------------------------------- module.exports = function(options, callback) { // just get the df stats for this device options.unit = options.unit || 'G'; exec('df -B' + options.unit + ' ' + options.device + ' | tail -1', function (err, stdout, stderr) { if (err) return callback(err); console.log(stdout); var fields = stdout.split(/\s+/); console.log(fields); var data = { used : fields[2].substr(0, fields[2].length-1), free : fields[3].substr(0, fields[3].length-1), total : fields[1].substr(0, fields[1].length-1), }; console.log(data) callback(null, data); }); }; // ----------------------------------------------------------------------------
Make docket export work (done last week, but not committed for some reason).
#!/usr/bin/env python import sys import os import csv import time from datetime import datetime from collections import namedtuple from pymongo import Connection pid = os.getpid() DOCKETS_QUERY = {'scraped': True} DOCKET_FIELDS = ['docket_id', 'title', 'agency', 'year'] def filter_for_postgres(v): if v is None: return '\N' if isinstance(v, datetime): return str(v) return unicode(v).encode('utf8').replace("\.", ".") if __name__ == '__main__': # set up options from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] host dbname file_prefix") (options, args) = parser.parse_args() # fetch options, args host = args[0] dbname = args[1] prefix = args[2] writer = csv.writer(open(sys.argv[3] + '_dockets.csv', 'w')) writer.writerow(DOCKET_FIELDS) cursor = Connection(host=host)[dbname].dockets.find(DOCKETS_QUERY) run_start = time.time() print '[%s] Starting export...' % pid for row in cursor: writer.writerow([filter_for_postgres(row[field]) for field in DOCKET_FIELDS]) print '[%s] Completed export in %s seconds.' % (pid, time.time() - run_start)
#!/usr/bin/env python import sys import os import csv import time from datetime import datetime from collections import namedtuple from pymongo import Connection pid = os.getpid() DOCKETS_QUERY = {'scraped': True} DOCKET_FIELDS = ['docket_id', 'title', 'agency', 'year'] if __name__ == '__main__': # set up options from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] host dbname file_prefix") (options, args) = parser.parse_args() # fetch options, args host = args[0] dbname = args[1] prefix = args[2] writer = csv.writer(open(sys.argv[3] + '_dockets.csv', 'w')) writer.writerow(DOCKET_FIELDS) cursor = Connection(host=host)[dbname].docs.find(DOCS_QUERY) run_start = time.time() print '[%s] Starting export...' % pid for row in cursor: csv.writerow([row[field] for field in DOCKET_FIELDS]) print '[%s] Completed export in %s seconds.' % (pid, time.time() - run_start)
Use defined constant for DOCKER
import {JSONReducer as env} from './serviceForm/EnvironmentVariables'; import {JSONReducer as labels} from './serviceForm/Labels'; import {JSONReducer as volumes} from './serviceForm/Volumes'; import {JSONReducer as healthChecks} from './serviceForm/HealthChecks'; import { combineReducers, simpleFloatReducer, simpleIntReducer, simpleReducer } from '../../../../../src/js/utils/ReducerUtil'; import VolumeConstants from '../constants/VolumeConstants'; const {DOCKER} = VolumeConstants.type; module.exports = { id: simpleReducer('id'), instances: simpleIntReducer('instances'), container: combineReducers({ type: simpleReducer('container.type', DOCKER), docker: combineReducers({ priviliged: simpleReducer('container.docker.privileged', false), forecePullImage: simpleReducer('container.docker.forcePullImage', false), image: simpleReducer('container.docker.image', '') }), volumes }), cpus: simpleFloatReducer('cpus'), mem: simpleIntReducer('mem'), disk: simpleIntReducer('disk'), cmd: simpleReducer('cmd'), env, labels, healthChecks };
import {JSONReducer as env} from './serviceForm/EnvironmentVariables'; import {JSONReducer as labels} from './serviceForm/Labels'; import {JSONReducer as volumes} from './serviceForm/Volumes'; import {JSONReducer as healthChecks} from './serviceForm/HealthChecks'; import { combineReducers, simpleFloatReducer, simpleIntReducer, simpleReducer } from '../../../../../src/js/utils/ReducerUtil'; module.exports = { id: simpleReducer('id'), instances: simpleIntReducer('instances'), container: combineReducers({ type: simpleReducer('container.type', 'DOCKER'), docker: combineReducers({ priviliged: simpleReducer('container.docker.privileged', false), forecePullImage: simpleReducer('container.docker.forcePullImage', false), image: simpleReducer('container.docker.image', '') }), volumes }), cpus: simpleFloatReducer('cpus'), mem: simpleIntReducer('mem'), disk: simpleIntReducer('disk'), cmd: simpleReducer('cmd'), env, labels, healthChecks };
Use Protokollen class instead of raw MySQL queries
#!/usr/bin/env php <?php /** * Protokollen - create services and add hostnames from entity definitions */ require_once('../php/Protokollen.class.php'); $p = new Protokollen(); foreach($p->listEntityDomains() as $domain) { /* Load entity */ $e = $p->getEntityByDomain($domain); /* Add HTTP service */ $s = $p->addService($e->id, Protokollen::SERVICE_TYPE_HTTP, $e->domain, 'Webbsajt '. $e->org); $p->addServiceHostname($s->id, $e->domain); $p->addServiceHostname($s->id, 'www.'. $e->domain); /* Add SMTP service */ if($e->domain_email === NULL) continue; $s = $p->addService($e->id, Protokollen::SERVICE_TYPE_SMTP, $e->domain_email, 'E-postdomän '. $e->org); /* Not yet implemented - should this be MX pointers instead? */ $p->addServiceHostname($s->id, $e->domain_email); }
#!/usr/bin/env php <?php /** * Protokollen - create services and add hostnames from entity definitions */ require_once('../php/Protokollen.class.php'); $p = new Protokollen(); $m = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); $m->set_charset(DB_CHARSET) or die("$m->error\n"); $q = 'SELECT domain FROM entities WHERE domain IS NOT NULL ORDER BY id'; $r = $m->query($q) or die("$m->error, SQL: $q\n"); while($row = $r->fetch_object()) { /* Load entity */ $e = $p->getEntityByDomain($row->domain); /* Add HTTP service */ $s = $p->addService($e->id, Protokollen::SERVICE_TYPE_HTTP, $e->domain, 'Webbsajt '. $e->org); $p->addServiceHostname($s->id, $e->domain); $p->addServiceHostname($s->id, 'www.'. $e->domain); /* Add SMTP service */ if($e->domain_email === NULL) continue; $s = $p->addService($e->id, Protokollen::SERVICE_TYPE_SMTP, $e->domain_email, 'E-postdomän '. $e->org); /* Not yet implemented - should this be MX pointers instead? */ $p->addServiceHostname($s->id, $e->domain_email); } $r->close();
Use console highlighting in example
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Sphinx extension to add a ``version-code-block`` directive This directive allows Flocker's release version to be inserted into code blocks. .. version-code-block:: console $ brew install flocker-|RELEASE| """ from sphinx.directives.code import CodeBlock from flocker import __version__ as version class VersionCodeBlock(CodeBlock): """ Similar to CodeBlock but replaces |RELEASE| with the latest release version. """ def run(self): # Use the WIP get_doc_version to get the latest release version # from https://github.com/ClusterHQ/flocker/pull/1092/ self.content = [item.replace(u'|RELEASE|', version) for item in self.content] block = CodeBlock(self.name, self.arguments, self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return block.run() def setup(app): app.add_directive('version-code-block', VersionCodeBlock)
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Sphinx extension to add a ``version-code-block`` directive This directive allows Flocker's release version to be inserted into code blocks. .. version-code-block:: rest $ brew install flocker-|RELEASE| """ from sphinx.directives.code import CodeBlock from flocker import __version__ as version class VersionCodeBlock(CodeBlock): """ Similar to CodeBlock but replaces |RELEASE| with the latest release version. """ def run(self): # Use the WIP get_doc_version to get the latest release version # from https://github.com/ClusterHQ/flocker/pull/1092/ self.content = [item.replace(u'|RELEASE|', version) for item in self.content] block = CodeBlock(self.name, self.arguments, self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) return block.run() def setup(app): app.add_directive('version-code-block', VersionCodeBlock)