text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix rendering of alfred.is data to json file
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy def single_item_serializer(value): # values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',) # so need to return just the fist value when serializing if isinstance(value, (list, tuple)): return value[0] return value class JobsItem(scrapy.Item): title = scrapy.Field(serializer=single_item_serializer) company = scrapy.Field(serializer=single_item_serializer) url = scrapy.Field(serializer=single_item_serializer) posted = scrapy.Field(serializer=single_item_serializer) deadline = scrapy.Field(serializer=single_item_serializer) views = scrapy.Field(serializer=int)
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy def single_item_serializer(value): # values are nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',) # so need to return just the fist value when serializing return value[0] class JobsItem(scrapy.Item): title = scrapy.Field(serializer=single_item_serializer) company = scrapy.Field(serializer=single_item_serializer) url = scrapy.Field(serializer=single_item_serializer) posted = scrapy.Field(serializer=single_item_serializer) deadline = scrapy.Field(serializer=single_item_serializer) views = scrapy.Field(serializer=int)
Fix import bardarash conf import path
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # noqa from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'library', }, { 'id': 'mediacenter', }, { 'id': 'khanacademy', } ]
"""Bardarash in Kurdistan, Iraq""" from .azraq import * # noqa from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'library', }, { 'id': 'mediacenter', }, { 'id': 'khanacademy', } ]
Simplify logic, add type hint
<?php /* * This file is part of the Zephir. * * (c) Zephir Team <team@zephir-lang.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Zephir\Documentation\Annotation; use Zephir\Documentation\Annotation; /** * A return annotation that looks like `(@)return type description`. */ class ReturnAnnotation extends Annotation { protected $returnType; protected $description; public function getReturnType(): string { if (!$this->contentParsed) { $this->parseContent(); } return $this->returnType; } public function getDescription(): string { if (!$this->contentParsed) { $this->parseContent(); } return $this->description; } protected function parseContent() { $spaceIndex = strpos($this->string, ' '); $this->returnType = $this->string; if (false !== $spaceIndex) { $this->returnType = substr($this->string, 0, $spaceIndex); $this->description = substr($this->string, $spaceIndex + 1); } $this->contentParsed = true; } }
<?php /* * This file is part of the Zephir. * * (c) Zephir Team <team@zephir-lang.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Zephir\Documentation\Annotation; use Zephir\Documentation\Annotation; /** * A return annotation that looks like `(@)return type description`. */ class ReturnAnnotation extends Annotation { protected $returnType; protected $description; public function getReturnType() { if (!$this->contentParsed) { $this->parseContent(); } return $this->returnType; } public function getDescription() { if (!$this->contentParsed) { $this->parseContent(); } return $this->description; } protected function parseContent() { $spaceIndex = strpos($this->string, ' '); if (false !== $spaceIndex) { $this->returnType = substr($this->string, 0, $spaceIndex); $this->description = substr($this->string, $spaceIndex + 1); } else { $this->returnType = $this->string; } $this->contentParsed = true; } }
Remove LMOD_CMD global from module scope Declaring the variable at the module level could cause problem when installing and enabling the extension when Lmod was not activated.
from os import environ from subprocess import Popen, PIPE LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '') def module(command, arguments=()): cmd = [environ['LMOD_CMD'], 'python', '--terse', command] cmd.extend(arguments) result = Popen(cmd, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def module_avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def module_list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def module_savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names
import os from subprocess import Popen, PIPE LMOD_CMD = os.environ['LMOD_CMD'] LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '') def module(command, arguments=()): cmd = [LMOD_CMD, 'python', '--terse', command] cmd.extend(arguments) result = Popen(cmd, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def module_avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def module_list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def module_savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names
Check if form is submitted first
<?php namespace ForkCMS\Bundle\InstallerBundle\Form\Handler; use ForkCMS\Bundle\InstallerBundle\Entity\InstallationData; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; /** * Base class to validate and save data from the installer form */ abstract class InstallerHandler { /** * @param Form $form * @param Request $request * * @return bool */ final public function process(Form $form, Request $request): bool { if (!$request->isMethod('POST')) { return false; } $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $request->getSession()->set('installation_data', $this->processInstallationData($form->getData())); return true; } return false; } /** * @param InstallationData $installationData * * @return InstallationData */ abstract public function processInstallationData(InstallationData $installationData): InstallationData; }
<?php namespace ForkCMS\Bundle\InstallerBundle\Form\Handler; use ForkCMS\Bundle\InstallerBundle\Entity\InstallationData; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; /** * Base class to validate and save data from the installer form */ abstract class InstallerHandler { /** * @param Form $form * @param Request $request * * @return bool */ final public function process(Form $form, Request $request): bool { if (!$request->isMethod('POST')) { return false; } $form->handleRequest($request); if ($form->isValid()) { $request->getSession()->set('installation_data', $this->processInstallationData($form->getData())); return true; } return false; } /** * @param InstallationData $installationData * * @return InstallationData */ abstract public function processInstallationData(InstallationData $installationData): InstallationData; }
Update Orchestra\Mail to follow latest update on Messages bundle Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra; use \Closure, \IoC; class Mail { /** * Make a new Orchestra\Mail instance. * * <code> * Orchestra\Mail::send('view.file', array(), function ($mail) * { * $mail->to('example@test.com', "Username") * ->subject("An awesome title") * ->send(); * }); * </code> * * @static * @access public * @param string $view * @param mixed $data * @param Closure $callback * @return self */ public static function send($view, $data = array(), Closure $callback) { $instance = new static($view, $data, $callback); return $instance->mailer; } /** * Swiftmailer mail instance. * * @var Object */ private $mailer = null; /** * Construct a new instance. * * @access public * @param string $view * @param mixed $data * @param Closure $callback * @return void */ public function __construct($view, $data = array(), Closure $callback) { $view = View::make($view, $data); $this->mailer = IoC::resolve('orchestra.mailer'); $this->mailer->body($view); $this->mailer->html(true); call_user_func($callback, $this->mailer); } }
<?php namespace Orchestra; use \Closure, \IoC; class Mail { /** * Make a new Orchestra\Mail instance. * * <code> * Orchestra\Mail::send('view.file', array(), function ($mail) * { * $mail->to('example@test.com', "Username") * ->subject("An awesome title") * ->send(); * }); * </code> * * @static * @access public * @param string $view * @param mixed $data * @param Closure $callback * @return self */ public static function send($view, $data = array(), Closure $callback) { $instance = new static($view, $data, $callback); return $instance->mailer; } /** * Swiftmailer mail instance. * * @var Object */ private $mailer = null; /** * Construct a new instance. * * @access public * @param string $view * @param mixed $data * @param Closure $callback * @return void */ public function __construct($view, $data = array(), Closure $callback) { $view = View::make($view, $data); $this->mailer = IoC::resolve('orchestra.mailer'); $this->mailer->body($view->render(), 'text/html'); call_user_func($callback, $this->mailer); } }
Fix example to use the right module name
var zmqbus = require('zmqbus'); /* simple quote sender/reader. Run multiple processes to send/receive cluster-wide. */ var node = zmqbus.createNode(); node.on('ready', function() { // subscribe to equity channel node.subscribe("equity"); setInterval(fakeEquityQuote, 1000); // uncomment the following to receive temperature readings // node.subscribe("temp") setInterval(fakeTemperatureQuote, 2000); }); node.on('message', function(msg) { console.log("received " + msg); }); function fakeEquityQuote() { // broadcast some fake stock quotes var stocks = ['AAPL', 'GOOG', 'IBM', 'FB']; var symbol = stocks[Math.floor(Math.random() * stocks.length)]; var quote = (Math.random() * 100.0 + 25.0).toFixed(2); node.publish('equity', symbol, quote); } function fakeTemperatureQuote() { // broadcast some fake stock quotes var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL']; var city = cities[Math.floor(Math.random() * cities.length)]; var quote = (Math.random() * 50.0 + 30.0).toFixed(2); node.publish('temp', city, quote); }
var zmqbus = require('../lib/index.js'); /* simple quote sender/reader. Run multiple processes to send/receive cluster-wide. */ var node = zmqbus.createNode(); node.on('ready', function() { // subscribe to equity channel node.subscribe("equity"); setInterval(fakeEquityQuote, 1000); // uncomment the following to receive temperature readings // node.subscribe("temp") setInterval(fakeTemperatureQuote, 2000); }); node.on('message', function(msg) { console.log("received " + msg); }); function fakeEquityQuote() { // broadcast some fake stock quotes var stocks = ['AAPL', 'GOOG', 'IBM', 'FB']; var symbol = stocks[Math.floor(Math.random() * stocks.length)]; var quote = (Math.random() * 100.0 + 25.0).toFixed(2); node.publish('equity', symbol, quote); } function fakeTemperatureQuote() { // broadcast some fake stock quotes var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL']; var city = cities[Math.floor(Math.random() * cities.length)]; var quote = (Math.random() * 50.0 + 30.0).toFixed(2); node.publish('temp', city, quote); }
Add --limit and filtering options to task event-list
import click from globus_cli.parsing import common_options, task_id_arg from globus_cli.helpers import outformat_is_json, print_table from globus_cli.services.transfer import print_json_from_iterator, get_client @click.command('event-list', help='List Events for a given Task') @common_options @task_id_arg @click.option( "--limit", default=10, show_default=True, help="Limit number of results.") @click.option( "--filter-errors", is_flag=True, help="Filter results to errors") @click.option( "--filter-non-errors", is_flag=True, help="Filter results to non errors") def task_event_list(task_id, limit, filter_errors, filter_non_errors): """ Executor for `globus task-event-list` """ client = get_client() # set filter based on filter flags, if both set do nothing filter_string = None if filter_errors and not filter_non_errors: filter_string = "is_error:1" if filter_non_errors and not filter_errors: filter_string = "is_error:1" event_iterator = client.task_event_list( task_id, num_results=limit, filter=filter_string) if outformat_is_json(): print_json_from_iterator(event_iterator) else: print_table(event_iterator, [ ('Time', 'time'), ('Code', 'code'), ('Is Error', 'is_error'), ('Details', 'details')])
import click from globus_cli.parsing import common_options, task_id_arg from globus_cli.helpers import outformat_is_json, print_table from globus_cli.services.transfer import print_json_from_iterator, get_client @click.command('event-list', help='List Events for a given Task') @common_options @task_id_arg def task_event_list(task_id): """ Executor for `globus task-event-list` """ client = get_client() event_iterator = client.task_event_list(task_id) if outformat_is_json(): print_json_from_iterator(event_iterator) else: print_table(event_iterator, [ ('Time', 'time'), ('Code', 'code'), ('Is Error', 'is_error'), ('Details', 'details')])
Change stage -> status column
<?php RequestHandler::$responseMode = 'csv'; RequestHandler::respond('projects', array( 'data' => array_map(function($Project) { preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches); return array( 'name' => $Project->Title ,'description' => trim($matches[0]) ,'link_url' => $Project->UsersUrl ,'code_url' => $Project->DevelopersUrl ,'tags' => implode(',', array_map( function($Tag) { return $Tag->UnprefixedTitle; } ,Tag::getTagsWithPrefix($Project->Tags, 'topic') ) ) ,'status' => $Project->Stage ); }, Laddr\Project::getAll()) ));
<?php RequestHandler::$responseMode = 'csv'; RequestHandler::respond('projects', array( 'data' => array_map(function($Project) { preg_match('/^\s*[^*#]\s*\w.*/m', $Project->README, $matches); return array( 'name' => $Project->Title ,'description' => trim($matches[0]) ,'link_url' => $Project->UsersUrl ,'code_url' => $Project->DevelopersUrl ,'tags' => implode(',', array_map( function($Tag) { return $Tag->UnprefixedTitle; } ,Tag::getTagsWithPrefix($Project->Tags, 'topic') ) ) ,'stage' => $Project->Stage ); }, Laddr\Project::getAll()) ));
Fix chopped off data for twelve hours
const React = require('react'); const Styled = require('styled-components'); const fns = require('../../shared/functions'); const constants = require('../../shared/constants'); const CloseIcon = require( '!babel-loader!svg-react-loader!./close.svg?name=CloseIcon' ); const { default: styled } = Styled; const { remcalc } = fns; const { colors } = constants; const StyledButton = styled.button` position: relative; display: flex; margin: 0; padding: ${remcalc(18)} ${remcalc(24)}; color: ${colors.brandPrimaryColor}; float: right; background-color: ${colors.brandPrimaryDark}; line-height: 1.5; border: none; border-left: solid ${remcalc(1)} ${colors.brandPrimaryDarkest}; cursor: pointer; `; const StyledIcon = styled(CloseIcon)` fill: ${colors.brandPrimaryColor}; `; const AddMetricButton = ({ onClick }) => { const onButtonClick = (e) => onClick(); return ( <StyledButton name='close-button' onClick={onButtonClick} > <StyledIcon /> </StyledButton> ); }; AddMetricButton.propTypes = { onClick: React.PropTypes.func, }; module.exports = AddMetricButton;
const React = require('react'); const Styled = require('styled-components'); const fns = require('../../shared/functions'); const constants = require('../../shared/constants'); const CloseIcon = require( '!babel!svg-react!./close.svg?name=CloseIcon' ); const { default: styled } = Styled; const { remcalc } = fns; const { colors } = constants; const StyledButton = styled.button` position: relative; display: flex; margin: 0; padding: ${remcalc(18)} ${remcalc(24)}; color: ${colors.brandPrimaryColor}; float: right; background-color: ${colors.brandPrimaryDark}; line-height: 1.5; border: none; border-left: solid ${remcalc(1)} ${colors.brandPrimaryDarkest}; cursor: pointer; `; const StyledIcon = styled(CloseIcon)` fill: ${colors.brandPrimaryColor}; `; const AddMetricButton = ({ onClick }) => { const onButtonClick = (e) => onClick(); return ( <StyledButton name='close-button' onClick={onButtonClick} > <StyledIcon /> </StyledButton> ); }; AddMetricButton.propTypes = { onClick: React.PropTypes.func, }; module.exports = AddMetricButton;
Fix bug removing FILE: from ccache name.
// vim:shiftwidth=4:tabstop=4:expandtab import sun.security.krb5.PrincipalName; import sun.security.krb5.internal.ccache.FileCredentialsCache; public class kwho { public static void main(String[] args) { String cache = System.getenv("KRB5CCNAME"); if (cache == null) { return; } // The FileCredentialsCache does not want to see the "FILE:" prefix cache = cache.replaceAll("^FILE:", ""); //assumes credendials cache of type "FILE:" FileCredentialsCache fcc = FileCredentialsCache.acquireInstance(null, cache); if (fcc == null) { return; } PrincipalName princ = fcc.getPrimaryPrincipal(); String[] nameStrings = princ.getNameStrings(); StringBuffer temp = new StringBuffer(nameStrings[0]); for (int i=1; i<nameStrings.length; i++) { temp.append("/"); temp.append(nameStrings[i]); } System.out.println(temp); } }
// vim:shiftwidth=4:tabstop=4:expandtab import sun.security.krb5.PrincipalName; import sun.security.krb5.internal.ccache.FileCredentialsCache; public class kwho { public static void main(String[] args) { String cache = System.getenv("KRB5CCNAME"); if (cache == null) { return; } // The FileCredentialsCache does not want to see the "FILE:" prefix cache = cache.replaceAll("^FILE:", cache); //assumes credendials cache of type "FILE:" FileCredentialsCache fcc = FileCredentialsCache.acquireInstance(null, cache); if (fcc == null) { return; } PrincipalName princ = fcc.getPrimaryPrincipal(); String[] nameStrings = princ.getNameStrings(); StringBuffer temp = new StringBuffer(nameStrings[0]); for (int i=1; i<nameStrings.length; i++) { temp.append("/"); temp.append(nameStrings[i]); } System.out.println(temp); } }
Add official support for Python 3.10
#! /usr/bin/env python3 from setuptools import setup from hsluv import __version__ setup( name='hsluv', version=__version__, description='Human-friendly HSL', long_description=open('README.md').read(), long_description_content_type='text/markdown', license="MIT", author_email="alexei@boronine.com", url="https://www.hsluv.org", keywords="color hsl cie cieluv colorwheel hsluv hpluv", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3 :: Only", ], python_requires='>=3.7', setup_requires=[ 'setuptools>=38.6.0', # for long_description_content_type ], py_modules=["hsluv"], test_suite="tests.test_hsluv" )
#! /usr/bin/env python3 from setuptools import setup from hsluv import __version__ setup( name='hsluv', version=__version__, description='Human-friendly HSL', long_description=open('README.md').read(), long_description_content_type='text/markdown', license="MIT", author_email="alexei@boronine.com", url="https://www.hsluv.org", keywords="color hsl cie cieluv colorwheel hsluv hpluv", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3 :: Only", ], python_requires='>=3.7', setup_requires=[ 'setuptools>=38.6.0', # for long_description_content_type ], py_modules=["hsluv"], test_suite="tests.test_hsluv" )
Add method to broadcast to all players
/* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.effect; import net.tridentsdk.entity.living.Player; import net.tridentsdk.util.Vector; /** * Represents effects that can be executed without an entity * * @author The TridentSDK Team * @since 0.4-alpha */ public interface RemoteEffect<T> extends Effect<T> { /** * Execute the effect at the given location */ void apply(); /** * Execute the effect at the given location for specified player * * @param player The player to send the effect to */ void apply(Player player); /** * Set the position of the effect * * @param vector The vector of the effect */ void setPosition(Vector vector); }
/* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.effect; import net.tridentsdk.entity.living.Player; import net.tridentsdk.util.Vector; /** * Represents effects that can be executed without an entity * * @author The TridentSDK Team * @since 0.4-alpha */ public interface RemoteEffect<T> extends Effect<T> { /** * Execute the effect at the given location for specified player * * @param player The player to send the effect to */ void apply(Player player); /** * Set the position of the effect * * @param vector The vector of the effect */ void setPosition(Vector vector); }
Make sure our ReadableStream can be written to
module.exports = function(runtime) { var STREAM_MODULE = 'stream'; function Readable() { Readable.$super.call(this); this._args = arguments; this._rendered = false; } Readable.prototype = { write: function(data) { this.push(data); }, end: function() { this.push(null); }, _read: function() { if (this._rendered) { return; } this._rendered = true; var args = this._args; var templatePath = args[0]; var data = args[1]; var context = runtime.createContext(this); runtime.render(templatePath, data, context); context.end(); } }; require('raptor-util').inherit(Readable, require(STREAM_MODULE).Readable); return function stream(templatePath, data) { return new Readable(templatePath, data); }; };
module.exports = function(runtime) { var STREAM_MODULE = 'stream'; function Readable() { Readable.$super.call(this); this._args = arguments; this._rendered = false; } Readable.prototype = { _read: function() { if (this._rendered) { return; } this._rendered = true; var args = this._args; var templatePath = args[0]; var data = args[1]; var context = runtime.createContext(this); runtime.render(templatePath, data, context); } }; require('raptor-util').inherit(Readable, require(STREAM_MODULE).Readable); return function stream(templatePath, data) { return new Readable(templatePath, data); }; };
Add some unit test on utils.io
import difflib import numpy as np import pytest from mbuild.tests.base_test import BaseTest from mbuild.utils.io import get_fn, import_ from mbuild.utils.validation import assert_port_exists class TestUtils(BaseTest): def test_assert_port_exists(self, ch2): assert_port_exists('up', ch2) with pytest.raises(ValueError): assert_port_exists('dog', ch2) def test_structure_reproducibility(self, alkane_monolayer): filename = 'monolayer-tmp.pdb' alkane_monolayer.save(filename) with open(get_fn('monolayer.pdb')) as file1: with open('monolayer-tmp.pdb') as file2: diff = difflib.ndiff(file1.readlines(), file2.readlines()) changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')] assert not changes def test_fn(self): get_fn('benzene.mol2') with pytest.raises((IOError, OSError)): get_fn('garbage_file_name.foo') def test_import(self): assert np == import_('numpy') with pytest.raises(ImportError): import_('garbagepackagename')
import difflib import pytest from mbuild.tests.base_test import BaseTest from mbuild.utils.io import get_fn from mbuild.utils.validation import assert_port_exists class TestUtils(BaseTest): def test_assert_port_exists(self, ch2): assert_port_exists('up', ch2) with pytest.raises(ValueError): assert_port_exists('dog', ch2) def test_structure_reproducibility(self, alkane_monolayer): filename = 'monolayer-tmp.pdb' alkane_monolayer.save(filename) with open(get_fn('monolayer.pdb')) as file1: with open('monolayer-tmp.pdb') as file2: diff = difflib.ndiff(file1.readlines(), file2.readlines()) changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')] assert not changes
Use deterministic name to make test always fail Problem: The test passes if the directory already exists, which makes it intermittent and hard to debug. Solution: Use a unique directory name for each instance of the test, which makes the test fail consistently.
'use strict' var tape = require('tape') var pull = require('pull-stream') var createSSB = require('./create-ssb') var keys = require('ssb-keys').generate() var content = { type: 'whatever' } const name = `test-ssb-close-${Date.now()}` tape('load', function (t) { t.plan(1) var ssb = createSSB(name, { keys, temp: false }) ssb.createFeed().add(content, function (err, msg) { if (err) throw err // console.log(msg) ssb.close(function () { t.ok(true, 'closes + runs callback') }) }) }) tape('reopen', function (t) { t.plan(1) var ssb = createSSB(name, { keys, temp: false }) pull( ssb.createLogStream(), pull.collect(function (err, ary) { if (err) throw err t.deepEqual(ary[0].value.content, content, 'reopen works fine') }) ) })
'use strict' var tape = require('tape') var pull = require('pull-stream') var createSSB = require('./create-ssb') var keys = require('ssb-keys').generate() var content = { type: 'whatever' } tape('load', function (t) { t.plan(1) var ssb = createSSB('test-ssb-feed', { keys, temp: false }) ssb.createFeed().add(content, function (err, msg) { if (err) throw err // console.log(msg) ssb.close(function () { t.ok(true, 'closes + runs callback') }) }) }) tape('reopen', function (t) { t.plan(1) var ssb = createSSB('test-ssb-feed', { keys, temp: false }) pull( ssb.createLogStream(), pull.collect(function (err, ary) { if (err) throw err t.deepEqual(ary[0].value.content, content, 'reopen works fine') }) ) })
Add Drivers/PostgreSQL to the list of autoloaded paths
<?php /* * Autoload controllers and modules */ function autoload($className) { foreach (array( 'include/resto/', 'include/resto/Drivers/', 'include/resto/Drivers/PostgreSQL/', 'include/resto/Collections/', 'include/resto/Models/', 'include/resto/Dictionaries/', 'include/resto/Modules/', 'include/resto/Routes/', 'include/resto/Utils/', 'lib/iTag/', 'lib/JWT/') as $current_dir) { $path = $current_dir . sprintf('%s.php', $className); if (file_exists($path)) { include $path; return; } } } spl_autoload_register('autoload'); /* * Launch RESTo */ new Resto(realpath(dirname(__FILE__)) . '/include/config.php');
<?php /* * Autoload controllers and modules */ function autoload($className) { foreach (array( 'include/resto/', 'include/resto/Drivers/', 'include/resto/Collections/', 'include/resto/Models/', 'include/resto/Dictionaries/', 'include/resto/Modules/', 'include/resto/Routes/', 'include/resto/Utils/', 'lib/iTag/', 'lib/JWT/') as $current_dir) { $path = $current_dir . sprintf('%s.php', $className); if (file_exists($path)) { include $path; return; } } } spl_autoload_register('autoload'); /* * Launch RESTo */ new Resto(realpath(dirname(__FILE__)) . '/include/config.php');
Add png mime type to the download blob
import React, { Component } from 'react'; import downloadIcon from '../icons/downloadIcon.svg'; class DownloadButton extends Component { constructor(props) { super(props); this.downloadImage = this.downloadImage.bind(this); this.downloadCanvasBlob = this.downloadCanvasBlob.bind(this); this.revokeURL = this.revokeURL.bind(this); // refs this.imagedownloader = null; } render() { return ( <div className="right"> <a className="hiddenInput" ref={input => {this.imagedownloader = input;}} onClick={this.revokeURL}/> <button type="button" onClick={this.downloadImage}> <img className="button-icon" src={downloadIcon} alt="upload icon"/> <span className="button-text">Download</span> </button> </div> ); } downloadImage(e) { if (this.props.canvas.hasImage) { this.props.canvas.toBlob(this.downloadCanvasBlob, 'image/png'); } } downloadCanvasBlob(blob) { this.imagedownloader.href = URL.createObjectURL(blob); this.imagedownloader.download = "bestest image"; this.imagedownloader.click(); } revokeURL() { // requestAnimationFrame makes the browser prepare the file for download // before revoking the URL requestAnimationFrame(() => URL.revokeObjectURL(this.imagedownloader.href)); } } export default DownloadButton;
import React, { Component } from 'react'; import downloadIcon from '../icons/downloadIcon.svg'; class DownloadButton extends Component { constructor(props) { super(props); this.downloadImage = this.downloadImage.bind(this); this.downloadCanvasBlob = this.downloadCanvasBlob.bind(this); this.revokeURL = this.revokeURL.bind(this); // refs this.imagedownloader = null; } render() { return ( <div className="right"> <a className="hiddenInput" ref={input => {this.imagedownloader = input;}} onClick={this.revokeURL}/> <button type="button" onClick={this.downloadImage}> <img className="button-icon" src={downloadIcon} alt="upload icon"/> <span className="button-text">Download</span> </button> </div> ); } downloadImage(e) { if (this.props.canvas.hasImage) { this.props.canvas.toBlob(this.downloadCanvasBlob); } } downloadCanvasBlob(blob) { this.imagedownloader.href = URL.createObjectURL(blob); this.imagedownloader.download = "bestest image"; this.imagedownloader.click(); } revokeURL() { // requestAnimationFrame makes the browser prepare the file for download // before revoking the URL requestAnimationFrame(() => URL.revokeObjectURL(this.imagedownloader.href)); } } export default DownloadButton;
Change en_US code from "en" to "en-us" for consistency
function randomFrom(array) { return array[Math.floor(Math.random()*array.length)] } function filter_available(item) { return !item.unreleased } var language_map = { "en_US": "en-us", "fr_FR": "fr", "ja_JP": "ja", "fr_CA": "fr-ca", "es_ES": "es", "es_MX": "es-mx" } String.prototype.format = function(scope) { eval(Object.keys(scope).map( function(x) { return "var " + x + "=scope." + x }).join(";")); return this.replace(/{(.+?)}/g, function($0, $1) { return eval($1); }) }; angular.module('splatApp').util = function($scope, $sce) { // this only works when each language is moved to a directory setup like above (ie in distribution on loadout.ink) $scope.redirect = function(lang) { var dir = language_map[lang] var URL = window.location.protocol + "//"+ window.location.hostname + "/" + dir + "/" if(window.location.hash) URL += window.location.hash; if (typeof(Storage) !== "undefined") { localStorage.selectedLang = lang; } window.location = URL; } $scope.renderHtml = function(html_code) { return $sce.trustAsHtml(html_code); }; }
function randomFrom(array) { return array[Math.floor(Math.random()*array.length)] } function filter_available(item) { return !item.unreleased } var language_map = { "en_US": "en", "fr_FR": "fr", "ja_JP": "ja", "fr_CA": "fr-ca", "es_ES": "es", "es_MX": "es-mx" } String.prototype.format = function(scope) { eval(Object.keys(scope).map( function(x) { return "var " + x + "=scope." + x }).join(";")); return this.replace(/{(.+?)}/g, function($0, $1) { return eval($1); }) }; angular.module('splatApp').util = function($scope, $sce) { // this only works when each language is moved to a directory setup like above (ie in distribution on loadout.ink) $scope.redirect = function(lang) { var dir = language_map[lang] var URL = window.location.protocol + "//"+ window.location.hostname + "/" + dir + "/" if(window.location.hash) URL += window.location.hash; if (typeof(Storage) !== "undefined") { localStorage.selectedLang = lang; } window.location = URL; } $scope.renderHtml = function(html_code) { return $sce.trustAsHtml(html_code); }; }
Store objects in memory map
package storage import ( "bytes" "errors" "io" ) type Storage struct { data map[string][]byte } func (storage *Storage) CopyObjectToWriter(w io.Writer, bucket string, object string) error { // TODO synchronize access // get object key := bucket + ":" + object if val, ok := storage.data[key]; ok { objectBuffer := bytes.NewBuffer(val) _, err := io.Copy(w, objectBuffer) return err } else { return errors.New("Not Found") } } func (storage *Storage) StoreObject(bucket string, object string, data io.Reader) { key := bucket + ":" + object var bytesBuffer bytes.Buffer if _, ok := io.Copy(&bytesBuffer, data); ok == nil { storage.data[key] = bytesBuffer.Bytes() } } func Start() (chan<- string, <-chan error, *Storage) { ctrlChannel := make(chan string) errorChannel := make(chan error) go start(ctrlChannel, errorChannel) return ctrlChannel, errorChannel, &Storage{ data: make(map[string][]byte), } } func start(ctrlChannel <-chan string, errorChannel chan<- error) { errorChannel <- errors.New("STORAGE MSG") errorChannel <- errors.New("STORAGE MSG") errorChannel <- errors.New("STORAGE MSG") close(errorChannel) }
package storage import ( "bytes" "errors" "io" ) type Storage struct { data map[string][]byte } func (storage *Storage) CopyObjectToWriter(w io.Writer, bucket string, object string) error { // TODO synchronize access // get object key := bucket + ":" + object if val, ok := storage.data[key]; ok { objectBuffer := bytes.NewBuffer(val) _, err := io.Copy(w, objectBuffer) return err } else { return errors.New("Not Found") } } func (storage *Storage) StoreObject(bucket string, object string, data io.Reader) { key := bucket + ":" + object var bytesBuffer bytes.Buffer if _, ok := io.Copy(&bytesBuffer, data); ok == nil { storage.data[key] = bytesBuffer.Bytes() } } func Start() (chan<- string, <-chan error, *Storage) { ctrlChannel := make(chan string) errorChannel := make(chan error) go start(ctrlChannel, errorChannel) return ctrlChannel, errorChannel, &Storage{} } func start(ctrlChannel <-chan string, errorChannel chan<- error) { errorChannel <- errors.New("STORAGE MSG") errorChannel <- errors.New("STORAGE MSG") errorChannel <- errors.New("STORAGE MSG") close(errorChannel) }
FIX language of privacy statement
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH (http://www.compassion.ch) # @author: Emanuel Cino <ecino@compassion.ch> # @author: Théo Nikles <theo.nikles@gmail.com> # # The licence is in the file __manifest__.py # ############################################################################## from ..controllers.mobile_app_controller import _get_lang from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, **params): lang = _get_lang(self, params) return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=lang) .sudo().search([], limit=1).text}
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH (http://www.compassion.ch) # @author: Emanuel Cino <ecino@compassion.ch> # @author: Théo Nikles <theo.nikles@gmail.com> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, language, **params): return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=language) .sudo().search([], limit=1).text}
Fix language when the device has been rotated (Language)
package net.somethingdreadful.MAL; import android.content.res.Configuration; import org.holoeverywhere.ThemeManager; import org.holoeverywhere.app.Application; import java.util.Locale; public class Theme extends Application { Locale locale; @Override public void onCreate() { super.onCreate(); PrefManager Prefs = new PrefManager(getApplicationContext()); locale = Prefs.getLocale(); // apply it until the app remains cached Locale.setDefault(locale); Configuration newConfig = new Configuration(); newConfig.locale = locale; getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // apply it until the app remains cached Locale.setDefault(locale); Configuration Config = new Configuration(); Config.locale = locale; getBaseContext().getResources().updateConfiguration(Config, getBaseContext().getResources().getDisplayMetrics()); } static { ThemeManager.setDefaultTheme(ThemeManager.MIXED); } }
package net.somethingdreadful.MAL; import android.content.res.Configuration; import org.holoeverywhere.ThemeManager; import org.holoeverywhere.app.Application; import java.util.Locale; public class Theme extends Application { @Override public void onCreate() { super.onCreate(); PrefManager Prefs = new PrefManager(getApplicationContext()); Locale locale = Prefs.getLocale(); // apply it until the app remains cached Locale.setDefault(locale); Configuration newConfig = new Configuration(); newConfig.locale = locale; getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); } static { ThemeManager.setDefaultTheme(ThemeManager.MIXED); } }
Add spec to test the return type of toLower()
describe('hasVowels()', function() { it('should always return a boolean', function() { expect('example string'.hasVowels()).toEqual(jasmine.any(Boolean)); }); it('should return true if string has vowels', function() { expect('oreofe'.hasVowels()).toBe(true); expect(('AnDeLa').hasVowels()).toBe(true); }); it('should return false if string has no vowels', function() { expect('why'.hasVowels()).toBe(false); expect(('twyndyllyngs').hasVowels()).toBe(false); }); }); describe('toUpper()', function() { it('should always return a string', function() { expect('example string'.toUpper()).toEqual(jasmine.any(String)); }); it('should return an upper case of the calling string', function() { expect('upper case'.toUpper()).toBe('UPPER CASE'); expect('camelCase'.toUpper()).toBe('CAMELCASE'); expect('MiXeD cAsE'.toUpper()).toBe('MIXED CASE'); }); }); describe('toLower()', function() { it('should return a string', function() { expect('example string'.toLower()).toEqual(jasmine.any(String)); }); });
describe('hasVowels()', function() { it('should always return a boolean', function() { expect('example string'.hasVowels()).toEqual(jasmine.any(Boolean)); }); it('should return true if string has vowels', function() { expect('oreofe'.hasVowels()).toBe(true); expect(('AnDeLa').hasVowels()).toBe(true); }); it('should return false if string has no vowels', function() { expect('why'.hasVowels()).toBe(false); expect(('twyndyllyngs').hasVowels()).toBe(false); }); }); describe('toUpper()', function() { it('should always return a string', function() { expect('example string'.toUpper()).toEqual(jasmine.any(String)); }); it('should return an upper case of the calling string', function() { expect('upper case'.toUpper()).toBe('UPPER CASE'); expect('camelCase'.toUpper()).toBe('CAMELCASE'); expect('MiXeD cAsE'.toUpper()).toBe('MIXED CASE'); }); });
Add method to determine if a computer is "mostly on" This means it is in the process of turning on, is on or is shutting down: basically anything which hasn't been fully stopped.
package org.squiddev.cctweaks.lua.patch; import dan200.computercraft.core.computer.Computer; import dan200.computercraft.core.computer.IComputerEnvironment; import dan200.computercraft.core.lua.ILuaMachine; import dan200.computercraft.core.terminal.Terminal; import org.squiddev.patcher.visitors.MergeVisitor; public class Computer_Patch extends Computer { @MergeVisitor.Stub private State m_state; @MergeVisitor.Stub private ILuaMachine m_machine; @MergeVisitor.Stub public Computer_Patch(IComputerEnvironment environment, Terminal terminal, int id) { super(environment, terminal, id); } public void abort(boolean hard) { synchronized (this) { if (m_state != State.Off && m_machine != null) { if (hard) { m_machine.hardAbort("Too long without yielding"); } else { m_machine.softAbort("Too long without yielding"); } } } } public boolean isMostlyOn() { synchronized (this) { return m_state != State.Off && m_machine != null; } } @MergeVisitor.Stub private enum State { Off, Starting, Running, Stopping, } }
package org.squiddev.cctweaks.lua.patch; import dan200.computercraft.core.computer.Computer; import dan200.computercraft.core.computer.IComputerEnvironment; import dan200.computercraft.core.lua.ILuaMachine; import dan200.computercraft.core.terminal.Terminal; import org.squiddev.patcher.visitors.MergeVisitor; public class Computer_Patch extends Computer { @MergeVisitor.Stub private State m_state; @MergeVisitor.Stub private ILuaMachine m_machine; @MergeVisitor.Stub public Computer_Patch(IComputerEnvironment environment, Terminal terminal, int id) { super(environment, terminal, id); } public void abort(boolean hard) { synchronized (this) { if (m_state != State.Off && m_machine != null) { if (hard) { m_machine.hardAbort("Too long without yielding"); } else { m_machine.softAbort("Too long without yielding"); } } } } @MergeVisitor.Stub private static enum State { Off, Starting, Running, Stopping; private State() { } } }
Use the system default LAF.
package gui; import gui.window.listener.GraphyWindowListener; import java.awt.BorderLayout; import javax.swing.*; public class MainWindow extends JFrame { private static MainWindow instance = null; public static MainWindow get_instance() { if (instance == null) { instance = new MainWindow(); } return instance; } private MainWindow() { super(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { e.printStackTrace(); } this.setTitle("Graphy"); this.setSize(1000, 600); this.setLocationRelativeTo(null); this.setJMenuBar(new MenuBar()); this.add(new TopPanel(), BorderLayout.NORTH); this.add(new RightPanel(), BorderLayout.EAST); this.add(new BottomPanel(800, 600), BorderLayout.SOUTH); this.add(new LeftPanel(), BorderLayout.WEST); this.add(new CenterPanel(), BorderLayout.CENTER); this.setVisible(true); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); ImageIcon img = new ImageIcon("images/Logo.png"); this.setIconImage(img.getImage()); addWindowListener(new GraphyWindowListener()); } }
package gui; import gui.window.listener.GraphyWindowListener; import java.awt.BorderLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; public class MainWindow extends JFrame { private static MainWindow instance = null; public static MainWindow get_instance() { if (instance == null) { instance = new MainWindow(); } return instance; } private MainWindow() { super("Graphy"); this.setSize(1000, 600); this.setLocationRelativeTo(null); this.setJMenuBar(new MenuBar()); this.add(new TopPanel(), BorderLayout.NORTH); this.add(new RightPanel(), BorderLayout.EAST); this.add(new BottomPanel(800, 600), BorderLayout.SOUTH); this.add(new LeftPanel(), BorderLayout.WEST); this.add(new CenterPanel(), BorderLayout.CENTER); this.setVisible(true); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); ImageIcon img = new ImageIcon("images/Logo.png"); this.setIconImage(img.getImage()); addWindowListener(new GraphyWindowListener()); } }
Allow event handlers to be passed in
var $soloModal = null // Used when allowMultiple = false. // The public API. Modal = { allowMultiple: false, show: function(templateName, data, options){ if($soloModal == null || this.allowMultiple){ var parentNode = document.body var view = Blaze.renderWithData(Template[templateName], data, parentNode) var domRange = view._domrange // TODO: Don't violate against the public API. var $modal = domRange.$('.modal') $modal.on('shown.bs.modal', function(event){ $modal.find('[autofocus]').focus() }) $modal.on('hidden.bs.modal', function(event){ Blaze.remove(view) $soloModal = null }) if (options && options.events) { Object.keys(options.events).forEach(function(eventName) { $modal.on(eventName, options.events[eventName]); }); } $soloModal = $modal $modal.modal(options) } }, hide: function(/* optional */ template){ if(template instanceof Blaze.TemplateInstance){ template.$('.modal').modal('hide') }else if($soloModal != null){ $soloModal.modal('hide') } } }
var $soloModal = null // Used when allowMultiple = false. // The public API. Modal = { allowMultiple: false, show: function(templateName, data, options){ if($soloModal == null || this.allowMultiple){ var parentNode = document.body var view = Blaze.renderWithData(Template[templateName], data, parentNode) var domRange = view._domrange // TODO: Don't violate against the public API. var $modal = domRange.$('.modal') $modal.on('shown.bs.modal', function(event){ $modal.find('[autofocus]').focus() }) $modal.on('hidden.bs.modal', function(event){ Blaze.remove(view) $soloModal = null }) $soloModal = $modal $modal.modal(options) } }, hide: function(/* optional */ template){ if(template instanceof Blaze.TemplateInstance){ template.$('.modal').modal('hide') }else if($soloModal != null){ $soloModal.modal('hide') } } }
GS-8654: Add machine isolation API shorter key svn path=/trunk/openspaces/; revision=83620 Former-commit-id: 2bab1678ffd82133a8e8506c17b9d505eb44706b
package org.openspaces.admin.internal.pu.elastic; import java.util.Map; /** * @author Moran Avigdor * @since 8.0.1 */ public class ElasticMachineIsolationConfig { private static final String ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY = "elastic-machine-isolation-sharing-id"; private final Map<String, String> properties; public ElasticMachineIsolationConfig(Map<String, String> properties) { this.properties = properties; } public boolean isDedicatedIsolation() { return (getSharingId() == null); } public boolean isSharedIsolation() { return (getSharingId() != null); } public String getSharingId() { return properties.get(ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY); } public void setSharingId(String sharingId) { properties.put(ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY, sharingId); } }
package org.openspaces.admin.internal.pu.elastic; import java.util.Map; /** * @author Moran Avigdor * @since 8.0.1 */ public class ElasticMachineIsolationConfig { private static final String ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY = "elastic-machine-provisioning-isolation-sharing-id"; private final Map<String, String> properties; public ElasticMachineIsolationConfig(Map<String, String> properties) { this.properties = properties; } public boolean isDedicatedIsolation() { return (getSharingId() == null); } public boolean isSharedIsolation() { return (getSharingId() != null); } public String getSharingId() { return properties.get(ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY); } public void setSharingId(String sharingId) { properties.put(ELASTIC_MACHINE_ISOLATION_SHARING_ID_KEY, sharingId); } }
Add missing unit test for auth_hdr.
var auth_hdr = require('../lib/auth_header') describe('Parsing Auth Header field-value', function() { it('Should handle single space separated values', function() { var res = auth_hdr.parse("SCHEME VALUE"); expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); }); it('Should handle CRLF separator', function() { var res = auth_hdr.parse("SCHEME\nVALUE"); expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); }); it('Should handle malformed authentication headers with no scheme', function() { var res = auth_hdr.parse("malformed"); expect(res).to.not.be.ok; }); it('Should return null when the auth header is not a string', function() { var res = auth_hdr.parse({}); expect(res).to.be.null; }); });
var auth_hdr = require('../lib/auth_header') describe('Parsing Auth Header field-value', function() { it('Should handle single space separated values', function() { var res = auth_hdr.parse("SCHEME VALUE"); expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); }); it('Should handle CRLF separator', function() { var res = auth_hdr.parse("SCHEME\nVALUE"); expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"}); }); it('Should handle malformed authentication headers with no scheme', function() { var res = auth_hdr.parse("malformed"); expect(res).to.not.be.ok; }); });
Call init to add blocks.
package com.pseudo_sudo.openstorage; import com.pseudo_sudo.openstorage.configuration.ConfigurationController; import com.pseudo_sudo.openstorage.init.ModBlocks; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid=OpenStorage.ID, name=OpenStorage.NAME, version=OpenStorage.VERSION) public class OpenStorage { public static final String ID = "OpenStorage"; public static final String ID_LOWER = ID.toLowerCase(); public static final String NAME = "OpenStorage"; public static final String VERSION = "1.7.10-0.1"; private ConfigurationController configurationController; @Mod.Instance(OpenStorage.ID) public static OpenStorage instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { this.configurationController = new ConfigurationController(event.getSuggestedConfigurationFile()); ModBlocks.init(); } }
package com.pseudo_sudo.openstorage; import com.pseudo_sudo.openstorage.configuration.ConfigurationController; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid=OpenStorage.ID, name=OpenStorage.NAME, version=OpenStorage.VERSION) public class OpenStorage { public static final String ID = "OpenStorage"; public static final String ID_LOWER = ID.toLowerCase(); public static final String NAME = "OpenStorage"; public static final String VERSION = "1.7.10-0.1"; private ConfigurationController configurationController; @Mod.Instance(OpenStorage.ID) public static OpenStorage instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { this.configurationController = new ConfigurationController(event.getSuggestedConfigurationFile()); } }
Fix crash when post's user has been deleted
<?php $discussion = $document->data; $postsCount = count($discussion->relationships->posts->data); ?> <div class="container"> <h2>{{ $discussion->attributes->title }}</h2> <div> @foreach ($posts as $post) <div> <?php $user = ! empty($post->relationships->user->data) ? $getResource($post->relationships->user->data) : null; ?> <h3>{{ $user ? $user->attributes->username : $translator->trans('core.lib.username.deleted_text') }}</h3> <div class="Post-body"> {!! $post->attributes->contentHtml !!} </div> </div> <hr> @endforeach </div> @if ($page > 1) <a href="{{ $url(['page' => $page - 1]) }}">&laquo; {{ $translator->trans('core.views.discussion.previous_page_button') }}</a> @endif @if ($page < $postsCount / 20) <a href="{{ $url(['page' => $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} &raquo;</a> @endif </div>
<?php $discussion = $document->data; $postsCount = count($discussion->relationships->posts->data); ?> <div class="container"> <h2>{{ $discussion->attributes->title }}</h2> <div> @foreach ($posts as $post) <div> <?php $user = $getResource($post->relationships->user->data); ?> <h3>{{ $user ? $user->attributes->username : $translator->trans('core.lib.username.deleted_text') }}</h3> <div class="Post-body"> {!! $post->attributes->contentHtml !!} </div> </div> <hr> @endforeach </div> @if ($page > 1) <a href="{{ $url(['page' => $page - 1]) }}">&laquo; {{ $translator->trans('core.views.discussion.previous_page_button') }}</a> @endif @if ($page < $postsCount / 20) <a href="{{ $url(['page' => $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} &raquo;</a> @endif </div>
Move MR and Pipelines to 1.9.15.0 - Slight tweaks to requirements.txt for pipeline to add GCS Client as a dep. Revision created by MOE tool push_codebase. MOE_MIGRATION=7173
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.15.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.15", "GoogleAppEnginePipeline >= 1.9.15", "Graphy >= 1.0.0", "simplejson >= 3.6.5", "mock >= 1.0.1", "mox >= 0.5.3", ] )
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.5.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.5", "GoogleAppEnginePipeline >= 1.9.5.1" "Graphy >= 1.0.0", "simplejson >= 3.6.5", "mock >= 1.0.1", "mox >= 0.5.3", ] )
Raise exceptions rather than catching
import pandas import traceback import typing def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame: def get_frames(): for file in file_iterator: df = processor(file) yield (df .assign(Source=getattr(file, 'name', None), SubjectID=getattr(file, 'cpgintegrate_subject_id', None), FileSubjectID=df.index if df.index.name else None)) return pandas.DataFrame(pandas.concat((frame for frame in get_frames()))).set_index("SubjectID")
import pandas import traceback import typing def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame: def get_frames(): for file in file_iterator: try: df = processor(file) except Exception: df = pandas.DataFrame({"error": [traceback.format_exc()]}) yield (df .assign(Source=getattr(file, 'name', None), SubjectID=getattr(file, 'cpgintegrate_subject_id', None), FileSubjectID=df.index if df.index.name else None)) return pandas.DataFrame(pandas.concat((frame for frame in get_frames()))).set_index("SubjectID")
Change the order of component info tabs to be shown - Nunjucks - Ruby - HTML - Context
'use strict' const path = require('path') /* Fractal theme ----------------------------------------------------------------------------- */ // Require the mandelbrot theme module const mandelbrot = require('@frctl/mandelbrot') // Configure a custom theme const customTheme = mandelbrot({ // Mandelbrot offers a pre-defined set of colour ‘skins’ that you can apply to the UI for quick and easy customisation 'skin': 'black', // The nav sections that should show up in the sidebar (and in which order) 'nav': [ 'docs', 'components' ], // The component info panels that should be displayed in the component browser (and in which order the tabs should be displayed) 'panels': [ 'nunjucks', 'ruby', 'html', 'context' ], // The URL of a stylesheet to apply the to the UI styles: [ 'default', // link to the default mandelbrot stylesheet '/theme/govuk/css/fractal-govuk-theme.css' // override with a custom stylesheet ], // Virtual path prefix for the theme’s static assets. The value of this is prepended to the generated theme static asset URLs. 'static': { 'mount': 'theme' } }) // Specify a template directory to override any view templates customTheme.addLoadPath(path.join(__dirname, 'views')) // Specify the static assets directory that contains the custom stylesheet customTheme.addStatic(path.join(__dirname, 'assets'), 'theme/govuk') // Export the customised theme instance so it can be used in Fractal projects module.exports = customTheme
'use strict' const path = require('path') /* Fractal theme ----------------------------------------------------------------------------- */ // Require the mandelbrot theme module const mandelbrot = require('@frctl/mandelbrot') // Configure a custom theme const customTheme = mandelbrot({ // Mandelbrot offers a pre-defined set of colour ‘skins’ that you can apply to the UI for quick and easy customisation 'skin': 'black', // The nav sections that should show up in the sidebar (and in which order) 'nav': [ 'docs', 'components' ], // The component info panels that should be displayed in the component browser (and in which order the tabs should be displayed) 'panels': [ 'notes', 'html', 'view', 'context', 'resources', 'info' ], // The URL of a stylesheet to apply the to the UI styles: [ 'default', // link to the default mandelbrot stylesheet '/theme/govuk/css/fractal-govuk-theme.css' // override with a custom stylesheet ], // Virtual path prefix for the theme’s static assets. The value of this is prepended to the generated theme static asset URLs. 'static': { 'mount': 'theme' } }) // Specify a template directory to override any view templates customTheme.addLoadPath(path.join(__dirname, 'views')) // Specify the static assets directory that contains the custom stylesheet customTheme.addStatic(path.join(__dirname, 'assets'), 'theme/govuk') // Export the customised theme instance so it can be used in Fractal projects module.exports = customTheme
Fix bug with comment POST (created_date was required)
from .models import Comment from .models import Motel from .models import Town from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False) class Meta: model = Comment fields = ('id', 'motel', 'body', 'ranking', 'created_date') class MotelListSerializer(serializers.ModelSerializer): class Meta: model = Motel fields = ('id', 'name', 'town', 'latitude', 'longitude', 'ranking', 'telephone', 'website', 'description') class MotelSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True) class Meta: model = Motel fields = ('id', 'name', 'town', 'latitude', 'longitude','ranking','telephone', 'website','description', 'comments') class TownSerializer(serializers.ModelSerializer): class Meta: model = Town fields = ('name', 'latitude', 'longitude')
from .models import Comment from .models import Motel from .models import Town from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M') class Meta: model = Comment fields = ('id', 'motel', 'body', 'ranking', 'created_date') class MotelListSerializer(serializers.ModelSerializer): class Meta: model = Motel fields = ('id', 'name', 'town', 'latitude', 'longitude', 'ranking', 'telephone', 'website', 'description') class MotelSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True) class Meta: model = Motel fields = ('id', 'name', 'town', 'latitude', 'longitude','ranking','telephone', 'website','description', 'comments') class TownSerializer(serializers.ModelSerializer): class Meta: model = Town fields = ('name', 'latitude', 'longitude')
Remove import of fixed-data-table javascript library
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require turbolinks //= require moment //= require react //= require react_ujs //= require components //= require accountingjs //= require bootstrap-sprockets //= require bootstrap-datetimepicker //= require bootstrap-guards //= require cocoon //= require select2 //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require turbolinks //= require moment //= require react //= require react_ujs //= require fixed-data-table //= require components //= require accountingjs //= require bootstrap-sprockets //= require bootstrap-datetimepicker //= require bootstrap-guards //= require cocoon //= require select2 //= require_tree .
Add gulp-connect to serve project
var gulp = require('gulp'); var gutil = require('gulp-util'); var notify = require('gulp-notify'); var less = require('gulp-less'); var autoprefix = require('gulp-autoprefixer'); var minifyCSS = require('gulp-minify-css'); var connect = require('gulp-connect'); //Pre-compiled directory var lessDir = 'src/less'; //Compiled directory var targetCSSDir = 'css/'; gulp.task('css', function () { return gulp.src(lessDir + '/*.less') .pipe(less({ style: 'compressed' }).on('error', gutil.log)) .pipe(gulp.dest(targetCSSDir)) .pipe(notify('CSS minified')) }); gulp.task('watch', function () { gulp.watch(lessDir + '/*.less', ['css']); }); gulp.task('connect', function() { connect.server({ root: '.', livereload: true }) }); gulp.task('default', ['css', 'watch', 'connect']);
var gulp = require('gulp'); var gutil = require('gulp-util'); var notify = require('gulp-notify'); var less = require('gulp-less'); var autoprefix = require('gulp-autoprefixer'); var minifyCSS = require('gulp-minify-css') //Pre-compiled directory var lessDir = 'src/less'; //Compiled directory var targetCSSDir = 'css/'; gulp.task('css', function () { return gulp.src(lessDir + '/*.less') .pipe(less({ style: 'compressed' }).on('error', gutil.log)) .pipe(gulp.dest(targetCSSDir)) .pipe(notify('CSS minified')) }); gulp.task('watch', function () { gulp.watch(lessDir + '/*.less', ['css']); }); gulp.task('default', ['css', 'watch']);
Enhancement: Handle module reload exceptions gracefully In some rare cases if the internal module structure has changed the 'reload' module can't recover all modules and will fail with ImportError. This is the situation we need to advice a restart of Sublime Text.
# -*- coding: utf-8 -*- """Load and Unload all GitGutter modules. This module exports __all__ modules, which Sublime Text needs to know about. The list of __all__ exported symbols is defined in modules/__init__.py. """ try: from .modules import * except ValueError: from modules import * except ImportError: # Failed to import at least one module. This can happen after upgrade due # to internal structure changes. import sublime sublime.message_dialog( "GitGutter failed to reload some of its modules.\n" "Please restart Sublime Text!") def plugin_loaded(): """Plugin loaded callback.""" try: # Reload 'modules' once after upgrading to ensure GitGutter is ready # for use instantly again. (Works with ST3 and python3 only!) from package_control import events if events.post_upgrade(__package__): from .modules.reload import reload_package reload_package(__package__) except ImportError: # Fail silently if package control isn't installed. pass
# -*- coding: utf-8 -*- """Load and Unload all GitGutter modules. This module exports __all__ modules, which Sublime Text needs to know about. The list of __all__ exported symbols is defined in modules/__init__.py. """ try: from .modules import * except ValueError: from modules import * def plugin_loaded(): """Plugin loaded callback.""" try: # Reload 'modules' once after upgrading to ensure GitGutter is ready # for use instantly again. (Works with ST3 and python3 only!) from package_control import events if events.post_upgrade(__package__): from .modules.reload import reload_package reload_package(__package__) except ImportError: # Fail silently if package control isn't installed. pass
Fix for querying for player by username
import isString from 'lodash/isString'; const ENDPOINT_PREFIX = 'players'; export default (http, options, parser) => { async function getByName(playerName) { if (!playerName) { return new Error('Expected required playerName. Usage: .getByName(playerName)'); } if (!isString(playerName)) { return new Error('Expected a string for playerName'); } const endpoint = `${ENDPOINT_PREFIX}`; const defaults = { filter: { playerName: '' } }; const query = { ...defaults, filter: { playerName: playerName } }; const body = await http.execute('GET', `${ENDPOINT_PREFIX}`, query); return parser('player', body); } async function getById(playerId) { if (!playerId) { return new Error('Expected required playerId. Usage: .single(playerId)'); } if (!isString(playerId)) { return new Error('Expected a string for playerId'); } const endpoint = `${ENDPOINT_PREFIX}/${playerId}`; const body = await http.execute('GET', endpoint); return parser('player', body); } return { getByName, getById }; }
import isString from 'lodash/isString'; const ENDPOINT_PREFIX = 'players'; export default (http, options, parser) => { async function getByName(playerName) { console.log('Heads up! This endpoint currently does not work, it is here because it is listed in the API docs.'); if (!playerName) { return new Error('Expected required playerName. Usage: .getByName(playerName)'); } if (!isString(playerName)) { return new Error('Expected a string for playerName'); } const endpoint = `${ENDPOINT_PREFIX}`; const defaults = { filter: { playerNames: '' } }; const query = { ...defaults, filter: { playerNames: playerName } }; const body = await http.execute('GET', `${ENDPOINT_PREFIX}`, query); return parser('player', body); } async function getById(playerId) { if (!playerId) { return new Error('Expected required playerId. Usage: .single(playerId)'); } if (!isString(playerId)) { return new Error('Expected a string for playerId'); } const endpoint = `${ENDPOINT_PREFIX}/${playerId}`; const body = await http.execute('GET', endpoint); return parser('player', body); } return { getByName, getById }; }
Add script file name to stack traces
'use strict'; var extend = require('extend'); var repl = require('repl') , vm = require('vm') , fs = require('fs'); /** * Start the REPL and expose variables in `context`. * * @arg {Object} context * @return {Repl} */ var replWith = function (context) { var r = repl.start({ prompt: '> ', useGlobal: true }); extend(r.context, context); return r; }; /** * Start the REPL and expose top-level definitions in `filename`. * * @arg {string} filename * @arg {function(Error, Repl)} [cb] */ module.exports = function (filename, cb) { cb = cb || function () {}; fs.readFile(filename, { encoding: 'utf8' }, function (err, script) { if (err) return cb(err); var sandbox = {}; vm.runInNewContext(script, sandbox, filename); var repl = replWith(sandbox); return cb(null, repl); }); };
'use strict'; var extend = require('extend'); var repl = require('repl') , vm = require('vm') , fs = require('fs'); /** * Start the REPL and expose variables in `context`. * * @arg {Object} context * @return {Repl} */ var replWith = function (context) { var r = repl.start({ prompt: '> ', useGlobal: true }); extend(r.context, context); return r; }; /** * Start the REPL and expose top-level definitions in `filename`. * * @arg {string} filename * @arg {function(Error, Repl)} [cb] */ module.exports = function (filename, cb) { cb = cb || function () {}; fs.readFile(filename, { encoding: 'utf8' }, function (err, script) { if (err) return cb(err); var sandbox = {}; vm.runInNewContext(script, sandbox); var repl = replWith(sandbox); return cb(null, repl); }); };
Support string value for color.
import {makeInner, normalizeToArray} from '../../util/model'; var inner = makeInner(); export default { clearColorPalette: function () { inner(this).colorIdx = 0; inner(this).colorNameMap = {}; }, getColorFromPalette: function (name, scope) { scope = scope || this; var scopeFields = inner(scope); var colorIdx = scopeFields.colorIdx || 0; var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype. if (colorNameMap.hasOwnProperty(name)) { return colorNameMap[name]; } var colorPalette = normalizeToArray(this.get('color', true)); if (!colorPalette.length) { return; } var color = colorPalette[colorIdx]; if (name) { colorNameMap[name] = color; } scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length; return color; } };
import {makeInner} from '../../util/model'; var inner = makeInner(); export default { clearColorPalette: function () { inner(this).colorIdx = 0; inner(this).colorNameMap = {}; }, getColorFromPalette: function (name, scope) { scope = scope || this; var scopeFields = inner(scope); var colorIdx = scopeFields.colorIdx || 0; var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype. if (colorNameMap.hasOwnProperty(name)) { return colorNameMap[name]; } var colorPalette = this.get('color', true) || []; if (!colorPalette.length) { return; } var color = colorPalette[colorIdx]; if (name) { colorNameMap[name] = color; } scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length; return color; } };
Remove default values from channels columns
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMusicSettings extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('music_settings', function (Blueprint $table) { $table->string('id')->primary(); $table->boolean('enabled')->default(true); $table->enum('mode', ['OFF','WHITELIST', 'BLACKLIST'])->default('OFF'); $table->text('channels')->nullable(); $table->text('blacklist_songs')->nullable(); $table->integer('max_queue_length')->default(-1); $table->integer('max_song_length')->default(-1); $table->integer('skip_cooldown')->default(0); $table->integer('skip_timer')->default(30); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('music_settings'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMusicSettings extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('music_settings', function (Blueprint $table) { $table->string('id')->primary(); $table->boolean('enabled')->default(true); $table->enum('mode', ['OFF','WHITELIST', 'BLACKLIST'])->default('OFF'); $table->text('channels')->default(''); $table->text('blacklist_songs')->default('')->nullable(); $table->integer('max_queue_length')->default(-1); $table->integer('max_song_length')->default(-1); $table->integer('skip_cooldown')->default(0); $table->integer('skip_timer')->default(30); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('music_settings'); } }
Fix scaling issue when a retina-capable device resizes. Will now correctly scale.
module.exports = function($, window, errorHandler) { var Multigraph = require('../../core/multigraph.js')($), Point = require('../../math/point.js'); if (typeof(Multigraph.registerResizeEvents)==="function") { return Multigraph; } Multigraph.respondsTo("registerResizeEvents", function (target) { var multigraph = this; var container = $(this.div()); var c = $(target); // select canvas in multigraph div $(window).resize(respondGraph); function respondGraph() { c.attr("width", container.width() * window.devicePixelRatio); c.attr("height", container.height() * window.devicePixelRatio); c.css("width", container.width()); c.css("height", container.height()); multigraph.init(); } }); return Multigraph; };
module.exports = function($, window, errorHandler) { var Multigraph = require('../../core/multigraph.js')($), Point = require('../../math/point.js'); if (typeof(Multigraph.registerResizeEvents)==="function") { return Multigraph; } Multigraph.respondsTo("registerResizeEvents", function (target) { var multigraph = this; var container = $(this.div()); var c = $(target); // select canvas in multigraph div $(window).resize(respondGraph); function respondGraph() { c.attr("width", container.width()); c.attr("height", container.height()); c.css("width", container.width()); c.css("height", container.height()); multigraph.init(); } }); return Multigraph; };
Add back 3.5, 3.6 classifiers
#!/usr/bin/env python from setuptools import setup, find_packages try: with open('VERSION.txt', 'r') as v: version = v.read().strip() except FileNotFoundError: version = '0.0.0.dev0' with open('DESCRIPTION', 'r') as d: long_description = d.read() setup( name='tukio', description='An event-based workflow library built around asyncio', long_description=long_description, url='https://github.com/surycat/tukio', author='Enovacom Surycat', author_email='rand@surycat.com', version=version, packages=find_packages(exclude=['tests']), license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: AsyncIO' 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', ], )
#!/usr/bin/env python from setuptools import setup, find_packages try: with open('VERSION.txt', 'r') as v: version = v.read().strip() except FileNotFoundError: version = '0.0.0.dev0' with open('DESCRIPTION', 'r') as d: long_description = d.read() setup( name='tukio', description='An event-based workflow library built around asyncio', long_description=long_description, url='https://github.com/surycat/tukio', author='Enovacom Surycat', author_email='rand@surycat.com', version=version, packages=find_packages(exclude=['tests']), license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: AsyncIO', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', ], )
Use dict not if/else, add exceptions
from __future__ import absolute_import import random from .jokes_en import jokes as jokes_en from .jokes_de import jokes as jokes_de from .jokes_es import jokes as jokes_es all_jokes = { 'en': jokes_en, 'de': jokes_de, 'es': jokes_es, } class LanguageNotFoundError(Exception): pass class CategoryNotFoundError(Exception): pass def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language in all_jokes: jokes = all_jokes[language] else: raise LanguageNotFoundError('No such language %s' % language) if category in jokes: jokes = jokes[category] return random.choice(jokes) else: raise CategoryNotFound('No such category %s' % category)
from __future__ import absolute_import import random import importlib def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language == 'en': from .jokes_en import jokes elif language == 'de': from .jokes_de import jokes elif language == 'es': from .jokes_es import jokes try: jokes = jokes[category] except: return 'Could not get the joke. Choose another category.' else: return random.choice(jokes)
Fix docstrings for JsonLdApi to avoid confusion See #4 for more details
// Copyright 2015 Stanislav Nazarenko // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ld // JsonLdApi exposes internal functions used by JsonLdProcessor. // See http://www.w3.org/TR/json-ld-api/ for detailed description of // underlying algorithms // // Warning: using this interface directly is highly discouraged. Please use JsonLdProcessor instead. type JsonLdApi struct { } // NewJsonLdApi creates a new instance of JsonLdApi. func NewJsonLdApi() *JsonLdApi { return &JsonLdApi{} }
// Copyright 2015 Stanislav Nazarenko // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ld // JsonLdApi is the main interface to JSON-LD API. // See http://www.w3.org/TR/json-ld-api/ for detailed description of this interface. type JsonLdApi struct { } // NewJsonLdApi creates a new instance of JsonLdApi and initialises it // with the given JsonLdOptions structure. func NewJsonLdApi() *JsonLdApi { return &JsonLdApi{} }
Make the embed widgets command return the full widget state schema (with version number), instead of just the widget state.
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. "use strict"; var save_state = function() { return new Promise(function(resolve) { requirejs(["base/js/namespace"], function(Jupyter) { return Jupyter.WidgetManager._managers[0].get_state({ 'drop_defaults': true }).then(function(state) { var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(state, null, " ")); var a = document.createElement("a"); a.download = "widget_state.json"; a.href = "data:" + data; a.click(); }); }); }); }; var action = { help: 'Download the widget state as a JSON file', icon: 'fa-sliders', help_index : 'zz', handler : save_state }; var action_name = 'save-widget-state'; var prefix = 'widgets'; requirejs(["base/js/namespace"], function(Jupyter) { Jupyter.notebook.keyboard_manager.actions.register(action, action_name, prefix); }); module.exports = {action: action};
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. "use strict"; var save_state = function() { return new Promise(function(resolve) { requirejs(["base/js/namespace"], function(Jupyter) { return Jupyter.WidgetManager._managers[0].get_state({ 'drop_defaults': true }).then(function(state) { var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(state.state, null, " ")); var a = document.createElement("a"); a.download = "widget_state.json"; a.href = "data:" + data; a.click(); }); }); }); }; var action = { help: 'Download the widget state as a JSON file', icon: 'fa-sliders', help_index : 'zz', handler : save_state }; var action_name = 'save-widget-state'; var prefix = 'widgets'; requirejs(["base/js/namespace"], function(Jupyter) { Jupyter.notebook.keyboard_manager.actions.register(action, action_name, prefix); }); module.exports = {action: action};
Use invoke method like in all other places. Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
package som.interpreter.nodes.dispatch; import som.vm.Universe; import som.vmobjects.SAbstractObject; import som.vmobjects.SInvokable; import som.vmobjects.SSymbol; import com.oracle.truffle.api.frame.VirtualFrame; public final class GenericDispatchNode extends AbstractDispatchWithLookupNode { public GenericDispatchNode(final SSymbol selector, final Universe universe) { super(selector, universe); } @Override public Object executeDispatch( final VirtualFrame frame, final Object[] arguments) { SInvokable method = lookupMethod(arguments[0]); if (method != null) { return method.invoke(arguments); } else { // TODO: perhaps, I should mark this branch with a branch profile as // being unlikely return sendDoesNotUnderstand(arguments); } } private Object sendDoesNotUnderstand(final Object[] arguments) { // TODO: this is all extremely expensive, and could be optimized by // further specialization for #dnu return SAbstractObject.sendDoesNotUnderstand(selector, arguments, universe); } @Override public int lengthOfDispatchChain() { return 1000; } }
package som.interpreter.nodes.dispatch; import som.vm.Universe; import som.vmobjects.SAbstractObject; import som.vmobjects.SInvokable; import som.vmobjects.SSymbol; import com.oracle.truffle.api.frame.VirtualFrame; public final class GenericDispatchNode extends AbstractDispatchWithLookupNode { public GenericDispatchNode(final SSymbol selector, final Universe universe) { super(selector, universe); } @Override public Object executeDispatch( final VirtualFrame frame, final Object[] arguments) { SInvokable method = lookupMethod(arguments[0]); if (method != null) { return method.getCallTarget().call(arguments); } else { // TODO: perhaps, I should mark this branch with a branch profile as // being unlikely return sendDoesNotUnderstand(arguments); } } private Object sendDoesNotUnderstand(final Object[] arguments) { // TODO: this is all extremely expensive, and could be optimized by // further specialization for #dnu return SAbstractObject.sendDoesNotUnderstand(selector, arguments, universe); } @Override public int lengthOfDispatchChain() { return 1000; } }
Use moment at the last minute
var path = require("path"); var _ = require("lodash"); // ----------------------------------------------------------------------------- // Make tags snake case // ----------------------------------------------------------------------------- function cleanTag(tag){ return _.snakeCase(tag); } // Regex used to parse date from file name var dateRegEx = /(\d{4})-(\d{1,2})-(\d{1,2})-(.*)/; // ----------------------------------------------------------------------------- // Use the filename to build a directory structure using the date // ----------------------------------------------------------------------------- function filename2date(filePath){ var result = {}; var basename = path.basename(filePath, '.md'); var match = dateRegEx.exec(basename); if(match) { var year = match[1]; var month = match[2]; var day = match[3]; var basename = match[4]; result.date = month + '-' + day + '-' + year, "MM-DD-YYYY"; result.url = '/' + year + '/' + month + '/' + day + '/' + basename + '.html'; if(!result.title){ result.title = basename.replace(/_/g, ' '); } } return result; } module.exports = { cleanTag: cleanTag, filename2date: filename2date };
var path = require("path"); var _ = require("lodash"); // ----------------------------------------------------------------------------- // Make tags snake case // ----------------------------------------------------------------------------- function cleanTag(tag){ return _.snakeCase(tag); } // Regex used to parse date from file name var dateRegEx = /(\d{4})-(\d{1,2})-(\d{1,2})-(.*)/; // ----------------------------------------------------------------------------- // Use the filename to build a directory structure using the date // ----------------------------------------------------------------------------- function filename2date(filePath){ var result = {}; var basename = path.basename(filePath, '.md'); var match = dateRegEx.exec(basename); if(match) { var year = match[1]; var month = match[2]; var day = match[3]; var basename = match[4]; result.date = moment(month + '-' + day + '-' + year, "MM-DD-YYYY"); result.url = '/' + year + '/' + month + '/' + day + '/' + basename + '.html'; if(!result.title){ result.title = basename.replace(/_/g, ' '); } } return result; } module.exports = { cleanTag: cleanTag, filename2date: filename2date };
Fix MorphingField: polymorphic_identy is already the string we want
from marshmallow.fields import Field class MorphingField(Field): # registry = { # } def __init__(self, many=False, fallback=None, overwrite=None, **metadata): self.many = False self.fallback = fallback or self.FALLBACK self.overwrite = overwrite # Common alternative: # def _obj_to_name(self, obj): # return obj.__class__.__name__ def _obj_to_name(self, obj): return obj.__mapper__.polymorphic_identity def _serialize(self, value, attr, obj): if value is None: return None if self.many: return [self._get_serializer(value).dump(x).data for x in value] return self._get_serializer(value).dump(value).data def _get_serializer(self, obj): name = self._obj_to_name(obj) if self.overwrite: kls = self.overwrite(obj, name) if isinstance(kls, str): name = kls elif callable(kls): return kls() return self.registry.get(name, self.fallback)()
from marshmallow.fields import Field class MorphingField(Field): # registry = { # } def __init__(self, many=False, fallback=None, overwrite=None, **metadata): self.many = False self.fallback = fallback or self.FALLBACK self.overwrite = overwrite # Common alternative: # def _obj_to_name(self, obj): # return obj.__class__.__name__ def _obj_to_name(self, obj): return obj.__mapper__.polymorphic_identity and obj.__mapper__.polymorphic_identity.__class__.__name__ def _serialize(self, value, attr, obj): if value is None: return None if self.many: return [self._get_serializer(value).dump(x).data for x in value] return self._get_serializer(value).dump(value).data def _get_serializer(self, obj): name = self._obj_to_name(obj) if self.overwrite: kls = self.overwrite(obj, name) if isinstance(kls, str): name = kls elif callable(kls): return kls() return self.registry.get(name, self.fallback)()
Rename print_struct to generate_template and use multi_map
#!/usr/bin/env python import json import os from lib.functional import multi_map from engine import types, consts template_dir = os.path.join(os.environ['PORTER'], 'templates') structs = ( (types.new_unit, "Tank", (consts.RED,)), (types.new_attack, "RegularCannon", ()), (types.new_armor, "WeakMetal", ()), (types.new_movement, "Treads", ()), ) def without_trailing_whitespace(string): def remove_trailing_whitespace(line): return line.rstrip() return '\n'.join(map(remove_trailing_whitespace, string.split('\n'))) def generate_template(new_, name, args): with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f: f.write( without_trailing_whitespace( json.dumps( json.loads( repr( new_(name, *args))), indent=4))) def main(): if not os.path.exists(template_dir): os.mkdir(template_dir) multi_map(generate_template, structs) if __name__ == '__main__': main()
#!/usr/bin/env python import json import os from engine import types, consts template_dir = os.path.join(os.environ['PORTER'], 'templates') structs = ( (types.new_unit, "Tank", (consts.RED,)), (types.new_attack, "RegularCannon", ()), (types.new_armor, "WeakMetal", ()), (types.new_movement, "Treads", ()), ) def without_trailing_whitespace(string): def remove_trailing_whitespace(line): return line.rstrip() return '\n'.join(map(remove_trailing_whitespace, string.split('\n'))) def print_struct(args): new_, name, args = args with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f: f.write( without_trailing_whitespace( json.dumps( json.loads( repr( new_(name, *args))), indent=4))) def main(): if not os.path.exists(template_dir): os.mkdir(template_dir) map(print_struct, structs) if __name__ == '__main__': main()
Use UnprovidedSet when converting ember to Box.lots
package org.marsik.elshelves.backend.entities.converters; import org.marsik.elshelves.api.entities.BoxApiModel; import org.marsik.elshelves.backend.entities.Box; import org.marsik.elshelves.backend.entities.IdentifiedEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.UUID; @Service public class EmberToBox extends AbstractEmberToEntity<BoxApiModel, Box> { @Autowired EmberToUser emberToUser; @Autowired EmberToNamedObject emberToNamedObject; public EmberToBox() { super(Box.class); } @Override public Box convert(BoxApiModel object, Box box, int nested, Map<UUID, Object> cache) { emberToNamedObject.convert(object, box, nested, cache); box.setParent(convert(object.getParent(), 1, cache)); if (object.getLots() == null) { box.setLots(new IdentifiedEntity.UnprovidedSet<>()); } if (object.getBoxes() == null) { box.setContains(null); } return box; } }
package org.marsik.elshelves.backend.entities.converters; import org.marsik.elshelves.api.entities.BoxApiModel; import org.marsik.elshelves.backend.entities.Box; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.UUID; @Service public class EmberToBox extends AbstractEmberToEntity<BoxApiModel, Box> { @Autowired EmberToUser emberToUser; @Autowired EmberToNamedObject emberToNamedObject; public EmberToBox() { super(Box.class); } @Override public Box convert(BoxApiModel object, Box box, int nested, Map<UUID, Object> cache) { emberToNamedObject.convert(object, box, nested, cache); box.setParent(convert(object.getParent(), 1, cache)); if (object.getLots() == null) { box.setLots(null); } if (object.getBoxes() == null) { box.setContains(null); } return box; } }
Add integer compatibility with integer
<?php /** * This file is part of Railt package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Railt\Reflection\Standard\Scalars; use Railt\Reflection\Standard\StandardType; /** * The ID standard scalar implementation. * * @see http://facebook.github.io/graphql/#sec-ID */ final class IDType extends StringType implements StandardType { /** * The ID scalar public name constant. * This name will be used in the future as * the type name available for use in our GraphQL schema. */ protected const SCALAR_TYPE_NAME = 'ID'; /** * Short ID scalar public description. */ protected const TYPE_DESCRIPTION = 'The `ID` scalar type represents a unique identifier, often used to ' . 'refetch an object or as key for a cache. The ID type appears in a JSON ' . 'response as a String; however, it is not intended to be human-readable. ' . 'When expected as an input type, any string (such as `"4"`) or integer ' . '(such as `4`) input value will be accepted as an ID.'; /** * @param mixed|string $value * @return bool */ public function isCompatible($value): bool { return \is_string($value) || \is_int($value); } }
<?php /** * This file is part of Railt package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Railt\Reflection\Standard\Scalars; use Railt\Reflection\Standard\StandardType; /** * The ID standard scalar implementation. * * @see http://facebook.github.io/graphql/#sec-ID */ final class IDType extends StringType implements StandardType { /** * The ID scalar public name constant. * This name will be used in the future as * the type name available for use in our GraphQL schema. */ protected const SCALAR_TYPE_NAME = 'ID'; /** * Short ID scalar public description. */ protected const TYPE_DESCRIPTION = 'The `ID` scalar type represents a unique identifier, often used to ' . 'refetch an object or as key for a cache. The ID type appears in a JSON ' . 'response as a String; however, it is not intended to be human-readable. ' . 'When expected as an input type, any string (such as `"4"`) or integer ' . '(such as `4`) input value will be accepted as an ID.'; }
Fix getattr() takes no keyword arguments
from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', {'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } class PageAdmin(FlatPageAdmin): """ Page Admin """ form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin)
from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', default={'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } class PageAdmin(FlatPageAdmin): """ Page Admin """ form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin)
Correct the 'reference' format transform method Currently, the 'reference' format transform method will traversal the metrics list and reconstruct every item of the list to add tenant_id and region info, but new transformed metrics list will use the reference of the local dict variable "transformed_metric", that will lead that all the items of the transformed metrics list be the same value. Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28 Closes-bug: #1439055
# Copyright 2014 Hewlett-Packard # # 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. import copy from oslo_utils import timeutils def transform(metrics, tenant_id, region): transformed_metric = {'metric': {}, 'meta': {'tenantId': tenant_id, 'region': region}, 'creation_time': timeutils.utcnow_ts()} if isinstance(metrics, list): transformed_metrics = [] for metric in metrics: transformed_metric['metric'] = metric transformed_metrics.append(copy.deepcopy(transformed_metric)) return transformed_metrics else: transformed_metric['metric'] = metrics return transformed_metric
# Copyright 2014 Hewlett-Packard # # 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 oslo_utils import timeutils def transform(metrics, tenant_id, region): transformed_metric = {'metric': {}, 'meta': {'tenantId': tenant_id, 'region': region}, 'creation_time': timeutils.utcnow_ts()} if isinstance(metrics, list): transformed_metrics = [] for metric in metrics: transformed_metric['metric'] = metric transformed_metrics.append(transformed_metric) return transformed_metrics else: transformed_metric['metric'] = metrics return transformed_metric
Fix json.loads when context is None Co-authored-by: Pierre Verkest <94ea506e1738fc492d3f7a19e812079abcde2af1@gmail.com>
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import json from odoo.http import request, route from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None, converter=None, **data): report = request.env["ir.actions.report"]._get_report_from_name(reportname) original_context = json.loads(data.get("context", "{}") or "{}") data["context"] = json.dumps( report.with_context(original_context)._get_context() ) return super().report_routes( reportname, docids=docids, converter=converter, **data )
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import json from odoo.http import request, route from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None, converter=None, **data): report = request.env["ir.actions.report"]._get_report_from_name(reportname) original_context = json.loads(data.get("context", "{}")) data["context"] = json.dumps( report.with_context(original_context)._get_context() ) return super().report_routes( reportname, docids=docids, converter=converter, **data )
Enable preventChanges hook to delete fields containing dots.
const existsByDot = require('../common/exists-by-dot'); const deleteByDot = require('../common/delete-by-dot'); const checkContext = require('./check-context'); const errors = require('@feathersjs/errors'); module.exports = function (...fieldNames) { const ifThrow = fieldNames[0]; if (typeof ifThrow === 'string') { console.log('**Deprecated** Use the preventChanges(true, ...fieldNames) syntax instead.'); } else { fieldNames = fieldNames.slice(1); } return context => { checkContext(context, 'before', ['patch'], 'preventChanges'); const data = context.data; fieldNames.forEach(name => { // Delete data['contactPerson.name'] if(data[name]) { delete data[name]; } // Delete data.contactPerson.name if (existsByDot(data, name)) { if (ifThrow) throw new errors.BadRequest(`Field ${name} may not be patched. (preventChanges)`); deleteByDot(data, name); } }); return context; }; };
const existsByDot = require('../common/exists-by-dot'); const deleteByDot = require('../common/delete-by-dot'); const checkContext = require('./check-context'); const errors = require('@feathersjs/errors'); module.exports = function (...fieldNames) { const ifThrow = fieldNames[0]; if (typeof ifThrow === 'string') { console.log('**Deprecated** Use the preventChanges(true, ...fieldNames) syntax instead.'); } else { fieldNames = fieldNames.slice(1); } return context => { checkContext(context, 'before', ['patch'], 'preventChanges'); const data = context.data; fieldNames.forEach(name => { if (existsByDot(data, name)) { if (ifThrow) throw new errors.BadRequest(`Field ${name} may not be patched. (preventChanges)`); deleteByDot(data, name); } }); return context; }; };
Exit unless we're explicitly in a Python3 environment
from setuptools import setup, find_packages from codecs import open from os import path import sys # Exit unless we're in pip3/Python 3 if not sys.version_info[0] == 3: print("\noctohatrack requires a Python 3 environment.\n\nTry `pip3 install` instead") sys.exit(1) here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='octohatrack', version='0.5.1', description='Show _all_ the contributors to a GitHub repository', long_description=long_description, url='https://github.com/labhr/octohatrack', author='Katie McLaughlin', author_email='katie@glasnt.com', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='octohatrack github contributions', install_requires=[ 'requests', 'simplejson', 'gitpython' ], entry_points={ 'console_scripts': [ "octohatrack = octohatrack.__main__:main" ] }, packages=find_packages() )
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='octohatrack', version='0.5.1', description='Show _all_ the contributors to a GitHub repository', long_description=long_description, url='https://github.com/labhr/octohatrack', author='Katie McLaughlin', author_email='katie@glasnt.com', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='octohatrack github contributions', install_requires=[ 'requests', 'simplejson', 'gitpython' ], entry_points={ 'console_scripts': [ "octohatrack = octohatrack.__main__:main" ] }, packages=find_packages() )
Extend the optionset to include ref The ref parameter expects a function which will be given the instance to the rendered component.
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['knockout', 'react', 'react-dom'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('knockout'), require('react'), require('react-dom')); } else { factory(root.ko, root.React, root.ReactDOM); } }(this, function (ko, React, ReactDOM) { ko.bindingHandlers.react = { init: function () { return { controlsDescendantBindings: true }; }, update: function (element, valueAccessor, allBindings) { var options = ko.unwrap(valueAccessor()); if (options && options.component) { var componentInstance = ReactDOM.render( React.createElement(options.component, options.props), element ); if (options.ref) { options.ref(componentInstance); } } } }; }));
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['knockout', 'react', 'react-dom'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('knockout'), require('react'), require('react-dom')); } else { factory(root.ko, root.React, root.ReactDOM); } }(this, function (ko, React, ReactDOM) { ko.bindingHandlers.react = { init: function () { return { controlsDescendantBindings: true }; }, update: function (element, valueAccessor, allBindings) { var options = ko.unwrap(valueAccessor()); if (options && options.component) { var componentInstance = ReactDOM.render( React.createElement(options.component, options.props), element ); } } }; }));
Load latestDistData in main build
import history from '!json!../assets/data/history.json' import metadata from '!json!../assets/data/metadata.json' // Loading latest season in the main bundle itself import latestSeasonData from '!json!../assets/data/season-latest.json' import latestDistData from '!json!../assets/data/distributions/season-latest-nat.json' const seasonDataCtx = require.context( 'file-loader!../assets/data/', false, /^\.\/.*\.json$/ ) const distDataCtx = require.context( 'file-loader!../assets/data/distributions/', false, /^\.\/.*\.json$/ ) const seasonDataUrls = seasonDataCtx.keys().reduce((acc, key) => { if (key.startsWith('./season-')) { // Identifier is like '2013-2014' acc[key.slice(9, -5)] = seasonDataCtx(key) } return acc }, {}) const distDataUrls = distDataCtx.keys().reduce((acc, key) => { if (key.startsWith('./season-')) { // Identifier is like '2013-2014-hhs10' acc[key.slice(9, -5)] = distDataCtx(key) } return acc }, {}) export { seasonDataUrls, distDataUrls, latestSeasonData, latestDistData, history, metadata }
import history from '!json!../assets/data/history.json' import metadata from '!json!../assets/data/metadata.json' // Loading latest season in the main bundle itself import latestSeasonData from '!json!../assets/data/season-latest.json' const seasonDataCtx = require.context( 'file-loader!../assets/data/', false, /^\.\/.*\.json$/ ) const distDataCtx = require.context( 'file-loader!../assets/data/distributions/', false, /^\.\/.*\.json$/ ) const seasonDataUrls = seasonDataCtx.keys().reduce((acc, key) => { if (key.startsWith('./season-')) { // Identifier is like '2013-2014' acc[key.slice(9, -5)] = seasonDataCtx(key) } return acc }, {}) const distDataUrls = distDataCtx.keys().reduce((acc, key) => { if (key.startsWith('./season-')) { // Identifier is like '2013-2014-hhs10' acc[key.slice(9, -5)] = distDataCtx(key) } return acc }, {}) export { seasonDataUrls, distDataUrls, latestSeasonData, history, metadata }
Fix an issue for hostname to be connected
/* global io */ 'use strict'; angular.module('memoApp') .service('memoService', function memoService() { this.socket = io.connect(window.location.protocol + '//' + window.location.hostname); this.watch = function (file) { this.socket.emit('watch', file); }; this.load = function (file, callback) { this.socket.on('memo', function (data) { if (callback) { callback(data); } }); }; this.save = function (file, memo) { this.socket.emit('save', { file: file, memo: memo }); }; this.getDirSplit = function (dir, disableLastItem) { var dirSplit = []; var fullDir = ''; var dirs = dir.split('/'); var length = dirs.length; for (var i = 0; i < length; i++) { var dir = { name: dirs[i] }; if (!disableLastItem || (i !== length - 1)) { dir.link = fullDir + dirs[i]; } dirSplit.push(dir); fullDir += dirs[i] + '/'; } return dirSplit; } });
/* global io */ 'use strict'; angular.module('memoApp') .service('memoService', function memoService() { this.socket = io.connect('http://localhost'); this.watch = function (file) { this.socket.emit('watch', file); }; this.load = function (file, callback) { this.socket.on('memo', function (data) { if (callback) { callback(data); } }); }; this.save = function (file, memo) { this.socket.emit('save', { file: file, memo: memo }); }; this.getDirSplit = function (dir, disableLastItem) { var dirSplit = []; var fullDir = ''; var dirs = dir.split('/'); var length = dirs.length; for (var i = 0; i < length; i++) { var dir = { name: dirs[i] }; if (!disableLastItem || (i !== length - 1)) { dir.link = fullDir + dirs[i]; } dirSplit.push(dir); fullDir += dirs[i] + '/'; } return dirSplit; } });
Add wrapper for render_to_resposne to include tmpl context processors easily Autoconverted from SVN (revision:2231)
from django.shortcuts import render_to_response from django.template.context import RequestContext def render(request, template, context={}): return render_to_response(template, context, context_instance=RequestContext(request)) def get_directory_name(job): """ Expected format: %sharedPath%watchedDirectories/workFlowDecisions/createDip/ImagesSIP-69826e50-87a2-4370-b7bd-406fc8aad94f/ """ import re directory = job.directory uuid = job.sipuuid try: return re.search(r'^.*/(?P<directory>.*)-[\w]{8}(-[\w]{4}){3}-[\w]{12}[/]{0,1}$', directory).group('directory') except: pass try: return re.search(r'^.*/(?P<directory>.*)/$', directory).group('directory') except: pass if directory: return directory else: return uuid
def get_directory_name(job): """ Expected format: %sharedPath%watchedDirectories/workFlowDecisions/createDip/ImagesSIP-69826e50-87a2-4370-b7bd-406fc8aad94f/ """ import re directory = job.directory uuid = job.sipuuid try: return re.search(r'^.*/(?P<directory>.*)-[\w]{8}(-[\w]{4}){3}-[\w]{12}[/]{0,1}$', directory).group('directory') except: pass try: return re.search(r'^.*/(?P<directory>.*)/$', directory).group('directory') except: pass if directory: return directory else: return uuid
Reset gzip encoder on put to pool
package main import ( "compress/gzip" "io" "io/ioutil" "sync" ) type gzipPool struct { mutex sync.Mutex top *gzipPoolEntry } type gzipPoolEntry struct { gz *gzip.Writer next *gzipPoolEntry } func newGzipPool(n int) *gzipPool { pool := new(gzipPool) for i := 0; i < n; i++ { pool.grow() } return pool } func (p *gzipPool) grow() { gz, err := gzip.NewWriterLevel(ioutil.Discard, conf.GZipCompression) if err != nil { logFatal("Can't init GZip compression: %s", err) } p.top = &gzipPoolEntry{ gz: gz, next: p.top, } } func (p *gzipPool) Get(w io.Writer) *gzip.Writer { p.mutex.Lock() defer p.mutex.Unlock() if p.top == nil { p.grow() } gz := p.top.gz gz.Reset(w) p.top = p.top.next return gz } func (p *gzipPool) Put(gz *gzip.Writer) { p.mutex.Lock() defer p.mutex.Unlock() gz.Reset(ioutil.Discard) p.top = &gzipPoolEntry{gz: gz, next: p.top} }
package main import ( "compress/gzip" "io" "io/ioutil" "sync" ) type gzipPool struct { mutex sync.Mutex top *gzipPoolEntry } type gzipPoolEntry struct { gz *gzip.Writer next *gzipPoolEntry } func newGzipPool(n int) *gzipPool { pool := new(gzipPool) for i := 0; i < n; i++ { pool.grow() } return pool } func (p *gzipPool) grow() { gz, err := gzip.NewWriterLevel(ioutil.Discard, conf.GZipCompression) if err != nil { logFatal("Can't init GZip compression: %s", err) } p.top = &gzipPoolEntry{ gz: gz, next: p.top, } } func (p *gzipPool) Get(w io.Writer) *gzip.Writer { p.mutex.Lock() defer p.mutex.Unlock() if p.top == nil { p.grow() } gz := p.top.gz gz.Reset(w) p.top = p.top.next return gz } func (p *gzipPool) Put(gz *gzip.Writer) { p.mutex.Lock() defer p.mutex.Unlock() p.top = &gzipPoolEntry{gz: gz, next: p.top} }
Change spec test back to true/false, rewrite loop for better clarity of changes
var pingPong = function(i) { if ((i % 5 === 0) || (i % 3 === 0)) { return true; } else { return false; } }; $(function() { $("#game").submit(function(event) { $('#outputList').empty(); var number = parseInt($("#userNumber").val()); for (var i = 1; i <= number; i += 1) { if (i % 15 === 0) { $('#outputList').append("<li>ping pong</li>"); } else if (i % 3 === 0) { $('#outputList').append("<li>ping</li>"); } else if (i % 5 === 0) { $('#outputList').append("<li>pong</li>"); } else { $('#outputList').append("<li>" + i + "</li>"); } } event.preventDefault(); }); });
var pingPong = function(i) { if ((i % 3 === 0) && (i % 5 != 0)) { return "ping"; } else if ((i % 5 === 0) && (i % 6 != 0)) { return "pong"; } else if ((i % 3 === 0) && (i % 5 === 0)) { return "ping pong"; } else { return false; } }; $(function() { $("#game").submit(function(event) { $('#outputList').empty(); var number = parseInt($("#userNumber").val()); for (var i = 1; i <= number; i += 1) { if (i % 15 === 0) { $('#outputList').append("<li>ping pong</li>"); } else if ((winner) && (i % 5 != 0)) { $('#outputList').append("<li>ping</li>"); } else if ((winner) && (i % 3 != 0)) { $('#outputList').append("<li>pong</li>"); } else { $('#outputList').append("<li>" + i + "</li>"); } } event.preventDefault(); }); });
Call e.respondWith() in fetch event handler.
this.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyHunters.jpg', '/sw-test/gallery/myLittleVader.jpg', '/sw-test/gallery/snowTroopers.jpg' ]); }) ); }); this.addEventListener('fetch', function(event) { var response; event.respondWith(caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); })); });
this.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyHunters.jpg', '/sw-test/gallery/myLittleVader.jpg', '/sw-test/gallery/snowTroopers.jpg' ]); }) ); }); this.addEventListener('fetch', function(event) { var response; var cachedResponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); }); });
Solve errata naming the class
<?php /* Copyright 2009-2011 Rafael Gutierrez Martinez * Copyright 2012-2013 Welma WEB MKT LABS, S.L. * Copyright 2014-2016 Where Ideas Simply Come True, S.L. * * 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. */ namespace nabu\data\icontact; use nabu\data\icontact\base\CNabuIContactProspectBase; /** * @author Rafael Gutierrez <rgutierrez@nabu-3.com> * @since 3.0.12 Surface * @version 3.0.12 Surface * @package \nabu\data\catalog */ class CNabuIContactProspect extends CNabuIContactProspectBase { }
<?php /* Copyright 2009-2011 Rafael Gutierrez Martinez * Copyright 2012-2013 Welma WEB MKT LABS, S.L. * Copyright 2014-2016 Where Ideas Simply Come True, S.L. * * 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. */ namespace nabu\data\icontact; use nabu\data\icontact\base\CNabuIContactProspectBase; /** * @author Rafael Gutierrez <rgutierrez@nabu-3.com> * @since 3.0.12 Surface * @version 3.0.12 Surface * @package \nabu\data\catalog */ class CNabuIcontactProspect extends CNabuIContactProspectBase { }
Use TAB instead of ;
#!/usr/bin/env python3 import sys import serial import datetime if __name__=='__main__': try: ser = serial.Serial('COM1', 115200, timeout=1) print("opened " + ser.portstr) except serial.SerialException: print('could not open port') sys.exit(1) pass f = open(datetime.datetime.now().strftime("%y-%m-%d_%H-%M-%S") + '.txt', 'w+') f.write('10ms\tx\ty\tz\tdelta\n') i = 0 line = ser.readline().decode('utf-8') # Truncate first read line try: while True: line = ser.readline().decode('utf-8') if line: f.write(str(i) + '\t' + line.replace(';', '\t')) i = i + 1 print(line) except KeyboardInterrupt: pass f.close() ser.close()
#!/usr/bin/env python3 import sys import serial import datetime if __name__=='__main__': try: ser = serial.Serial('COM1', 115200, timeout=1) print("opened " + ser.portstr) except serial.SerialException: print('could not open port') sys.exit(1) pass f = open(datetime.datetime.now().strftime("%y-%m-%d_%H-%M-%S") + '.csv', 'w+') f.write('10ms;x;y;z;delta\n') i = 0 line = ser.readline().decode('utf-8') # Truncate first read line try: while True: line = ser.readline().decode('utf-8') if line: f.write(str(i) + ';' + line) i = i + 1 print(line) except KeyboardInterrupt: pass f.close() ser.close()
Normalize the variance to 1.0 (from 0.5)
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance // because variance of similarity values can be a maximum of 0.5, we // multiply by 2 to get a metric from 0 to 1.0 return 2 * computeVariance(signatureVector); } }
package am.app.mappingEngine.qualityEvaluation.metrics.ufl; import java.util.List; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric; import am.app.mappingEngine.similarityMatrix.SimilarityMatrix; import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance; /** * Compute the disagreement between matching algorithms given their individual * similarity matrices. The constructor takes only one kind of matrix, either * the classes matrices or the properties matrices. You must instantiate a * separate object for each type of matrices. * * @author <a href="http://cstroe.com">Cosmin Stroe</a> * */ public class VarianceMatcherDisagreement extends AbstractQualityMetric { private SimilarityMatrix[] matrices; public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) { super(); this.matrices = matrices.toArray(new SimilarityMatrix[0]); } /** * @param type * This parameter is ignored. */ @Override public double getQuality(alignType type, int i, int j) { // create signature vector double[] signatureVector = new double[matrices.length]; for(int k = 0; k < matrices.length; k++) { signatureVector[k] = matrices[k].getSimilarity(i, j); } // return the computed variance return computeVariance(signatureVector); } }
Migrate the tests for the alert service to vlui
'use strict'; describe('Directive: alertMessages', function() { var element, scope; // load the directive's module beforeEach(module('vlui', function($provide) { // Mock the alerts service $provide.value('Alerts', { alerts: [ {msg: 'foo'}, {msg: 'bar'} ] }); })); beforeEach(inject(function($rootScope, $compile) { scope = $rootScope.$new(); var $el = angular.element('<alert-messages></alert-messages>'); element = $compile($el)(scope); scope.$digest(); })); it('should show alert messages', function() { expect(element.find('.alert-item').length).to.equal(2); // Ignore the close buttons, which use an HTML entity for the close icon element.find('a').remove(); expect(element.find('.alert-item').eq(0).text().trim()).to.equal('foo'); expect(element.find('.alert-item').eq(1).text().trim()).to.equal('bar'); }); });
'use strict'; describe('Directive: alertMessages', function() { // load the directive's module beforeEach(module('polestar')); var element, scope; beforeEach(module('polestar', function($provide) { var mock = { alerts: [ {name: 'foo'}, {name: 'bar'} ] }; $provide.value('Alerts', mock); })); beforeEach(inject(function($rootScope) { scope = $rootScope.$new(); })); it('should show alert messages', inject(function($compile) { element = angular.element('<alert-messages></alert-messages>'); element = $compile(element)(scope); scope.$digest(); expect(element.find('.alert-item').length).to.eql(2); })); });
Write out grammar JSON to a file when compiling
var api = require("../api"), fs = require("fs-extra"), path = require("path"), mkdirp = require("mkdirp"), templates = require("./templates"), cwd = process.cwd(); module.exports = function compile(options) { for (var key in api.dsl) { global[key] = api.dsl[key]; } require("coffee-script/register"); var grammar = require(path.join(cwd, "grammar")); var code; try { code = api.compile(grammar) } catch (e) { if (e.isGrammarError) { console.warn("Error: " + e.message); return 1; } else { throw e; } } mkdirp.sync(path.join(cwd, "src")); fs.writeFileSync(path.join(cwd, "src", "grammar.json"), JSON.stringify(grammar, null, 2)); fs.writeFileSync(path.join(cwd, "src", "parser.c"), code); fs.writeFileSync(path.join(cwd, "src", "binding.cc"), templates.bindingCC(grammar.name)); fs.writeFileSync(path.join(cwd, "binding.gyp"), templates.bindingGyp(grammar.name)); fs.writeFileSync(path.join(cwd, "index.js"), templates.indexJS(grammar.name)); return 0; }
var api = require("../api"), fs = require("fs-extra"), path = require("path"), mkdirp = require("mkdirp"), templates = require("./templates"), cwd = process.cwd(); module.exports = function compile(options) { for (var key in api.dsl) { global[key] = api.dsl[key]; } require("coffee-script/register"); var grammar = require(path.join(cwd, "grammar")); var code; try { code = api.compile(grammar) } catch (e) { if (e.isGrammarError) { console.warn("Error: " + e.message); return 1; } else { throw e; } } mkdirp.sync(path.join(cwd, "src")); fs.writeFileSync(path.join(cwd, "src", "parser.c"), code); fs.writeFileSync(path.join(cwd, "src", "binding.cc"), templates.bindingCC(grammar.name)); fs.writeFileSync(path.join(cwd, "binding.gyp"), templates.bindingGyp(grammar.name)); fs.writeFileSync(path.join(cwd, "index.js"), templates.indexJS(grammar.name)); return 0; }
Use the Chrome formatter when running in Electron
module.exports = require('./common/minilog.js'); var consoleLogger = require('./node/console.js'); // if we are running inside Electron then use the web version of console.js isChrome = (typeof navigator != 'undefined' && /chrome/i.test(navigator.userAgent)); if (isChrome) { consoleLogger = require('./web/console.js').minilog; } // intercept the pipe method and transparently wrap the stringifier, if the // destination is a Node core stream module.exports.Stringifier = require('./node/stringify.js'); var oldPipe = module.exports.pipe; module.exports.pipe = function(dest) { if(dest instanceof require('stream')) { return oldPipe.call(module.exports, new (module.exports.Stringifier)).pipe(dest); } else { return oldPipe.call(module.exports, dest); } }; module.exports.defaultBackend = consoleLogger; module.exports.defaultFormatter = consoleLogger.formatMinilog; module.exports.backends = { redis: require('./node/redis.js'), nodeConsole: consoleLogger, console: consoleLogger };
module.exports = require('./common/minilog.js'); var consoleLogger = require('./node/console.js'); // intercept the pipe method and transparently wrap the stringifier, if the // destination is a Node core stream module.exports.Stringifier = require('./node/stringify.js'); var oldPipe = module.exports.pipe; module.exports.pipe = function(dest) { if(dest instanceof require('stream')) { return oldPipe.call(module.exports, new (module.exports.Stringifier)).pipe(dest); } else { return oldPipe.call(module.exports, dest); } }; module.exports.defaultBackend = consoleLogger; module.exports.defaultFormatter = consoleLogger.formatMinilog; module.exports.backends = { redis: require('./node/redis.js'), nodeConsole: consoleLogger, console: consoleLogger };
Connect actions to props and add onSubmit function
import React, {Component} from 'react' import {connect} from 'react-redux'; import {bindActionCreators} from 'redux' import * as sessionsActions from '../actions/sessionsActions'; class Login extends Component { constructor(props) { super(); this.state = { email: '', password: '' } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e) { e.preventDefault(); this.props.actions.loginUser(this.state) this.setState({ email: '', password: '' }) } handleChange(e) { const name = e.target.name const value = e.target.value this.setState({ [name]: value }) } render() { return ( <form onSubmit={this.handleSubmit}> <label>Email: </label> <input type="text" name="email" value={this.state.email} onChange={this.handleChange} /><br /> <label>Password: </label> <input type="password" name="password" value={this.state.password} onChange={this.handleChange} /><br /> <input type="Submit" value="Log In" /> </form> ) } } function mapDispatchToProps(dispatch) { return {actions: bindActionCreators(sessionsActions, dispatch) } } export default connect(null, mapDispatchToProps)(Login)
import React, {Component} from 'react' class Login extends Component { constructor(props) { super(); this.state = { email: '', password: '' } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e) { e.preventDefault(); console.log("Submitted email: ", this.state.email, ", password: ", this.state.password) this.setState({ email: '', password: '' }) } handleChange(e) { const name = e.target.name const value = e.target.value this.setState({ [name]: value }) } render() { return ( <form onSubmit={this.handleSubmit}> <label>Email: </label> <input type="text" name="email" value={this.state.email} onChange={this.handleChange} /><br /> <label>Password: </label> <input type="password" name="password" value={this.state.password} onChange={this.handleChange} /><br /> <input type="Submit" value="Log In" /> </form> ) } } export default Login
Add project_id to invoice detail
<?php namespace Picqer\Financials\Moneybird\Entities\Generic; use Picqer\Financials\Moneybird\Model; /** * Class InvoiceDetail. */ abstract class InvoiceDetail extends Model { /** * @var array */ protected $fillable = [ 'id', 'tax_rate_id', 'ledger_account_id', 'amount', 'description', 'period', 'price', 'row_order', 'total_price_excl_tax_with_discount', 'total_price_excl_tax_with_discount_base', 'tax_report_reference', 'created_at', 'updated_at', 'product_id', '_destroy', 'project_id', ]; }
<?php namespace Picqer\Financials\Moneybird\Entities\Generic; use Picqer\Financials\Moneybird\Model; /** * Class InvoiceDetail. */ abstract class InvoiceDetail extends Model { /** * @var array */ protected $fillable = [ 'id', 'tax_rate_id', 'ledger_account_id', 'amount', 'description', 'period', 'price', 'row_order', 'total_price_excl_tax_with_discount', 'total_price_excl_tax_with_discount_base', 'tax_report_reference', 'created_at', 'updated_at', 'product_id', '_destroy', ]; }
Add purecloud hosts as trusted
import Ember from 'ember'; import AjaxService from 'ember-ajax/services/ajax'; const { inject, computed } = Ember; export default AjaxService.extend({ auth: inject.service(), contentType: 'application/json; charset=utf-8', trustedHosts: [ /outlook.office.com/, /graph.microsoft.com/, /online.lync.com/, /api.(?:inindca|mypurecloud).(?:com|jp).?(?:ie|au)?/ ], headers: computed('auth.msftAccessToken', function () { let headers = {}; const token = this.get('auth.msftAccessToken'); if (token) { headers['Authorization'] = `Bearer ${token}`; } return headers; }) });
import Ember from 'ember'; import AjaxService from 'ember-ajax/services/ajax'; const { inject, computed } = Ember; export default AjaxService.extend({ auth: inject.service(), contentType: 'application/json; charset=utf-8', trustedHosts: [ /outlook.office.com/, /graph.microsoft.com/, /online.lync.com/ ], headers: computed('auth.msftAccessToken', function () { let headers = {}; const token = this.get('auth.msftAccessToken'); if (token) { headers['Authorization'] = `Bearer ${token}`; } return headers; }) });
Update regex for diesel fuel
<?php use Illuminate\Database\Seeder; class VehiclesFuelsTableSeeder extends Seeder { public function run() { DB::table('vehicles_fuels')->delete(); $fuels = [ ['name' => 'Gasolina', 'regex' => '/\bgasolina\b/i'], ['name' => 'Diesel', 'regex' => '/\bdiesel|gas[oó]leo\b/iu'], ['name' => 'GPL', 'regex' => '/\bgpl|g[aá]s\b/iu'], ['name' => 'Híbrido', 'regex' => '/\bh[íi]brido\b/iu'], ['name' => 'Eléctrico', 'regex' => '/\bel[ée]c?trico\b/iu'], ]; DB::table('vehicles_fuels')->insert($fuels); } }
<?php use Illuminate\Database\Seeder; class VehiclesFuelsTableSeeder extends Seeder { public function run() { DB::table('vehicles_fuels')->delete(); $fuels = [ ['name' => 'Gasolina', 'regex' => '/\bgasolina\b/i'], ['name' => 'Diesel', 'regex' => '/\bgas[oó]leo\b/iu'], ['name' => 'GPL', 'regex' => '/\bgpl|g[aá]s\b/iu'], ['name' => 'Híbrido', 'regex' => '/\bh[íi]brido\b/iu'], ['name' => 'Eléctrico', 'regex' => '/\bel[ée]c?trico\b/iu'], ]; DB::table('vehicles_fuels')->insert($fuels); } }
Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # For Django 1.6 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ]
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^selectable/', include('selectable.urls')), url(r'', include('timepiece.urls')), # authentication views url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='auth_login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', name='auth_logout'), url(r'^accounts/password-change/$', 'django.contrib.auth.views.password_change', name='change_password'), url(r'^accounts/password-change/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^accounts/password-reset/$', 'django.contrib.auth.views.password_reset', name='reset_password'), url(r'^accounts/password-reset/done/$', 'django.contrib.auth.views.password_reset_done'), url(r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^accounts/reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ]
Tag an image based on detected visual content which mean running a CNN on top of it.
<?php /* * PixLab PHP Client which is just a single class PHP file without any dependency that you can get from Github * https://github.com/symisc/pixlab-php */ require_once "pixlab.php"; # Tag an image based on detected visual content which mean running a CNN on top of it. # https://pixlab.io/#/cmd?id=tagimg for more info. # Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info. $img = 'https://s-media-cache-ak0.pinimg.com/originals/35/d0/f6/35d0f6ee0e40306c41cfd714c625f78e.jpg'; # Your PixLab key $key = 'My_Pixlab_Key'; /* Process */ $pix = new Pixlab($key); if( !$pix->get('tagimg',array( 'img' => $img )) ){ echo $pix->get_error_message(); die; } /* Grab the total number of tags */ $tags = $pix->json->tags; echo "Total number of tags: ".count($tags)."\n"; foreach($tags as $tag){ echo "Tag = ".$tag->name.", Confidence: ".$tag->confidence."\n"; }
<?php /* * PixLab PHP Client which is just a single class PHP file without any dependency that you can get from Github * https://github.com/symisc/pixlab-php */ require_once "pixlab.php"; # Tag an image based on detected visual content which mean running a CNN on top of it. # https://pixlab.io/#/cmd?id=tagimg for more info. # Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info. $img = 'https://s-media-cache-ak0.pinimg.com/originals/35/d0/f6/35d0f6ee0e40306c41cfd714c625f78e.jpg'; # Your PixLab key $key = 'My_Pixlab_Key'; /* Process */ $pix = new Pixlab($key); if( !$pix->get('tagimg',array( 'img' => $img, 'key' => $key )) ){ echo $pix->get_error_message(); die; } /* Grab the total number of tags */ $tags = $pix->json->tags; echo "Total number of tags: ".count($tags)."\n"; foreach($tags as $tag){ echo "Tag = ".$tag->name.", Confidence: ".$tag->confidence."\n"; }
Rename passwd to password for form field validation
<?php namespace OpenCFP\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; class ResetForm extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('password', 'repeated', array( 'constraints' => array( new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'type' => 'password', 'first_options' => array('label' => 'Password (minimum 5 characters)'), 'second_options' => array('label' => 'Password (confirm)'), 'first_name' => 'password', 'second_name' => 'password2', 'invalid_message' => 'Passwords did not match')) ->add('user_id', 'hidden') ->add('reset_code', 'hidden') ->getForm(); } public function getName() { return 'reset'; } }
<?php namespace OpenCFP\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; class ResetForm extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('password', 'repeated', array( 'constraints' => array( new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'type' => 'password', 'first_options' => array('label' => 'Password (minimum 5 characters)'), 'second_options' => array('label' => 'Password (confirm)'), 'first_name' => 'passwd', 'second_name' => 'passwd2', 'invalid_message' => 'Passwords did not match')) ->add('user_id', 'hidden') ->add('reset_code', 'hidden') ->getForm(); } public function getName() { return 'reset'; } }
Bump version for new pypi dist
#!/usr/bin/env python from distutils.core import setup setup(name='optfunc-ysimonson', version='0.1.2', description='Generate commandline flags from function arguments.', author='Simon Willison', author_email='simon@lanyrd.com', url='https://github.com/ysimonson/optfunc', license='BSD', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2 :: Only', 'Environment :: Console', 'Development Status :: 4 - Beta'], py_modules=['optfunc'])
#!/usr/bin/env python from distutils.core import setup setup(name='optfunc-ysimonson', version='0.1.1', description='Generate commandline flags from function arguments.', author='Simon Willison', author_email='simon@lanyrd.com', url='https://github.com/ysimonson/optfunc', license='BSD', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2 :: Only', 'Environment :: Console', 'Development Status :: 4 - Beta'], py_modules=['optfunc'])
Rewrite structure_check tests with hypothesis `OrderedDict` chosen instead of `SimpleNamespace` as the former supports the dictionary-like item access, unlike the latter.
from collections import OrderedDict import pytest from hypothesis import given from hypothesis.strategies import lists, tuples, integers, dictionaries, \ fixed_dictionaries from datatyping.datatyping import validate @given(lst=lists(integers()), tpl=tuples(integers())) def test_different_sequences(lst, tpl): with pytest.raises(TypeError): if tpl: validate([int], tpl) else: validate([], tpl) with pytest.raises(TypeError): if lst: validate((int), lst) else: validate((), lst) @given(dct=dictionaries(integers(), integers())) def test_different_mappings(dct): with pytest.raises(TypeError): validate(dict, OrderedDict(dct)) validate(OrderedDict, dct) @given(lst=lists( fixed_dictionaries({ 'a': fixed_dictionaries({ 'b': lists( dictionaries(integers(), integers(), min_size=1), min_size=1 ) }) }), min_size=1 )) def test_dict_nested(lst): assert validate([{'a': {'b': [dict]}}], lst) is None
import pytest from datatyping.datatyping import validate def test_empty(): with pytest.raises(TypeError): assert validate([], ()) is None def test_empty_reversed(): with pytest.raises(TypeError): assert validate((), []) is None def test_plain(): with pytest.raises(TypeError): assert validate([int], (1, 2, 3, 4, 5)) is None def test_plain_reversed(): with pytest.raises(TypeError): assert validate((int, ), [1, 2, 3, 4, 5]) is None from types import SimpleNamespace def test_mapping_empty(): with pytest.raises(TypeError): assert validate([dict], [SimpleNamespace(), SimpleNamespace(), SimpleNamespace()]) is None def test_mapping_empty_reversed(): with pytest.raises(TypeError): assert validate([SimpleNamespace], [{}, {}, {}]) is None def test_dict_nested(): with pytest.raises(TypeError): assert validate([{'a': {'b': [dict]}}], [ {'a': {'b': [{}, SimpleNamespace()]}}, {'a': {'b': [{'any': 'key'}, {'used': 'here'}]}}, ]) is None
Improve cprint to use __str__ method if available
from __future__ import print_function import sys import string from colors import * def is_posix_filename(name, extra_chars=""): CHARS = string.letters + string.digits + "._-" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stdout, end='\n'): data = msg.__str__() if hasattr(msg, '__str__') else msg print(color + data + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, "tst: non-recognized encoding"
from __future__ import print_function import sys import string from colors import * def is_posix_filename(name, extra_chars=""): CHARS = string.letters + string.digits + "._-" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stdout, end='\n'): print(color + msg + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, "tst: non-recognized encoding"
Define a global for the autoloader location
<?php /* * Test bootstrapper. This leaves out all stuff registering services and * related to request dispatching. */ global $CLASSLOADER; if (!defined('TEST_ROOT')) { define('TEST_ROOT', realpath(__DIR__ . '/../../')); } if (!defined('BOLT_AUTOLOAD')) { if (is_dir(TEST_ROOT . '/../../../vendor/')) { // Composer install define('BOLT_AUTOLOAD', TEST_ROOT . '/../../autoload.php'); } else { // Git/tarball install define('BOLT_AUTOLOAD', TEST_ROOT . '/vendor/autoload.php'); } // Load the autoloader $CLASSLOADER = require_once BOLT_AUTOLOAD; } // Load the upload bootstrap require_once 'bootstraps/upload-bootstrap.php'; // Make sure we wipe the db file to start with a clean one if (is_readable(TEST_ROOT . '/bolt.db')) { unlink(TEST_ROOT . '/bolt.db'); } copy(TEST_ROOT . '/tests/phpunit/resources/db/bolt.db', TEST_ROOT . '/bolt.db'); @mkdir(TEST_ROOT . '/app/cache/', 0777, true);
<?php /* * Test bootstrapper. This leaves out all stuff registering services and * related to request dispatching. */ global $CLASSLOADER; if (!defined('TEST_ROOT')) { define('TEST_ROOT', realpath(__DIR__ . '/../../')); } if (is_dir(TEST_ROOT . '/../../../vendor/')) { // Composer install $CLASSLOADER = require_once TEST_ROOT . '/../../autoload.php'; } else { // Git/tarball install $CLASSLOADER = require_once TEST_ROOT . '/vendor/autoload.php'; } require_once 'bootstraps/upload-bootstrap.php'; // Make sure we wipe the db file to start with a clean one if (is_readable(TEST_ROOT . '/bolt.db')) { unlink(TEST_ROOT . '/bolt.db'); } copy(TEST_ROOT . '/tests/phpunit/resources/db/bolt.db', TEST_ROOT . '/bolt.db'); @mkdir(TEST_ROOT . '/app/cache/', 0777, true);
Make sure we have actually looked up a model in get_model_from_string.
# Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-webshop. # # django-webshop is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging logger = logging.getLogger(__name__) from django.db import models """ Several util functions for use in core functionality. """ def get_model_from_string(model): """ Takes a string in the form of `appname.Model`, (ie. `basic_webshop.CartItem`) and returns the model class for it. """ model_class = models.get_model(*model.split('.')) assert isinstance(model_class, models.base.ModelBase), \ '%s does not refer to a known Model class.' % model return model_class
# Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-webshop. # # django-webshop is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from django.db.models import get_model """ Several util functions for use in core functionality. """ def get_model_from_string(model): """ Takes a string in the form of `appname.Model`, (ie. `basic_webshop.CartItem`) and returns the model class for it. """ return get_model(*model.split('.'))
Rename the package so that it does not contain -
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='ckanserviceprovider', version=version, description="A server that can server jobs at services.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='David Raznick', author_email='kindly@gmail.com', url='', license='AGPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[''' APScheduler Flask SQLAlchemy requests''' ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='ckan-service-provider', version=version, description="A server that can server jobs at services.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='David Raznick', author_email='kindly@gmail.com', url='', license='AGPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[''' APScheduler Flask SQLAlchemy requests''' ], entry_points=""" # -*- Entry points: -*- """, )
TDB-4594: Return a copy of Nomad object mappper for protection
/* * Copyright (c) 2011-2019 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. * Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. */ package com.terracottatech.dynamic_config.nomad; import com.fasterxml.jackson.databind.ObjectMapper; import com.terracottatech.nomad.client.change.MultipleNomadChanges; import com.terracottatech.nomad.client.change.NomadChange; import com.terracottatech.nomad.client.change.SimpleNomadChange; import com.terracottatech.utilities.Json; /** * @author Mathieu Carbou */ public class NomadJson { public static ObjectMapper buildObjectMapper() { ObjectMapper objectMapper = Json.copyObjectMapper(true); objectMapper.registerSubtypes( NomadChange.class, FilteredNomadChange.class, ConfigMigrationNomadChange.class, ConfigRepairNomadChange.class, ClusterActivationNomadChange.class, SettingNomadChange.class, MultipleNomadChanges.class, SimpleNomadChange.class); return objectMapper.copy(); } }
/* * Copyright (c) 2011-2019 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. * Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. */ package com.terracottatech.dynamic_config.nomad; import com.fasterxml.jackson.databind.ObjectMapper; import com.terracottatech.nomad.client.change.MultipleNomadChanges; import com.terracottatech.nomad.client.change.NomadChange; import com.terracottatech.nomad.client.change.SimpleNomadChange; import com.terracottatech.utilities.Json; /** * @author Mathieu Carbou */ public class NomadJson { public static ObjectMapper buildObjectMapper() { ObjectMapper objectMapper = Json.copyObjectMapper(true); objectMapper.registerSubtypes( NomadChange.class, FilteredNomadChange.class, ConfigMigrationNomadChange.class, ConfigRepairNomadChange.class, ClusterActivationNomadChange.class, SettingNomadChange.class, MultipleNomadChanges.class, SimpleNomadChange.class); return objectMapper; } }
Fix test coverage being horribly useless
var path = require('path'); var coffeeCoverage = require('coffee-coverage'); var projectRoot = path.normalize(path.join(__dirname, '..')); var coverageVar = coffeeCoverage.findIstanbulVariable(); // Only write a coverage report if we're not running inside of Istanbul. var writeOnExit = (coverageVar == null) ? (projectRoot + '/coverage/coverage-coffee.json') : null; coffeeCoverage.register({ instrumentor: 'istanbul', basePath: projectRoot, exclude: [ '/test', '/node_modules', '/.git', '/gulpfile.coffee', '/' + path.normalize('src/client.coffee'), '/' + path.normalize('src/main.coffee') ], coverageVar: coverageVar, writeOnExit: writeOnExit, initAll: true });
var path = require('path'); var coffeeCoverage = require('coffee-coverage'); var projectRoot = path.normalize(__dirname); var coverageVar = coffeeCoverage.findIstanbulVariable(); // Only write a coverage report if we're not running inside of Istanbul. var writeOnExit = (coverageVar == null) ? (projectRoot + '/coverage/coverage-coffee.json') : null; coffeeCoverage.register({ instrumentor: 'istanbul', basePath: projectRoot, exclude: [ '/test', '/node_modules', '/.git', '/gulpfile.coffee', '/' + path.normalize('src/client.coffee'), '/' + path.normalize('src/main.coffee') ], coverageVar: coverageVar, writeOnExit: writeOnExit, initAll: true });
Add onclick handler to toggle soft wrap
'use babel' /** @jsx etch.dom */ import etch from 'etch' import stateless from 'etch-stateless' const IndicatorAnchor = stateless(etch, ({onclick, wrapped}) => { let light = '' if (wrapped) { light = 'lit' } else { light = 'unlit' } return <a className={`status-${light}`} onclick={onclick} href="#">Wrap</a> }) export default class SoftWrapStatusComponent { constructor () { this.visible = true this.softWrapped = false etch.initialize(this) } render () { return ( <div className="soft-wrap-status-component inline-block"> {this.renderIndicator()} </div> ) } renderIndicator () { if (this.visible) { return <IndicatorAnchor onclick={this.toggleSoftWrap.bind(this)} wrapped={this.softWrapped} /> } } toggleSoftWrap () { atom.workspace.getActiveTextEditor().toggleSoftWrapped() } update ({visible, softWrapped}) { this.visible = visible this.softWrapped = softWrapped return etch.update(this) } destroy () { etch.destroy(this) } }
'use babel' /** @jsx etch.dom */ import etch from 'etch' import stateless from 'etch-stateless' const IndicatorAnchor = stateless(etch, ({wrapped}) => { let light = '' if (wrapped) { light = 'lit' } else { light = 'unlit' } return <a className={`status-${light}`} href="#">Wrap</a> }) export default class SoftWrapStatusComponent { constructor () { this.visible = true this.softWrapped = false etch.initialize(this) } render () { return ( <div className="soft-wrap-status-component inline-block"> {this.renderIndicator()} </div> ) } renderIndicator () { if (this.visible) { return <IndicatorAnchor wrapped={this.softWrapped} /> } } update ({visible, softWrapped}) { this.visible = visible this.softWrapped = softWrapped return etch.update(this) } destroy () { etch.destroy(this) } }
Fix autoload path in example
<!DOCTYPE html> <html lang="cs-CZ"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ical Parser example</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Czech holidays</h1> <ul> <?php require_once __DIR__ . '/../vendor/autoload.php'; $cal = new \om\IcalParser(); $results = $cal->parseFile( 'https://www.google.com/calendar/ical/cs.czech%23holiday%40group.v.calendar.google.com/public/basic.ics' ); foreach ($cal->getSortedEvents() as $r) { echo sprintf(' <li>%s - %s</li>' . PHP_EOL, $r['DTSTART']->format('j.n.Y'), $r['SUMMARY']); } ?></ul> </div> </body> </html>
<!DOCTYPE html> <html lang="cs-CZ"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ical Parser example</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Czech holidays</h1> <ul> <?php require_once '../vendor/autoload.php'; $cal = new \om\IcalParser(); $results = $cal->parseFile( 'https://www.google.com/calendar/ical/cs.czech%23holiday%40group.v.calendar.google.com/public/basic.ics' ); foreach ($cal->getSortedEvents() as $r) { echo sprintf(' <li>%s - %s</li>' . PHP_EOL, $r['DTSTART']->format('j.n.Y'), $r['SUMMARY']); } ?></ul> </div> </body> </html>
Prepare for players and maps update of core.
'use strict'; // Make our own plugin main interface an event emitter. // This can be used to communicate and subscribe to others plugins events. import { EventEmitter } from 'events'; /** * Plugin Interface * @class Plugin */ export default class extends EventEmitter { /** * Construct the plugin. */ constructor() { super(); // Will be injected by core this.app = null; this.plugins = null; this.server = null; this.players = null; this.maps = null; /** * Will hold the defined models for this plugin! * * @type {{}} */ this.models = {}; } /** * Inject Core App interface into the plugin. * * @param {App} app */ inject(app) { this.app = app; this.server = app.server; // Expand app into separate parts. this.players = app.players; this.maps = app.maps; } }
'use strict'; // Make our own plugin main interface an event emitter. // This can be used to communicate and subscribe to others plugins events. import { EventEmitter } from 'events'; /** * Plugin Interface * @class Plugin */ export default class extends EventEmitter { /** * Construct the plugin. */ constructor() { super(); // Will be injected by core this.app = null; this.plugins = null; this.server = null; this.players = null; this.maps = null; /** * Will hold the defined models for this plugin! * * @type {{}} */ this.models = {}; } /** * Inject Core App interface into the plugin. * * @param {App} app */ inject(app) { this.app = app; this.server = app.server; // Expand app into separate parts. // TODO: Fill in plugins, server, players, maps. } }
Simplify the icon finder function. We statically know our bundle identifier, so we don’t have too find the bundle by runtime class.
#!/usr/bin/env python # -*- coding: utf-8 -*- from Foundation import objc from Foundation import NSBundle from AppKit import NSImage haskellBundleIdentifier = 'org.purl.net.mkhl.haskell' def iconForName(name): """Return the NSImage instance representing a `name` item.""" bundle = NSBundle.bundleWithIdentifier_(haskellBundleIdentifier) imgpath = bundle.pathForResource_ofType_(name, 'png') img = NSImage.alloc().initWithContentsOfFile_(imgpath) img.autorelease() return img class HaskellModuleItem(objc.lookUpClass('ESBaseItem')): """Itemizer for modules""" def isDecorator(self): return True def image(self): return iconForName('module') class HaskellTypeItem(objc.lookUpClass('ESBaseItem')): """Itemizer for datatypes""" def isDecorator(self): return True def image(self): return iconForName('type') def isTextualizer(self): return True def title(self): return self.text().lstrip() class HaskellFunctionItem(objc.lookUpClass('ESBaseItem')): """Itemizer for functions""" pass class HaskellCodeBlockItem(objc.lookUpClass('ESCodeBlockItem')): """Itemizer for code blocks""" def isTextualizer(self): return True def title(self): return '%s %s' % (u'{…}', self.text().lstrip())
#!/usr/bin/env python # -*- coding: utf-8 -*- from Foundation import objc from Foundation import NSBundle from AppKit import NSImage def iconForName(klass, name): """Return the NSImage instance representing a `name` item.""" imgpath = NSBundle.bundleForClass_(klass).pathForResource_ofType_(name, 'png') img = NSImage.alloc().initWithContentsOfFile_(imgpath) img.autorelease() return img class HaskellModuleItem(objc.lookUpClass('ESBaseItem')): """Itemizer for modules""" def isDecorator(self): return True def image(self): return iconForName(self.class__(), 'module') class HaskellTypeItem(objc.lookUpClass('ESBaseItem')): """Itemizer for datatypes""" def isDecorator(self): return True def image(self): return iconForName(self.class__(), 'type') def isTextualizer(self): return True def title(self): return self.text().lstrip() class HaskellFunctionItem(objc.lookUpClass('ESBaseItem')): """Itemizer for functions""" pass class HaskellCodeBlockItem(objc.lookUpClass('ESCodeBlockItem')): """Itemizer for code blocks""" def isTextualizer(self): return True def title(self): return '%s %s' % (u'{…}', self.text().lstrip())
Add proptypes & signedIn check to navbar
import React, { PureComponent, PropTypes } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import signOut from '../../actions/users/sign-out' class Navbar extends PureComponent { static propTypes = { currentUser: PropTypes.object, signedIn: PropTypes.bool.isRequired } renderSignOut() { return <li><a onClick={this.props.signOut} href='#'>Sign Out</a></li> } renderSignIn() { return <li><Link to='/sign-in'>Sign In</Link></li> } render() { const { signedIn } = this.props return( <header className='page-header'> <span><Link to='/'>SlimPoll</Link></span> <nav className='navbar'> <li><Link to="/all-polls">Polls</Link></li> { signedIn && <li><Link to="/create-poll">Create a poll</Link></li> } { signedIn && <li><Link to="/my-polls">View your polls</Link></li> } { signedIn ? this.renderSignOut() : this.renderSignIn() } </nav> </header> ) } } const mapStateToProps = ({ currentUser }) => ({ currentUser, signedIn: !!currentUser }) export default connect(mapStateToProps, { signOut })(Navbar)
import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import signOut from '../../actions/users/sign-out' class Navbar extends PureComponent { checkLoginStatus() { return !!this.props.currentUser ? this.renderSignOut() : this.renderSignIn() } renderSignOut() { return <li><a onClick={this.props.signOut} href='#'>Sign Out</a></li> } renderSignIn() { return <li><Link to='/sign-in'>Sign In</Link></li> } render() { return( <header className='page-header'> <span><Link to='/'>SlimPoll</Link></span> <nav className='navbar'> <li><Link to="/all-polls">Polls</Link></li> <li><Link to="/create-poll">Create a poll</Link></li> <li><Link to="/my-polls">View your polls</Link></li> { this.checkLoginStatus() } </nav> </header> ) } } const mapStateToProps = ({ currentUser }) => ({ currentUser }) export default connect(mapStateToProps, { signOut })(Navbar)
Fix development environment broken after Babel 6 update
import reactTransform from 'babel-plugin-react-transform' import es2015 from 'babel-preset-es2015' import stage0 from 'babel-preset-stage-0' import react from 'babel-preset-react' export default { name: 'webpack-babel', configure ({ buildTarget }) { const hmrEnv = { development: { plugins: [ [reactTransform, { transforms: [{ transform: 'react-transform-hmr', imports: ['react'], locals: ['module'] }] }] ] } } return { babel: { presets: [es2015, stage0, react], env: buildTarget === 'develop' ? hmrEnv : {} }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' } ] }, resolve: { extensions: ['', '.js', '.jsx'] } } } }
import reactTransform from 'babel-plugin-react-transform' import es2015 from 'babel-preset-es2015' import stage0 from 'babel-preset-stage-0' import react from 'babel-preset-react' export default { name: 'webpack-babel', configure ({ buildTarget }) { const hmrEnv = { development: { plugins: [reactTransform], extra: { 'react-transform': { transforms: [{ transform: 'react-transform-hmr', imports: ['react'], locals: ['module'] }] } } } } return { babel: { presets: [es2015, stage0, react], env: buildTarget === 'develop' ? hmrEnv : {} }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' } ] }, resolve: { extensions: ['', '.js', '.jsx'] } } } }
Update test Solr download script to work with default Python 3
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import sys import requests # Try to import urljoin from the Python 3 reorganized stdlib first: try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin if len(sys.argv) != 2: print('Usage: %s SOLR_VERSION' % sys.argv[0], file=sys.stderr) sys.exit(1) solr_version = sys.argv[1] tarball = 'solr-{0}.tgz'.format(solr_version) dist_path = 'lucene/solr/{0}/{1}'.format(solr_version, tarball) download_url = urljoin('http://archive.apache.org/dist/', dist_path) mirror_response = requests.get("http://www.apache.org/dyn/mirrors/mirrors.cgi/%s?asjson=1" % dist_path) if mirror_response.ok: mirror_data = mirror_response.json() download_url = urljoin(mirror_data['preferred'], mirror_data['path_info']) print(download_url)
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import sys import requests # Try to import urljoin from the Python 3 reorganized stdlib first: try: from urlparse.parse import urljoin except ImportError: from urlparse import urljoin if len(sys.argv) != 2: print('Usage: %s SOLR_VERSION' % sys.argv[0], file=sys.stderr) sys.exit(1) solr_version = sys.argv[1] tarball = 'solr-{0}.tgz'.format(solr_version) dist_path = 'lucene/solr/{0}/{1}'.format(solr_version, tarball) download_url = urljoin('http://archive.apache.org/dist/', dist_path) mirror_response = requests.get("http://www.apache.org/dyn/mirrors/mirrors.cgi/%s?asjson=1" % dist_path) if mirror_response.ok: mirror_data = mirror_response.json() download_url = urljoin(mirror_data['preferred'], mirror_data['path_info']) print(download_url)
Fix ui bug in switch
# -*- coding: utf-8 -*- # Gitless - a version control system built on top of Git. # Licensed under GNU GPL v2. """gl switch - Switch branches.""" from __future__ import unicode_literals from clint.textui import colored from . import pprint def parser(subparsers, _): """Adds the switch parser to the given subparsers object.""" switch_parser = subparsers.add_parser( 'switch', help='switch branches') switch_parser.add_argument('branch', help='switch to branch') switch_parser.add_argument( '-mo', '--move-over', help='move uncomitted changes made in the current branch to the ' 'destination branch', action='store_true') switch_parser.set_defaults(func=main) def main(args, repo): b = repo.lookup_branch(args.branch) if not b: pprint.err('Branch {0} doesn\'t exist'.format(args.branch)) pprint.err_exp('to list existing branches do gl branch') return False repo.switch_current_branch(b, move_over=args.move_over) pprint.ok('Switched to branch {0}'.format(args.branch)) return True
# -*- coding: utf-8 -*- # Gitless - a version control system built on top of Git. # Licensed under GNU GPL v2. """gl switch - Switch branches.""" from __future__ import unicode_literals from clint.textui import colored from . import pprint def parser(subparsers, _): """Adds the switch parser to the given subparsers object.""" switch_parser = subparsers.add_parser( 'switch', help='switch branches') switch_parser.add_argument('branch', help='switch to branch') switch_parser.add_argument( '-mo', '--move-over', help='move uncomitted changes made in the current branch to the ' 'destination branch', action='store_true') switch_parser.set_defaults(func=main) def main(args, repo): b = repo.lookup_branch(args.branch) if not b: pprint.err('Branch {0} doesn\'t exist'.format(colored.green(args.branch))) pprint.err_exp('to list existing branches do gl branch') return False repo.switch_current_branch(b, move_over=args.move_over) pprint.ok('Switched to branch {0}'.format(args.branch)) return True
Set `output_routes` to True by default
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) define( "output_routes", default=True, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) # Options for testing define( "output_routes", default=False, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'})
Add preamble with settings for some famous web servers Makes it simple to configure the headers for the Apache and Nginx without reading it up on the net. Output the headers with level 'ERROR' so that it's written out when using the `--silent` option.
'use strict'; var buildPolicyString = require('./utils')['buildPolicyString']; var chalk = require('chalk'); module.exports = { 'csp-headers': { name: 'csp-headers', description: 'Generate Content-Security-Policy headers', works: 'insideProject', availableOptions: [ { name: 'environment', type: String, aliases: [ 'e' ], default: 'development' }, { name: 'report-uri', type: String } ], run: function(options) { var config = this.project.config(options.environment); var reportUri = options.reportUri; if (!!reportUri) { config.contentSecurityPolicy['report-uri'] = reportUri; } this.ui.writeLine(chalk.dim.cyan('# Content Security Policy Header Configuration')); this.ui.writeLine(chalk.dim.cyan('#')); this.ui.writeLine(chalk.dim.cyan('# for Apache: Header set ' + config.contentSecurityPolicyHeader + ' "..."')); this.ui.writeLine(chalk.dim.cyan('# for Nginx : add_header ' + config.contentSecurityPolicyHeader + ' "...";') + '\n'); var policyObject = config.contentSecurityPolicy; this.ui.writeLine(buildPolicyString(policyObject), 'ERROR'); } } };
'use strict'; var buildPolicyString = require('./utils')['buildPolicyString']; module.exports = { 'csp-headers': { name: 'csp-headers', description: 'Generate Content-Security-Policy headers', works: 'insideProject', availableOptions: [ { name: 'environment', type: String, aliases: [ 'e' ], default: 'development' }, { name: 'report-uri', type: String } ], run: function(options) { var config = this.project.config(options.environment); var reportUri = options.reportUri; if (!!reportUri) { config.contentSecurityPolicy['report-uri'] = reportUri; } var policyObject = config.contentSecurityPolicy; this.ui.writeLine(buildPolicyString(policyObject)); } } };
Make inaccessable private key exception more informative Perviously setting $config['rsa_private_key'] = 'file://full/path/to/key.pem' (note two slashes instead of three) or other variations that are incompatitible with openssl_pkey_private(), would just give the user "Cannot access private key for signing", for a file that is very much accessable. The additional info I've added allows the user to go straight to the manual instead of spending time thinking it's a permissions issue.
<?php namespace XeroPHP\Remote\OAuth\SignatureMethod; use XeroPHP\Remote\OAuth\Exception; class RSASHA1 implements SignatureMethodInterface { public static function generateSignature(array $config, $sbs, $secret) { // Fetch the private key if(false === $private_key_id = openssl_pkey_get_private($config['rsa_private_key'])){ throw new Exception("Cannot access private key for signing: openssl_pkey_get_private('${config['rsa_private_key']}') returned false"); } // Sign using the key if(false === openssl_sign($sbs, $signature, $private_key_id)) { throw new Exception('Cannot sign signature base string.'); } // Release the key resource openssl_free_key($private_key_id); return base64_encode($signature); } }
<?php namespace XeroPHP\Remote\OAuth\SignatureMethod; use XeroPHP\Remote\OAuth\Exception; class RSASHA1 implements SignatureMethodInterface { public static function generateSignature(array $config, $sbs, $secret) { // Fetch the private key if(false === $private_key_id = openssl_pkey_get_private($config['rsa_private_key'])) throw new Exception('Cannot access private key for signing'); // Sign using the key if(false === openssl_sign($sbs, $signature, $private_key_id)) { throw new Exception('Cannot sign signature base string.'); } // Release the key resource openssl_free_key($private_key_id); return base64_encode($signature); } }
Fix me being an idiot
@foreach (session('flash_notification', collect())->toArray() as $message) @if ($message['overlay']) @include('flash::modal', [ 'modalClass' => 'flash-modal', 'title' => $message['title'], 'body' => $message['message'] ]) @else <div class="alert alert-{{ $message['level'] }} {{ $message['important'] ? 'alert-important' : '' }}" > @if ($message['important']) <button type="button" class="close" data-dismiss="alert" aria-hidden="true" >&times;</button> @endif {!! $message['message'] !!} </div> @endif @endforeach {{ session()->forget('flash_notification') }}
@foreach (session('flash_notification', collect())->toArray() as $message) @if (isset($message['overlay'] && $message['overlay']) @include('flash::modal', [ 'modalClass' => 'flash-modal', 'title' => $message['title'], 'body' => $message['message'] ]) @else <div class="alert alert-{{ $message['level'] }} {{ $message['important'] ? 'alert-important' : '' }}" > @if ($message['important']) <button type="button" class="close" data-dismiss="alert" aria-hidden="true" >&times;</button> @endif {!! $message['message'] !!} </div> @endif @endforeach {{ session()->forget('flash_notification') }}
Integrate jshint in CI process.
module.exports = function(grunt) { var pkg = grunt.file.readJSON('package.json'); (function () { var taskName; for(taskName in pkg.devDependencies) { if(taskName.substring(0, 6) === 'grunt-') { grunt.loadNpmTasks(taskName); } } })(); grunt.initConfig({ pkg: pkg, jshint: { files: [ 'lib/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochaTest: { unit: { options: { reporter: 'spec' }, src: ['test/**/*.js'] } } }); grunt.registerTask('test', ['jshint', 'mochaTest:unit']); };
module.exports = function(grunt) { var pkg = grunt.file.readJSON('package.json'); (function () { var taskName; for(taskName in pkg.devDependencies) { if(taskName.substring(0, 6) === 'grunt-') { grunt.loadNpmTasks(taskName); } } })(); grunt.initConfig({ pkg: pkg, jshint: { files: [ 'lib/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochaTest: { unit: { options: { reporter: 'spec' }, src: ['test/**/*.js'] } } }); grunt.registerTask('test', ['mochaTest:unit']); };
Make Croogo fixture insert compatible with CakePHP 3 one
<?php namespace Croogo\Croogo\TestSuite; use Cake\Database\Connection; use Cake\Database\Driver\Postgres; use Cake\TestSuite\Fixture\TestFixture; /** * CroogoTestFixture class * * @category TestSuite * @package Croogo * @version 1.4 * @author Fahad Ibnay Heylaal <contact@fahad19.com> * @author Rachman Chavik <rchavik@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @link http://www.croogo.org */ class CroogoTestFixture extends TestFixture { /** * _fixSequence * * @param Postgres $db */ protected function _fixSequence($db) { $sql = sprintf(" SELECT setval(pg_get_serial_sequence('%s', 'id'), (SELECT MAX(id) FROM %s))", $this->table, $this->table); $db->execute($sql); } /** * insert * * @param Object $db * @return array */ public function insert(Connection $db) { $result = parent::insert($db); if ($result === true && $db instanceof Postgres) { $this->_fixSequence($db); } return $result; } }
<?php namespace Croogo\Croogo\TestSuite; use Cake\TestSuite\Fixture\TestFixture; /** * CroogoTestFixture class * * @category TestSuite * @package Croogo * @version 1.4 * @author Fahad Ibnay Heylaal <contact@fahad19.com> * @author Rachman Chavik <rchavik@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @link http://www.croogo.org */ class CroogoTestFixture extends TestFixture { /** * _fixSequence * * @param Postgres $db */ protected function _fixSequence($db) { $sql = sprintf(" SELECT setval(pg_get_serial_sequence('%s', 'id'), (SELECT MAX(id) FROM %s))", $this->table, $this->table); $db->execute($sql); } /** * insert * * @param Object $db * @return array */ public function insert($db) { $result = parent::insert($db); if ($result === true && $db instanceof Postgres) { $this->_fixSequence($db); } return $result; } }