text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix mode +n specification so that it actually fires ever
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandmodify-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandmodify-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandpermission-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandpermission-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
Use strict equality for sanitized value comparison Fixes gh-9.
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { 'use strict'; var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keypress keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { return this.each(function(){ // the element(s) to be restricted var $this = $(this); $this.bind(inputEvents, function() { var val = $this.val(); var sanitizedVal = sanitizationFunc(val); if (val !== sanitizedVal) { $this.val(sanitizedVal); } }); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); }; })(jQuery);
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { 'use strict'; var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keypress keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { return this.each(function(){ // the element(s) to be restricted var $this = $(this); $this.bind(inputEvents, function() { var val = $this.val(); var sanitizedVal = sanitizationFunc(val); if (val != sanitizedVal) { $this.val(sanitizedVal); } }); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); }; })(jQuery);
Add method to read from filename
from astropy.table import Table import os class AuxService: renames = {} ignored_columns = [] transforms = {} basename = 'AUX_SERVICE' def __init__(self, auxdir='/fact/aux'): self.auxdir = auxdir self.filename_template = os.path.join( self.auxdir, '{date:%Y}', '{date:%m}', '{date:%d}', '{date:%Y%m%d}.' + self.basename + '.fits' ) def read_file(self, filename): df = Table.read(filename).to_pandas() df.drop(self.ignored_columns, axis=1, inplace=True) df.rename(columns=self.renames, inplace=True) for key, transform in self.transforms.items(): df[key] = transform(df[key]) return df def read_date(self, date): filename = self.filename_template.format(date=date) return self.read_file(filename)
from astropy.table import Table import os class AuxService: renames = {} ignored_columns = [] transforms = {} basename = 'AUX_SERVICE' def __init__(self, auxdir='/fact/aux'): self.auxdir = auxdir self.filename_template = os.path.join( self.auxdir, '{date:%Y}', '{date:%m}', '{date:%d}', '{date:%Y%m%d}.' + self.basename + '.fits' ) def read(self, date): filename = self.filename_template.format(date=date) df = Table.read(filename).to_pandas() df.drop(self.ignored_columns, axis=1, inplace=True) df.rename(columns=self.renames, inplace=True) for key, transform in self.transforms.items(): df[key] = transform(df[key]) return df
Make test failure on purpose
<?php namespace Tests\Functional; class QuoteTest extends BaseTestCase { public function testNumberOfCategories(){ $quote = new \Quote(null, null); $categories = $quote->getCategories(); $this->assertEquals(8, sizeof($categories)); } public function testCategoryListContainsManagement(){ $quote = new \Quote(null, null); $categories = $quote->getCategories(); $this->assertTrue(in_array("management", $categories)); } public function testQuoteClientFailsForInvalidCategory(){ try{ $quote = new \Quote("Invalid Category", null); $this->fail("Shouldn't have come here."); }catch(\Exception $e){ // expected } } }
<?php namespace Tests\Functional; class QuoteTest extends BaseTestCase { public function testNumberOfCategories(){ $quote = new \Quote(null, null); $categories = $quote->getCategories(); $this->assertEquals(5, sizeof($categories)); } public function testCategoryListContainsManagement(){ $quote = new \Quote(null, null); $categories = $quote->getCategories(); $this->assertTrue(in_array("management", $categories)); } public function testQuoteClientFailsForInvalidCategory(){ try{ $quote = new \Quote("Invalid Category", null); $this->fail("Shouldn't have come here."); }catch(\Exception $e){ // expected } } }
Revert "match system for hints should be "Confirmed" instead of "Accepted"" This reverts commit ee44143219ce33b9de7d65068f4ce5de094e2258.
/** * Copyright Intellectual Reserve, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.familysearch.platform.ct; import org.codehaus.enunciate.qname.XmlQNameEnum; import org.gedcomx.common.URI; /** * The way a match was resolved. */ @XmlQNameEnum ( base = XmlQNameEnum.BaseType.URI ) public enum MatchStatus { Pending, Accepted, Rejected; /** * Return the QName value for this enum. * * @return The QName value for this enum. */ public URI toQNameURI() { return URI.create(org.codehaus.enunciate.XmlQNameEnumUtil.toURIValue(this)); } /** * Get the enumeration from the QName. * * @param qname The qname. * @return The enumeration. */ public static MatchStatus fromQNameURI(URI qname) { return org.codehaus.enunciate.XmlQNameEnumUtil.fromURIValue(qname.toString(), MatchStatus.class); } }
/** * Copyright Intellectual Reserve, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.familysearch.platform.ct; import org.codehaus.enunciate.qname.XmlQNameEnum; import org.gedcomx.common.URI; /** * The way a match was resolved. */ @XmlQNameEnum ( base = XmlQNameEnum.BaseType.URI ) public enum MatchStatus { Pending, Confirmed, Rejected; /** * Return the QName value for this enum. * * @return The QName value for this enum. */ public URI toQNameURI() { return URI.create(org.codehaus.enunciate.XmlQNameEnumUtil.toURIValue(this)); } /** * Get the enumeration from the QName. * * @param qname The qname. * @return The enumeration. */ public static MatchStatus fromQNameURI(URI qname) { return org.codehaus.enunciate.XmlQNameEnumUtil.fromURIValue(qname.toString(), MatchStatus.class); } }
Remove 'only' that was hogging the test suites
/** * WPCOM module */ var util = require('./util'); var assert = require('assert'); /** * Testing data */ function trueAssertion( done ) { return function() { done(); }; } function trueCallback( callback ) { callback( null, true ); } function falseAssertion( done ) { return function() { done( new Error('Failed!')); }; } function falseCallback( callback ) { callback( true, null ); } function timedCallback( delay, caller = trueCallback ) { return function( params, callback ) { setTimeout( function() { return caller.apply(null, [params, callback] ); }, delay ); }; } /** * WPCOM Promises */ describe('wpcom', function(){ var wpcom = util.wpcom_public(); describe('wpcom.promises', function(){ it('should fail when slower than timeout', done => { wpcom.site(util.site()).postsList() .timeout( 10 ) .then( falseAssertion( done ) ) .catch( trueAssertion( done ) ); }); it('should still catch() with timeout()', done => { wpcom.site(util.site()).post(-5).get() .timeout( 10000 ) .then( falseAssertion( done ) ) .catch( trueAssertion( done ) ); }); }); });
/** * WPCOM module */ var util = require('./util'); var assert = require('assert'); /** * Testing data */ function trueAssertion( done ) { return function() { done(); }; } function trueCallback( callback ) { callback( null, true ); } function falseAssertion( done ) { return function() { done( new Error('Failed!')); }; } function falseCallback( callback ) { callback( true, null ); } function timedCallback( delay, caller = trueCallback ) { return function( params, callback ) { setTimeout( function() { return caller.apply(null, [params, callback] ); }, delay ); }; } /** * WPCOM Promises */ describe('wpcom', function(){ var wpcom = util.wpcom_public(); describe.only('wpcom.promises', function(){ it('should fail when slower than timeout', done => { wpcom.site(util.site()).postsList() .timeout( 10 ) .then( falseAssertion( done ) ) .catch( trueAssertion( done ) ); }); it('should still catch() with timeout()', done => { wpcom.site(util.site()).post(-5).get() .timeout( 10000 ) .then( falseAssertion( done ) ) .catch( trueAssertion( done ) ); }); }); });
Add CONTRIBUTING file to package description
import names from setuptools import setup, find_packages setup( name=names.__title__, version=names.__version__, author=names.__author__, url="https://github.com/treyhunner/names", description="Generate random names", long_description='\n\n'.join(( open('README.rst').read(), open('CHANGES.rst').read(), open('CONTRIBUTING.rst').read(), )), license=names.__license__, packages=find_packages(), package_data={'names': ['dist.*']}, include_package_data=True, entry_points={ 'console_scripts': [ 'names = names.main:main', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], test_suite='test_names', )
import names from setuptools import setup, find_packages setup( name=names.__title__, version=names.__version__, author=names.__author__, url="https://github.com/treyhunner/names", description="Generate random names", long_description='\n\n'.join(( open('README.rst').read(), open('CHANGES.rst').read(), )), license=names.__license__, packages=find_packages(), package_data={'names': ['dist.*']}, include_package_data=True, entry_points={ 'console_scripts': [ 'names = names.main:main', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], test_suite='test_names', )
Move hash algorithm to class constant This change makes the tests a bit more readable.
<?php namespace UoMCS\OpenBadges\Backend; class UtilityTest extends \PHPUnit_Framework_TestCase { const HASH_ALGORITHM = 'sha512'; public function testIdentityHashSalt() { $str = 'test'; $salt = 'salty'; $hash = '8d8e45e4dfcee6c5c0248d33717d87a3988817246db4f200b89bda0070444fd8f435638db28e6a8d0b2ce3d9d338c5871cf0f203f37ff678ac2a92a3cca6acd3'; $hash = self::HASH_ALGORITHM . '$' . $hash; $this->assertEquals($hash, Utility::identityHash($str, $salt)); } public function testIdentityHashNoSalt() { $str = 'test'; $hash = 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff'; $hash = self::HASH_ALGORITHM . '$' . $hash; $this->assertEquals($hash, Utility::identityHash($str)); } }
<?php namespace UoMCS\OpenBadges\Backend; class UtilityTest extends \PHPUnit_Framework_TestCase { public function testIdentityHashSalt() { $str = 'test'; $salt = 'salty'; $hash = 'sha512$8d8e45e4dfcee6c5c0248d33717d87a3988817246db4f200b89bda0070444fd8f435638db28e6a8d0b2ce3d9d338c5871cf0f203f37ff678ac2a92a3cca6acd3'; $this->assertEquals($hash, Utility::identityHash($str, $salt)); } public function testIdentityHashNoSalt() { $str = 'test'; $hash = 'sha512$ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff'; $this->assertEquals($hash, Utility::identityHash($str)); } }
Use skip combinators in example test.
<?php class ExamplesTest extends \PHPUnit_Framework_TestCase { public function testParsePhpLikeArrayExample() { $array_keyword = Parser::str('array'); $comma = Parser::char(','); $identifier = Parser::satisfyChar(function ($c) { return ctype_alnum($c); }); $item = Parser::many1($identifier); $items_list = Parser::product( Parser::many(Parser::skipR($item, $comma)), $item ); $open = Parser::char('('); $close = Parser::char(')'); $array = Parser::skipL( $array_keyword, Parser::skipR(Parser::skipL($open, $items_list), $close) ->or_(Parser::product($open, $close)) ); $t1 = 'array(lbas2d,aaa,aaaaa)'; $t2 = 'array(a,a,a)'; $t3 = 'array(9)'; $t4 = 'array()'; $test = function ($input) use ($array) { $this->assertEquals( new Good($input, strlen($input)), Parser::slice($array)->run($input), 'PHP-like array example' ); }; $test($t1); $test($t2); $test($t3); $test($t4); } }
<?php class ExamplesTest extends \PHPUnit_Framework_TestCase { public function testParsePhpLikeArrayExample() { $array_keyword = Parser::str('array'); $comma = Parser::char(','); $identifier = Parser::satisfyChar(function ($c) { return ctype_alnum($c); }); $item = Parser::many1($identifier); $items_list = Parser::product( Parser::many(Parser::product($item, $comma)), $item ); $open = Parser::char('('); $close = Parser::char(')'); $array = Parser::product( $array_keyword, Parser::product(Parser::product($open, $items_list), $close) ->or_(Parser::product($open, $close)) ); $t1 = 'array(lbas2d,aaa,aaaaa)'; $t2 = 'array(a,a,a)'; $t3 = 'array(9)'; $t4 = 'array()'; $test = function ($input) use ($array) { $this->assertEquals( new Good($input, strlen($input)), Parser::slice($array)->run($input), 'PHP-like array example' ); }; $test($t1); $test($t2); $test($t3); $test($t4); } }
Fix tags not being mutated
<?php namespace Vend\Statsd\Datadog; use Vend\Statsd\Metric as BaseMetric; class Metric extends BaseMetric { /** * @var array<string,string> */ protected $tags = []; public function __construct($key, $value, $type, array $tags = []) { parent::__construct($key, $value, $type); $this->setTags($tags); } public function setTags(array $tags = []) { $this->tags = $tags; } public function getData() { $result = parent::getData(); if (!empty($this->tags)) { $tags = []; array_walk($this->tags, function ($tagValue, $tagName) use (&$tags) { $tags[] = is_integer($tagName) ? $tagValue : $tagName . ':' . $tagValue; }); $result .= '|#' . implode(',', $tags); } return $result; } }
<?php namespace Vend\Statsd\Datadog; use Vend\Statsd\Metric as BaseMetric; class Metric extends BaseMetric { /** * @var array<string,string> */ protected $tags = []; public function __construct($key, $value, $type, array $tags = []) { parent::__construct($key, $value, $type); $this->setTags($tags); } public function setTags(array $tags = []) { $this->tags = $tags; } public function getData() { $result = parent::getData(); if (!empty($this->tags)) { $tags = []; array_walk($this->tags, function ($v, $k) { $tags[] = is_integer($k) ? $v : $k . ':' . $v; }); $result .= '|#' . implode(',', $tags); } return $result; } }
Add Domain class's shorthand name
'use strict' /** * @class Elastic */ var Elastic = { // like OOP klass : klass, // shorthand Layout : LayoutDomain, View : ViewDomain, Component: ComponentDomain, // classes domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
'use strict' /** * @class Elastic */ var Elastic = { klass : klass, domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
Remove per patch version classifiers
#!/usr/bin/env python from setuptools import setup import argparse_addons setup(name='argparse_addons', version=argparse_addons.__version__, description=('Additional argparse types and actions.'), long_description=open('README.rst', 'r').read(), author='Erik Moqvist', author_email='erik.moqvist@gmail.com', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', ], keywords=['argparse'], url='https://github.com/eerimoq/argparse_addons', py_modules=['argparse_addons'], python_requires='>=3.6', install_requires=[ ], test_suite="tests")
#!/usr/bin/env python from setuptools import setup import argparse_addons setup(name='argparse_addons', version=argparse_addons.__version__, description=('Additional argparse types and actions.'), long_description=open('README.rst', 'r').read(), author='Erik Moqvist', author_email='erik.moqvist@gmail.com', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], keywords=['argparse'], url='https://github.com/eerimoq/argparse_addons', py_modules=['argparse_addons'], python_requires='>=3.6', install_requires=[ ], test_suite="tests")
Copy debug alerts to browser console if flag set
/* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. */ $( function() { console.log( "pwm Password Manager (c) Copyright Owen Maule 2015 <o@owen-m.com> http://owen-m.com/" ); console.log( "Latest version: https://github.com/owenmaule/pwm Licence: GNU Affero General Public License" ); if( debugToConsole ) { // Transfer debug alerts to console $( "#alert .alert-debug" ).each( function() { console.log( 'debug: ' + $( this ).html() ); $( this ).hide(); } ); } } );
/* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. */ $( function() { console.log( "pwm Password Manager (c) Copyright Owen Maule 2015 <o@owen-m.com> http://owen-m.com/" ); console.log( "Latest version: https://github.com/owenmaule/pwm Licence: GNU Affero General Public License" ); } );
Fix login with oauth services
global.IPC = require('ipc') var events = ['unread-changed']; events.forEach(function(e) { window.addEventListener(e, function(event) { IPC.send(e, event.detail); }); }); require('./menus'); var shell = require('shell'); var supportExternalLinks = function (e) { var href; var isExternal = false; var checkDomElement = function (element) { if (element.nodeName === 'A') { href = element.getAttribute('href') || ''; } if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/) { isExternal = true; } if (href && isExternal) { shell.openExternal(href); e.preventDefault(); } else if (element.parentElement) { checkDomElement(element.parentElement); } } checkDomElement(e.target); } document.addEventListener('click', supportExternalLinks, false); windowOpen = window.open; window.open = function() { result = windowOpen.apply(this, arguments); result.closed = false; return result; }
global.IPC = require('ipc') var events = ['unread-changed']; events.forEach(function(e) { window.addEventListener(e, function(event) { IPC.send(e, event.detail); }); }); require('./menus'); var shell = require('shell'); var supportExternalLinks = function (e) { var href; var isExternal = false; var checkDomElement = function (element) { if (element.nodeName === 'A') { href = element.getAttribute('href') || ''; } if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/) { isExternal = true; } if (href && isExternal) { shell.openExternal(href); e.preventDefault(); } else if (element.parentElement) { checkDomElement(element.parentElement); } } checkDomElement(e.target); } document.addEventListener('click', supportExternalLinks, false);
Fix inflated view using parent view.
package jp.satorufujiwara.binder.recycler; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import jp.satorufujiwara.binder.Binder; import jp.satorufujiwara.binder.ViewType; public abstract class RecyclerBinder<V extends ViewType> implements Binder<V, RecyclerView.ViewHolder> { private final V mViewType; private Context mContext; protected RecyclerBinder(final Context context, final V viewType) { mContext = context; mViewType = viewType; } @LayoutRes public abstract int layoutResId(); public abstract RecyclerView.ViewHolder onCreateViewHolder(final View v); @Override public final RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent) { return onCreateViewHolder(LayoutInflater.from(mContext).inflate(layoutResId(), parent, false)); } @Override public void onViewRecycled(RecyclerView.ViewHolder holder) { // no op } @Override public void onRemoved() { mContext = null; } @Override public V getViewType() { return mViewType; } public final Context getContext() { return mContext; } }
package jp.satorufujiwara.binder.recycler; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import jp.satorufujiwara.binder.Binder; import jp.satorufujiwara.binder.ViewType; public abstract class RecyclerBinder<V extends ViewType> implements Binder<V, RecyclerView.ViewHolder> { private final V mViewType; private Context mContext; protected RecyclerBinder(final Context context, final V viewType) { mContext = context; mViewType = viewType; } @LayoutRes public abstract int layoutResId(); public abstract RecyclerView.ViewHolder onCreateViewHolder(final View v); @Override public final RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent) { return onCreateViewHolder(View.inflate(mContext, layoutResId(), null)); } @Override public void onViewRecycled(RecyclerView.ViewHolder holder) { // no op } @Override public void onRemoved() { mContext = null; } @Override public V getViewType() { return mViewType; } public final Context getContext() { return mContext; } }
Remove leading backslash from class name namespace before creating the type map
<?php namespace Papper\Internal; use Papper\MappingOptionsInterface; use Papper\TypeMap; /** * Class Configuration * * @author Vladimir Komissarov <dr0id@dr0id.ru> */ class Configuration { /** * @var TypeMap[] */ private $typeMaps = array(); /** * @var TypeMapFactory */ private $typeMapFactory; /** * @var MappingOptionsInterface */ private $mappingOptions; public function __construct() { $this->typeMapFactory = new TypeMapFactory(); $this->mappingOptions = new MappingOptions(); } public function getMappingOptions() { return $this->mappingOptions; } public function findTypeMap($sourceType, $destinationType) { $sourceType = ltrim($sourceType, '\\'); $destinationType = ltrim($destinationType, '\\'); $key = $this->computeTypePairHash($sourceType, $destinationType); return isset($this->typeMaps[$key]) ? $this->typeMaps[$key] : $this->typeMaps[$key] = $this->typeMapFactory->createTypeMap($sourceType, $destinationType, $this->mappingOptions); } public function getAllTypeMaps() { return $this->typeMaps; } private function computeTypePairHash($sourceType, $destinationType) { return $sourceType . '#' . $destinationType; } }
<?php namespace Papper\Internal; use Papper\MappingOptionsInterface; use Papper\TypeMap; /** * Class Configuration * * @author Vladimir Komissarov <dr0id@dr0id.ru> */ class Configuration { /** * @var TypeMap[] */ private $typeMaps = array(); /** * @var TypeMapFactory */ private $typeMapFactory; /** * @var MappingOptionsInterface */ private $mappingOptions; public function __construct() { $this->typeMapFactory = new TypeMapFactory(); $this->mappingOptions = new MappingOptions(); } public function getMappingOptions() { return $this->mappingOptions; } public function findTypeMap($sourceType, $destinationType) { $key = $this->computeTypePairHash($sourceType, $destinationType); return isset($this->typeMaps[$key]) ? $this->typeMaps[$key] : $this->typeMaps[$key] = $this->typeMapFactory->createTypeMap($sourceType, $destinationType, $this->mappingOptions); } public function getAllTypeMaps() { return $this->typeMaps; } private function computeTypePairHash($sourceType, $destinationType) { return ltrim($sourceType, '\\') . '#' . ltrim($destinationType, '\\'); } }
Update the event name in the test, too.
require('./common'); var DB_NAME = 'node-couchdb-test', callbacks = { A: false, B1: false, B2: false, C: false, }, db = client.db(DB_NAME); // Init fresh db db.remove(); db .create(function(er) { if (er) throw er; var stream = db.changesStream(); stream .addListener('data', function(change) { callbacks['B'+change.seq] = true; if (change.seq == 2) { stream.close(); } }) .addListener('end', function() { callbacks.C = true; }); }); db.saveDoc({test: 1}); db.saveDoc({test: 2}); db.changes({since: 1}, function(er, r) { if (er) throw er; callbacks.A = true; assert.equal(2, r.results[0].seq); assert.equal(1, r.results.length); }); process.addListener('exit', function() { checkCallbacks(callbacks); });
require('./common'); var DB_NAME = 'node-couchdb-test', callbacks = { A: false, B1: false, B2: false, C: false, }, db = client.db(DB_NAME); // Init fresh db db.remove(); db .create(function(er) { if (er) throw er; var stream = db.changesStream(); stream .addListener('change', function(change) { callbacks['B'+change.seq] = true; if (change.seq == 2) { stream.close(); } }) .addListener('end', function() { callbacks.C = true; }); }); db.saveDoc({test: 1}); db.saveDoc({test: 2}); db.changes({since: 1}, function(er, r) { if (er) throw er; callbacks.A = true; assert.equal(2, r.results[0].seq); assert.equal(1, r.results.length); }); process.addListener('exit', function() { checkCallbacks(callbacks); });
Add references to common and libclient, which will not be deployed to PyPi.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`setup` ==================== :Synopsis: Create egg. :Author: DataONE (Pippin) """ from setuptools import setup, find_packages import d1_client_cli setup( name='Python DataONE CLI', version=d1_client_cli.__version__, author='Roger Dahl, and the DataONE Development Team', author_email='developers@dataone.org', url='http://dataone.org', license='Apache License, Version 2.0', description='A DataONE Command-line interface', packages = find_packages(), # Dependencies that are available through PYPI / easy_install. install_requires = [ 'pyxb >= 1.1.3', ], dependency_links = [ 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Common-1.0.0c4-py2.6.egg', 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Client_Library-1.0.0c4-py2.6.egg', ] package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], } )
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`setup` ==================== :Synopsis: Create egg. :Author: DataONE (Pippin) """ from setuptools import setup, find_packages import d1_client_cli setup( name='Python DataONE CLI', version=d1_client_cli.__version__, author='Roger Dahl, and the DataONE Development Team', author_email='developers@dataone.org', url='http://dataone.org', license='Apache License, Version 2.0', description='A DataONE Command-line interface', packages=find_packages(), # Dependencies that are available through PYPI / easy_install. install_requires=[ 'pyxb >= 1.1.3', ], package_data={ # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], } )
provider/aws: Rename the Import aws_opsworks_stack import test The casing on the test name was causing it not to run with the entire test suite ``` % make testacc TEST=./builtin/providers/aws % TESTARGS='-run=TestAccAWSOpsworksStack' 2 ↵ ✹ ==> Checking that code complies with gofmt requirements... go generate $(go list ./... | grep -v /terraform/vendor/) 2016/10/03 16:43:07 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/aws -v -run=TestAccAWSOpsworksStack -timeout 120m === RUN TestAccAWSOpsworksStackImportBasic --- PASS: TestAccAWSOpsworksStackImportBasic (49.00s) === RUN TestAccAWSOpsworksStackNoVpc --- PASS: TestAccAWSOpsworksStackNoVpc (36.10s) === RUN TestAccAWSOpsworksStackVpc --- PASS: TestAccAWSOpsworksStackVpc (73.27s) PASS ok github.com/hashicorp/terraform/builtin/providers/aws158.385s ```
package aws import ( "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSOpsworksStackImportBasic(t *testing.T) { name := acctest.RandString(10) resourceName := "aws_opsworks_stack.tf-acc" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsOpsworksStackDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAwsOpsworksStackConfigVpcCreate(name), }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
package aws import ( "os" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSOpsWorksStack_importBasic(t *testing.T) { oldvar := os.Getenv("AWS_DEFAULT_REGION") os.Setenv("AWS_DEFAULT_REGION", "us-west-2") defer os.Setenv("AWS_DEFAULT_REGION", oldvar) name := acctest.RandString(10) resourceName := "aws_opsworks_stack.tf-acc" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsOpsworksStackDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAwsOpsworksStackConfigVpcCreate(name), }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
Fix for supporting special characters in the url.
import re as regex from django.conf.urls import patterns, url def build_patterns(modules, version): pattern_list = [] for module in modules: url_string = r'^' url_string += str(version) + r'/' # NOTE, the assumption here is that get_path() is an instance of the AnnotationBaseClass: url_string += module.get_path_abstract() + r'$' url_string = regex.sub(r'{', r'(?P<', url_string) url_string = regex.sub(r'}', r'>[^/]+)', url_string) url_string = regex.sub('[\?]?[/]?\$$', '/?$', url_string) pattern_list.append(url(url_string, module())) return patterns('', *pattern_list)
import re as regex from django.conf.urls import patterns, url def build_patterns(modules, version): pattern_list = [] for module in modules: url_string = r'^' url_string += str(version) + r'/' # NOTE, the assumption here is that get_path() is an instance of the AnnotationBaseClass: url_string += module.get_path_abstract() + r'$' url_string = regex.sub(r'{', r'(?P<', url_string) url_string = regex.sub(r'}', r'>[\w\s.@-]+)', url_string) url_string = regex.sub('[\?]?[/]?\$$', '/?$', url_string) pattern_list.append(url(url_string, module())) return patterns('', *pattern_list)
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows" This reverts commit d87c71142ba7bcc0d99d84886f3534dea7617b0c.
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins if os.environ.has_key('MAPNIK_INPUT_PLUGINS_DIRECTORY'): settings_dict['input_plugins'] = os.environ['MAPNIK_INPUT_PLUGINS_DIRECTORY'] else: settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() if os.environ.has_key('MAPNIK_FONT_DIRECTORY'): settings_dict['fonts'] = os.environ['MAPNIK_FONT_DIRECTORY'] else: settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
Modify test_process_list()'s expect sub-strings to be up-to-date. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@128697 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test some lldb platform commands. """ import os, time import unittest2 import lldb from lldbtest import * class PlatformCommandTestCase(TestBase): mydir = "platform" def test_help_platform(self): self.runCmd("help platform") def test_list(self): self.expect("platform list", patterns = ['^Available platforms:']) def test_process_list(self): self.expect("platform process list", substrs = ['PID', 'ARCH', 'NAME']) def test_status(self): self.expect("platform status", substrs = ['Platform', 'Triple', 'OS Version', 'Kernel', 'Hostname']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" Test some lldb platform commands. """ import os, time import unittest2 import lldb from lldbtest import * class PlatformCommandTestCase(TestBase): mydir = "platform" def test_help_platform(self): self.runCmd("help platform") def test_list(self): self.expect("platform list", patterns = ['^Available platforms:']) def test_process_list(self): self.expect("platform process list", substrs = ['PID', 'TRIPLE', 'NAME']) def test_status(self): self.expect("platform status", substrs = ['Platform', 'Triple', 'OS Version', 'Kernel', 'Hostname']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Add new function js execute_statment
var MBTilesPlugin = function() { }; MBTilesPlugin.prototype.open = function(params, onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "open", [params]); }; MBTilesPlugin.prototype.getMetadata = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_metadata", []); }; MBTilesPlugin.prototype.getMinZoom = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_min_zoom", []); }; MBTilesPlugin.prototype.getMaxZoom = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_max_zoom", []); }; MBTilesPlugin.prototype.getTile = function(params, onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_tile", [params]); }; MBTilesPlugin.prototype.getTile = function(params, onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "execute_statment", [params]); }; module.exports = MBTilesPlugin;
var MBTilesPlugin = function() { }; MBTilesPlugin.prototype.open = function(params, onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "open", [params]); }; MBTilesPlugin.prototype.getMetadata = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_metadata", []); }; MBTilesPlugin.prototype.getMinZoom = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_min_zoom", []); }; MBTilesPlugin.prototype.getMaxZoom = function(onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_max_zoom", []); }; MBTilesPlugin.prototype.getTile = function(params, onSuccess, onError) { return cordova.exec(onSuccess, onError, "MBTilesPlugin", "get_tile", [params]); }; module.exports = MBTilesPlugin;
Make the tooltips hide when they are clicked.
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { this.$el.fadeOut('fast', function() { this.$el.remove(); }); }, render: function() { $('a.weakening',this.$el).tooltip('hide'); $('a.supporting',this.$el).tooltip('hide'); this.$el.html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); $('a.supporting',this.$el).tooltip({'title':"This is relevant"}); $('a.weakening',this.$el).tooltip({'title':"This is not relevant", 'placement':'bottom'}); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { var self = this; self.$el.animate({"background-color": "#ffffe1"}, {duration: 2000, complete: function() { $(this).animate({"background-color": "#ffffff"}, 2000); }}); } });
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { this.$el.fadeOut('fast', function() { this.$el.remove(); }); }, render: function() { this.$el.html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); $('a.supporting',this.$el).tooltip({'title':"This is relevant"}); $('a.weakening',this.$el).tooltip({'title':"This is not relevant", 'placement':'bottom'}); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { var self = this; self.$el.animate({"background-color": "#ffffe1"}, {duration: 2000, complete: function() { $(this).animate({"background-color": "#ffffff"}, 2000); }}); } });
Update expectation for details/organism test
<?php namespace Tests\AppBundle\API\Details; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class OrganismTest extends WebserviceTestCase { public function testExecute() { $default_db = $this->default_db; $session = null; $organisms = $this->webservice->factory('details', 'organism'); $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42)); $results = $organisms->execute($parameterBag, $session); $expected = array( "fennec_id" => 42, "scientific_name" => "Trebouxiophyceae sp. TP-2016a", "eol_identifier" => "", "ncbi_identifier" => "3083" ); $this->assertEquals($expected, $results); } }
<?php namespace Tests\AppBundle\API\Details; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class OrganismTest extends WebserviceTestCase { public function testExecute() { $default_db = $this->default_db; $session = null; $organisms = $this->webservice->factory('details', 'organism'); $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42)); $results = $organisms->execute($parameterBag, $session); $expected = array( "organism_id" => 42, "scientific_name" => "Artocarpus pithecogallus", "rank" => "species", "common_name" => null, "eol_accession" => "", "ncbi_accession" => "1679377" ); $this->assertEquals($expected, $results); } }
Simplify usage of tags with name only
<?php declare(strict_types = 1); namespace Apitte\Core\Annotation\Controller; use Doctrine\Common\Annotations\Annotation\Target; use Doctrine\Common\Annotations\AnnotationException; /** * @Annotation * @Target({"CLASS", "METHOD"}) */ final class Tag { /** @var string */ private $name; /** @var string|null */ private $value; /** * @param mixed[] $values */ public function __construct(array $values) { if (isset($values['value']) && !isset($values['name'])) { $values['name'] = $values['value']; } if (!isset($values['name'])) { throw new AnnotationException('No @Tag name given'); } $name = $values['name']; if ($name === null || $name === '') { throw new AnnotationException('Empty @Tag name given'); } $this->name = $name; $this->value = $values['value'] ?? null; } public function getName(): string { return $this->name; } public function getValue(): ?string { return $this->value; } }
<?php declare(strict_types = 1); namespace Apitte\Core\Annotation\Controller; use Doctrine\Common\Annotations\Annotation\Target; use Doctrine\Common\Annotations\AnnotationException; /** * @Annotation * @Target({"CLASS", "METHOD"}) */ final class Tag { /** @var string */ private $name; /** @var string|null */ private $value; /** * @param mixed[] $values */ public function __construct(array $values) { if (!isset($values['name'])) { throw new AnnotationException('No @Tag name given'); } $name = $values['name']; if ($name === null || $name === '') { throw new AnnotationException('Empty @Tag name given'); } $this->name = $name; $this->value = $values['value'] ?? null; } public function getName(): string { return $this->name; } public function getValue(): ?string { return $this->value; } }
Change Django requirement to avoid 1.10 alpha
from setuptools import setup, find_packages setup( name = "open511-server", version = "0.1", url='', license = "", packages = find_packages(), install_requires = [ 'open511==0.5', 'lxml>=3.0,<=4.0', 'WebOb==1.5.1', 'python-dateutil==2.4.2', 'requests==2.8.1', 'pytz>=2015b', 'django-appconf==1.0.1', 'cssselect==0.9.1', 'Django>=1.9.2,<=1.9.99', 'jsonfield==1.0.3' ], entry_points = { 'console_scripts': [ 'open511-task-runner = open511_server.task_runner.task_runner' ] }, )
from setuptools import setup, find_packages setup( name = "open511-server", version = "0.1", url='', license = "", packages = find_packages(), install_requires = [ 'open511==0.5', 'lxml>=3.0,<=4.0', 'WebOb==1.5.1', 'python-dateutil==2.4.2', 'requests==2.8.1', 'pytz>=2015b', 'django-appconf==1.0.1', 'cssselect==0.9.1', 'Django>=1.9.2,<=1.10', 'jsonfield==1.0.3' ], entry_points = { 'console_scripts': [ 'open511-task-runner = open511_server.task_runner.task_runner' ] }, )
Add constructor with id, name and is_page values
package awesomefb.facebook; import org.bson.Document; import org.json.JSONObject; /** * Created by earl on 5/25/2015. */ public class User extends Entity { private String mName; private boolean mIsPage; public User(JSONObject reference) { super(reference); mName = reference.getString("name"); mIsPage = reference.has("category"); } public User(String id, String name, boolean isPage) { super(id); mName = name; mIsPage = isPage; } public String getName() { return mName; } public boolean isPage() { return mIsPage; } public Document toDocument() { return new Document("fb_id", getFacebookId()) .append("name", mName) .append("is_page", mIsPage) ; } }
package awesomefb.facebook; import com.mongodb.BasicDBObject; import org.bson.Document; import org.json.JSONObject; /** * Created by earl on 5/25/2015. */ public class User extends Entity { private String mName; private boolean mIsPage; /** * Saves user data into users collection, * returns DBObject with newly inserted id and some basic info (FB ID, name) * @param reference */ public User(JSONObject reference) { super(reference); mName = reference.getString("name"); mIsPage = reference.has("category"); } public String getName() { return mName; } public boolean isPage() { return mIsPage; } public Document toDocument() { return new Document("fb_id", getFacebookId()) .append("name", mName) .append("is_page", mIsPage) ; } }
Implement service to fetch charity data from spreadsheet https://trello.com/c/wjthoHP0/28-user-sbat-view-the-charity-contributions-done-per-month-by-the-company
class GetCharityData { getData(){ var CHARITY_DATA_ARRAY = []; var spreadsheetID = "1f1tFr7y62QS7IRWOC2nNR5HWsTO99Bna3d0Xv1PTPiY"; var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json"; fetch(url).then((response) => response.json()) .then((responseText) => { entry = responseText.feed.entry; entry.forEach(function(element){ CHARITY_DATA_ARRAY.push({amount: element.gsx$charityamount.$t, month: element.gsx$month.$t, year: element.gsx$year.$t, name: element.gsx$charityname.$t, description: element.gsx$charitydesc.$t, imageSource: element.gsx$charityimage.$t }); }); }) .catch((error) => { console.warn(error); }); return CHARITY_DATA_ARRAY; } } export default new GetCharityData();
class GetCharityData { getData(){ var CHARITY_DATA = [ {amount: '41,234', month: 'January', year: '2015', name: 'Charity:Water', description: 'Cool description that was so hard to come up with. Hence I ended up writing some random text that dosent make much text' ,imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/March2015/GiveIndia_education_march_2015.png'}, {amount: '41,234', month: 'February', year: '2015', name: 'Charity:Water', description: 'Cooler description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'}, {amount: '21,234', month: 'March', year: '2015', name: 'Charity:Water', description: 'Coolest description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'} ]; return CHARITY_DATA ; } } export default new GetCharityData();
Make Python example output identical to C++ and Java by removing redundant spaces. git-svn-id: 6df6fa3ddd728f578ea1442598151d5900a6ed44@65 630680e5-0e50-0410-840e-4b1c322b438d
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #:", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #:", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #:", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #: ", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #: ", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #: ", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
Remove default filter that breaks unknown users export filter
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
Remove left over comment from copy and pasting code :(
function updateTickets(tabId) { chrome.pageAction.hide(tabId); chrome.tabs.sendRequest(tabId, {supported: true}, function(supported) { if (supported == undefined) { chrome.pageAction.hide(tabId); } else { chrome.pageAction.show(tabId); } }); } function getTickets(callback) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendRequest(tabs[0].id, {tickets: true}, function(newTickets) { callback(newTickets); }); }); } chrome.tabs.onUpdated.addListener(function(tabId, change, tab) { if (change.status == "complete") { updateTickets(tab.id); } }); chrome.tabs.onSelectionChanged.addListener(function(tabId, info) { updateTickets(tabId); }); // Ensure the current selected tab is set up. chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { updateTickets(tabs[0].id); });
// Global accessor that the popup uses. function updateTickets(tabId) { chrome.pageAction.hide(tabId); chrome.tabs.sendRequest(tabId, {supported: true}, function(supported) { if (supported == undefined) { chrome.pageAction.hide(tabId); } else { chrome.pageAction.show(tabId); } }); } function getTickets(callback) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendRequest(tabs[0].id, {tickets: true}, function(newTickets) { callback(newTickets); }); }); } chrome.tabs.onUpdated.addListener(function(tabId, change, tab) { if (change.status == "complete") { updateTickets(tab.id); } }); chrome.tabs.onSelectionChanged.addListener(function(tabId, info) { updateTickets(tabId); }); // Ensure the current selected tab is set up. chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { updateTickets(tabs[0].id); });
Update channel mapping ot use process.cwd()
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var errors = require('./errors'); function getChannelMapping() { var mapping = process.env.CHANNEL_MAPPING; try { var jsonMapping = JSON.parse(mapping); return jsonMapping; } catch(e) { // Mapping might be given as a file path, try to find the file and JSON.parse it try { var mainFolder = process.cwd(); var mappingPath = path.resolve(mainFolder, mapping); mapping = JSON.parse(fs.readFileSync(mappingPath)); } catch(e) { throw new errors.ChannelMappingError(); } if (!_.isObject(mapping)) { throw new errors.ChannelMappingError(); } return mapping; } } module.exports = getChannelMapping();
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var errors = require('./errors'); function getChannelMapping() { var mapping = process.env.CHANNEL_MAPPING; try { var jsonMapping = JSON.parse(mapping); return jsonMapping; } catch(e) { // Mapping might be given as a file path, try to find the file and JSON.parse it try { var mainFolder = path.dirname(require.main.filename); var mappingPath = path.resolve(mainFolder, mapping); mapping = JSON.parse(fs.readFileSync(mappingPath)); } catch(e) { throw new errors.ChannelMappingError(); } if (!_.isObject(mapping)) { throw new errors.ChannelMappingError(); } return mapping; } } module.exports = getChannelMapping();
Fix create action response code
<?php /** * CreateAction class file. * @author Christoffer Lindqvist <christoffer.lindqvist@nordsoftware.com> * @copyright Copyright &copy; Nord Software 2014- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @package nordsoftware.yii-rest.actions */ namespace nordsoftware\yii_rest\actions; /** * CreateAction implements the REST API endpoint for creating a new model from the given data. */ class CreateAction extends Action { /** * Creates a new model. */ public function run() { /** @var \CActiveRecord $model */ $model = new $this->modelClass(); $model->attributes = \Yii::app()->getRequest()->getBodyParams(); $model->save(); $this->sendResponse($model, 201); } }
<?php /** * CreateAction class file. * @author Christoffer Lindqvist <christoffer.lindqvist@nordsoftware.com> * @copyright Copyright &copy; Nord Software 2014- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @package nordsoftware.yii-rest.actions */ namespace nordsoftware\yii_rest\actions; /** * CreateAction implements the REST API endpoint for creating a new model from the given data. */ class CreateAction extends Action { /** * Creates a new model. */ public function run() { /** @var \CActiveRecord $model */ $model = new $this->modelClass(); $model->attributes = \Yii::app()->getRequest()->getBodyParams(); $model->save(); $this->sendResponse($model); } }
Update Root URL config to set the default mapping
__author__ = 'ankesh' from django.conf.urls import patterns, include, url from django.http import HttpResponseRedirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'upload.views.home', name='home'), url(r'^$', lambda x: HttpResponseRedirect('/plots/avgVGRvsProcessorFamily/')), url(r'^upload/', include('fileupload.urls')), url(r'^plots/', include('plots.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) import os urlpatterns += patterns('', (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}), )
__author__ = 'ankesh' from django.conf.urls import patterns, include, url from django.http import HttpResponseRedirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'upload.views.home', name='home'), url(r'^$', lambda x: HttpResponseRedirect('/plots/avgVGRvsProcessor/')), url(r'^upload/', include('fileupload.urls')), url(r'^plots/', include('plots.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) import os urlpatterns += patterns('', (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}), )
Set the `foreign_key` attribute on the author belongsTo method When the user model has a custom primary key (e.g `user_id` instead of `id`) Laravel will attempt to guess the foreign key and local key on a `belongsTo` relationship. However if guesses incorrectly. In the case where the foreign key is `user_id` Laravel 5.4 will interpret the foreign key as `author_user_id`. Manually setting the foregin key to `author_id` fixes this.
<?php namespace Riari\Forum\Models\Traits; trait HasAuthor { /** * Relationship: Author. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function author() { return $this->belongsTo(config('forum.integration.user_model'), 'author_id'); } /** * Attribute: Author name. * * @return mixed */ public function getAuthorNameAttribute() { $attribute = config('forum.integration.user_name'); if (!is_null($this->author)) { return $this->author->$attribute; } return null; } }
<?php namespace Riari\Forum\Models\Traits; trait HasAuthor { /** * Relationship: Author. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function author() { return $this->belongsTo(config('forum.integration.user_model')); } /** * Attribute: Author name. * * @return mixed */ public function getAuthorNameAttribute() { $attribute = config('forum.integration.user_name'); if (!is_null($this->author)) { return $this->author->$attribute; } return null; } }
Update template request in set interface task
// Copyright 2016, EMC, Inc. 'use strict'; module.exports = { friendlyName: 'Set Interfaces', injectableName: 'Task.Set.Interfaces', implementsTask: 'Task.Base.Linux.Commands', options: { commands: [ { command: 'sudo python set_interfaces.py', downloadUrl: '{{ api.templates }}/set_interfaces.py?nodeId={{ task.nodeId }}' } ] }, properties: { os: { linux: { type: 'microkernel' } } } };
// Copyright 2016, EMC, Inc. 'use strict'; module.exports = { friendlyName: 'Set Interfaces', injectableName: 'Task.Set.Interfaces', implementsTask: 'Task.Base.Linux.Commands', options: { commands: [ { command: 'sudo python set_interfaces.py', downloadUrl: '/api/current/templates/set_interfaces.py' } ] }, properties: { os: { linux: { type: 'microkernel' } } } };
Test server maps to all interfaces. Add signal handler for cleaning up on SIGINT.
// Copyright 2014, Kevin Ko <kevin@faveset.com> package com.faveset.khttpserver; import java.io.IOException; import sun.misc.Signal; import sun.misc.SignalHandler; import com.faveset.log.OutputStreamLog; public class HttpServer { public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("<port>"); return; } int port = new Integer(args[0]); OutputStreamLog log = new OutputStreamLog(System.out); final com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer(); server.setLog(log); // Set up the signal handler. Signal.handle(new Signal("INT"), new SignalHandler() { @Override public void handle(Signal sig) { server.stop(); } }); server.listenAndServe("::", port); log.close(); } }
// Copyright 2014, Kevin Ko <kevin@faveset.com> package com.faveset.khttpserver; import java.io.IOException; import com.faveset.log.OutputStreamLog; public class HttpServer { public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("<port>"); return; } int port = new Integer(args[0]); OutputStreamLog log = new OutputStreamLog(System.out); com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer(); server.setLog(log); server.listenAndServe("127.0.0.1", port); log.close(); } }
Fix cart and item controllers
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Order\Model; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Model\TimestampableInterface; interface CommentInterface extends ResourceInterface, TimestampableInterface { /** * @return OrderInterface */ public function getOrder(); /** * @param OrderInterface $order */ public function setOrder(OrderInterface $order = null); /** * @return string */ public function getState(); /** * @param string $state */ public function setState($state); /** * @return string */ public function getComment(); /** * @param string $comment */ public function setComment($comment); /** * @return bool */ public function getNotifyCustomer(); /** * @param bool $notifyCustomer */ public function setNotifyCustomer($notifyCustomer); /** * @return null|string */ public function getAuthor(); /** * @param string $author */ public function setAuthor($author); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Order\Model; use Sylius\Component\Resource\Model\TimestampableInterface; interface CommentInterface extends TimestampableInterface { /** * @return OrderInterface */ public function getOrder(); /** * @param OrderInterface $order */ public function setOrder(OrderInterface $order = null); /** * @return string */ public function getState(); /** * @param string $state */ public function setState($state); /** * @return string */ public function getComment(); /** * @param string $comment */ public function setComment($comment); /** * @return bool */ public function getNotifyCustomer(); /** * @param bool $notifyCustomer */ public function setNotifyCustomer($notifyCustomer); /** * @return null|string */ public function getAuthor(); /** * @param string $author */ public function setAuthor($author); }
Set payments fetch type to eager
package com.centralnabanka.model; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; import java.util.List; @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @Entity @Table(name = "group_payment") public class GroupPayment extends Base { private String messageId; private String creditorSwiftCode; private String creditorAccountNumber; private String debtorSwiftCode; private String debtorAccountNumber; private BigDecimal total; private String valuteCode; private Date valuteDate; private Date paymentDate; private boolean settled = false; @OneToMany(mappedBy = "groupPayment", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List<PaymentRequest> paymentRequests; }
package com.centralnabanka.model; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.Table; import java.math.BigDecimal; import java.util.Date; import java.util.List; @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @Entity @Table(name = "group_payment") public class GroupPayment extends Base { private String messageId; private String creditorSwiftCode; private String creditorAccountNumber; private String debtorSwiftCode; private String debtorAccountNumber; private BigDecimal total; private String valuteCode; private Date valuteDate; private Date paymentDate; private boolean settled = false; @OneToMany(mappedBy = "groupPayment", cascade = CascadeType.ALL, orphanRemoval = true) private List<PaymentRequest> paymentRequests; }
Make last changes over to diary name
from threading import Thread try: from queue import Queue except ImportError: # python 2 from Queue import Queue class DiaryThread(Thread): """A thread for logging as to not disrupt the logged application""" def __init__(self, diary, name="Diary Logger"): """Construct a thread for logging :param diary: An Diary instance to handle logging :param name: A string to represent this thread """ Thread.__init__(self, name=name) self.daemon = True # py2 constructor requires explicit self.diary = diary self.queue = Queue() self.start() def add(self, event): """Add a logged event to queue for logging""" self.queue.put(event) def run(self): """Main for thread to run""" while True: self.diary.write(self.queue.get())
from threading import Thread try: from queue import Queue except ImportError: # python 2 from Queue import Queue class ElemThread(Thread): """A thread for logging as to not disrupt the logged application""" def __init__(self, elem, name="Elementary Logger"): """Construct a thread for logging :param elem: An Elementary instance to handle logging :param name: A string to represent this thread """ Thread.__init__(self, name=name) self.daemon = True # py2 constructor requires explicit self.elem = elem self.queue = Queue() self.start() def add(self, event): """Add a logged event to queue for logging""" self.queue.put(event) def run(self): """Main for thread to run""" while True: self.elem.write(self.queue.get())
Fix potential NPE in the code
package org.kohsuke.github; /** * A branch in a repository. * * @author Yusuke Kokubo */ public class GHBranch { private GitHub root; private GHRepository owner; private String name; private Commit commit; public static class Commit { String sha,url; } public GitHub getRoot() { return root; } /** * Repository that this branch is in. */ public GHRepository getOwner() { return owner; } public String getName() { return name; } /** * The commit that this branch currently points to. */ public String getSHA1() { return commit.sha; } @Override public String toString() { final String url = owner != null ? owner.getUrl().toString() : "unknown"; return "Branch:" + name + " in " + url; } /*package*/ GHBranch wrap(GHRepository repo) { this.owner = repo; this.root = repo.root; return this; } }
package org.kohsuke.github; /** * A branch in a repository. * * @author Yusuke Kokubo */ public class GHBranch { private GitHub root; private GHRepository owner; private String name; private Commit commit; public static class Commit { String sha,url; } public GitHub getRoot() { return root; } /** * Repository that this branch is in. */ public GHRepository getOwner() { return owner; } public String getName() { return name; } /** * The commit that this branch currently points to. */ public String getSHA1() { return commit.sha; } @Override public String toString() { return "Branch:" + name + " in " + owner.getUrl(); } /*package*/ GHBranch wrap(GHRepository repo) { this.owner = repo; this.root = repo.root; return this; } }
Use the ClientRegistry Method in screen register to make it allow the registry object supplier
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.*; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.screen.*; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class TestScreens { @SubscribeEvent public static void register(FMLClientSetupEvent event) { MainThreadWorker.run(() -> { ClientRegistry.registryScreen(TestContainers.BASIC, BasicTileEntityScreen::new); ClientRegistry.registryScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new); ClientRegistry.registryScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new); }); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.MainThreadWorker; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.screen.*; import net.minecraft.client.gui.ScreenManager; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class TestScreens { @SubscribeEvent public static void register(FMLClientSetupEvent event) { MainThreadWorker.run(() -> { ScreenManager.registerFactory(TestContainers.BASIC.get(), BasicTileEntityScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR.get(), BasicEnergyCreatorScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY.get(), BasicFluidInventoryScreen::new); }); } }
Make collab field consts plural and add new constant for RawTripData objects.
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLAB = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLAB = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLAB = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
Simplify the dependencies and wait on the chooseTemplate service (modal) to return the process to create.
(function (module) { module.controller('ProjectHomeController', ProjectHomeController); ProjectHomeController.$inject = ["project", "modalInstance", "templates", "$state"]; function ProjectHomeController(project, modalInstance, templates, $state) { var ctrl = this; ctrl.project = project; ctrl.chooseTemplate = chooseTemplate; ctrl.createSample = createSample; ///////////////////////// function chooseTemplate() { modalInstance.chooseTemplate(ctrl.project, templates).then(function(processTemplateName) { $state.go('projects.project.processes.create', {process: processTemplateName}); }); } function createSample() { $state.go('projects.project.processes.create', {process: 'As Received'}); } } }(angular.module('materialscommons')));
(function (module) { module.controller('ProjectHomeController', ProjectHomeController); ProjectHomeController.$inject = ["project", "modalInstance", "processTemplates", "$state"]; function ProjectHomeController(project, modalInstance, processTemplates, $state) { var ctrl = this; ctrl.project = project; ctrl.chooseTemplate = chooseTemplate; ctrl.createSample = createSample; ///////////////////////// function chooseTemplate() { modalInstance.chooseTemplate(ctrl.project); } function createSample() { var template = processTemplates.getTemplateByName('As Received'); processTemplates.setActiveTemplate(template); $state.go('projects.project.processes.create'); } } }(angular.module('materialscommons')));
Make sure variables don't pollute the global namespace.
$(function () { var isElementOnScreen = function($el, scrollTop) { // Get very bottom of element var elementBottom = $el.offset().top + $el.outerHeight(); // Get very top of element var elementTop = $el.offset().top - scrollTop; if (elementTop <= $(window).height() && elementBottom - scrollTop >= 0) { // Element is on-screen return true; } else { // Element is not on-screen return false; } } $('.js-scroll-to').on('click', function(e) { e.preventDefault(); var $target = $(this).attr('href'); $('body').animate({ scrollTop: $target.offset().top }); }); // Scroll effect on steps var $steps = $('.js-step, .js-learn-more'); $(window).on('scroll', function() { $steps.each(function() { var isOnScreen = isElementOnScreen($(this), ($(window).scrollTop() - 150)); if (isOnScreen && !$(this).hasClass('is-visible')) { $(this).addClass('is-visible'); } }); }); });
$(function () { var isElementOnScreen = function($el, scrollTop) { // Get very bottom of element elementBottom = $el.offset().top + $el.outerHeight(); // Get very top of element elementTop = $el.offset().top - scrollTop; if (elementTop <= $(window).height() && elementBottom - scrollTop >= 0) { // Element is on-screen return true; } else { // Element is not on-screen return false; } } $('.js-scroll-to').on('click', function(e) { e.preventDefault(); $target = $(this).attr('href'); $('body').animate({ scrollTop: $target.offset().top }); }); // Scroll effect on steps $steps = $('.js-step, .js-learn-more'); $(window).on('scroll', function() { $steps.each(function() { isOnScreen = isElementOnScreen($(this), ($(window).scrollTop() - 150)); if (isOnScreen && !$(this).hasClass('is-visible')) { $(this).addClass('is-visible'); } }); }); });
Add scipy to project requirements list
from setuptools import setup, find_packages setup( name='manifold', version='1.0.0', packages=find_packages(include=('manifold', 'manifold.*')), long_description=open('README.md').read(), include_package_data=True, install_requires=( 'numpy', 'scipy', 'matplotlib', 'sklearn', 'networkx', 'fake-factory', 'nose', 'nose-parameterized', 'coverage', 'radon', ), license='MIT', test_suite='tests.unit', classifiers=[ 'Programming Language :: Python', 'License :: MIT', 'Natural language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Topic :: Manifold Learning', ], requires=['networkx', 'numpy', 'sklearn', 'matplotlib', 'scipy'] )
from setuptools import setup, find_packages setup( name='manifold', version='1.0.0', packages=find_packages(include=('manifold', 'manifold.*')), long_description=open('README.md').read(), include_package_data=True, install_requires=( 'numpy', 'scipy', 'matplotlib', 'sklearn', 'networkx', 'fake-factory', 'nose', 'nose-parameterized', 'coverage', 'radon', ), license='MIT', test_suite='tests.unit', classifiers=[ 'Programming Language :: Python', 'License :: MIT', 'Natural language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Topic :: Manifold Learning', ], requires=['networkx', 'numpy', 'sklearn', 'matplotlib'] )
Fix bug regarding local config in webdisk.
<?php /* The MIT License (MIT) Copyright (c) 2015 Fernando Bevilacqua Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @include_once dirname(__FILE__).'/config.local.php'; include_once dirname(__FILE__).'/config.php'; include_once dirname(__FILE__).'/functions.php'; include_once dirname(__FILE__).'/../ide-web/globals.php'; ?>
<?php /* The MIT License (MIT) Copyright (c) 2015 Fernando Bevilacqua Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ include_once dirname(__FILE__).'/config.local.php'; include_once dirname(__FILE__).'/config.php'; include_once dirname(__FILE__).'/functions.php'; include_once dirname(__FILE__).'/../ide-web/globals.php'; ?>
Fix bug where .gitignore was not being generated
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') , pjson = require('./package.json') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } var paths = { basefiles: __dirname + '/assets/**/*', dotfiles: __dirname + '/assets/.*', gitignore: __dirname + '/assets/.gitignore' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create) gulp.src([paths.basefiles, paths.dotfiles, paths.gitignore]) .pipe(gulp.dest(process.cwd() + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version(pjson.version) .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('Scaffold out a new app with given name') .action(newProject) program.parse(process.argv);
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') , pjson = require('./package.json') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } var paths = { basefiles: __dirname + '/assets/**/*', dotfiles: __dirname + '/assets/.*' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create) gulp.src([paths.basefiles, paths.dotfiles]) .pipe(gulp.dest(process.cwd() + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version(pjson.version) .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('Scaffold out a new app with given name') .action(newProject) program.parse(process.argv);
Add empty default value for model actions
import React, { Component } from 'react'; import { connect } from "react-redux"; import {FormGroup, InputGroup, TextArea} from "@blueprintjs/core"; import { updateModel } from "../../redux/actions"; class ModelGroup extends Component { render() { const { name, generator, actions, updateModel} = this.props; return ( <> <FormGroup label="Model Name"> <InputGroup placeholder="Model Name" value={name} onChange={({ target: { value }}) => updateModel('name', value)}/> </FormGroup> <FormGroup label="Model Generator"> <InputGroup placeholder="Model Generator" value={generator} onChange={({ target: { value }}) => updateModel('generator', value)}/> </FormGroup> <FormGroup label="Model Actions"> <div className="bp3-input-group"> <TextArea value={actions.join("\n")} onChange={({ target: { value }}) => updateModel('actions', value.split("\n"))}/> </div> </FormGroup> </> ) } } const mapStateToProps = ({ test: { models, selectedModelIndex }}) => { const { name, generator, actions = [] } = models[selectedModelIndex]; return { name, generator, actions } }; export default connect(mapStateToProps, { updateModel })(ModelGroup);
import React, { Component } from 'react'; import { connect } from "react-redux"; import {FormGroup, InputGroup, TextArea} from "@blueprintjs/core"; import { updateModel } from "../../redux/actions"; class ModelGroup extends Component { render() { const { name, generator, actions, updateModel} = this.props; return ( <> <FormGroup label="Model Name"> <InputGroup placeholder="Model Name" value={name} onChange={({ target: { value }}) => updateModel('name', value)}/> </FormGroup> <FormGroup label="Model Generator"> <InputGroup placeholder="Model Generator" value={generator} onChange={({ target: { value }}) => updateModel('generator', value)}/> </FormGroup> <FormGroup label="Model Actions"> <div className="bp3-input-group"> <TextArea value={actions.join("\n")} onChange={({ target: { value }}) => updateModel('actions', value.split("\n"))}/> </div> </FormGroup> </> ) } } const mapStateToProps = ({ test: { models, selectedModelIndex }}) => { const { name, generator, actions } = models[selectedModelIndex]; return { name, generator, actions } }; export default connect(mapStateToProps, { updateModel })(ModelGroup);
Use abstract.Abstract instead of Base alias when testing pygrapes.serializer.abstract.Abstract class
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # hack for loading modules # import _path _path.fix() ## # python standard library # from functools import partial import unittest ## # pygrapes modules # from pygrapes.serializer.abstract import Abstract class AbstractSerializerTestCase(unittest.TestCase): def test_method_dumps_exists(self): self.assertTrue(hasattr(Abstract(), 'dumps')) def test_method_dumps_expects_one_arg(self): self.assertRaises(TypeError, Abstract().dumps) def test_dumps_method_must_be_implemented(self): self.assertRaises(NotImplementedError, partial(Abstract().dumps, 1)) def test_method_loads_exists(self): self.assertTrue(hasattr(Abstract(), 'loads')) def test_method_loads_expects_one_arg(self): self.assertRaises(TypeError, Abstract().loads) def test_loads_method_must_be_implemented(self): self.assertRaises(NotImplementedError, partial(Abstract().loads, 1)) if "__main__" == __name__: unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # hack for loading modules # import _path _path.fix() ## # python standard library # from functools import partial import unittest ## # pygrapes modules # from pygrapes.serializer import Base class BaseSerializerTestCase(unittest.TestCase): def test_method_dumps_exists(self): self.assertTrue(hasattr(Base(), 'dumps')) def test_method_dumps_expects_one_arg(self): self.assertRaises(TypeError, Base().dumps) def test_dumps_method_must_be_implemented(self): self.assertRaises(NotImplementedError, partial(Base().dumps, 1)) def test_method_loads_exists(self): self.assertTrue(hasattr(Base(), 'loads')) def test_method_loads_expects_one_arg(self): self.assertRaises(TypeError, Base().loads) def test_loads_method_must_be_implemented(self): self.assertRaises(NotImplementedError, partial(Base().loads, 1)) if "__main__" == __name__: unittest.main()
Fix test creating crawl job
<?php namespace SimplyTestable\ApiBundle\Tests\Command\Task\AssignmentSelectionCommand; use SimplyTestable\ApiBundle\Tests\BaseSimplyTestableTestCase; class UrlDiscoverySelectionTest extends BaseSimplyTestableTestCase { const WORKER_TASK_ASSIGNMENT_FACTOR = 2; public static function setUpBeforeClass() { self::setupDatabaseIfNotExists(); } public function testUrlDiscoveryTaskIsSelectedForAssigment() { $this->createWorkers(1); $this->setHttpFixtures($this->getHttpFixtures($this->getFixturesDataPath(__FUNCTION__). '/HttpResponses')); $canonicalUrl = 'http://example.com/'; $job = $this->getJobService()->getById($this->createAndPrepareJob($canonicalUrl)); $crawlJobContainer = $this->getCrawlJobContainerService()->getForJob($job); $this->getCrawlJobContainerService()->prepare($crawlJobContainer); $this->assertEquals(0, $this->runConsole('simplytestable:task:assign:select')); $this->assertEquals('task-queued-for-assignment', $crawlJobContainer->getCrawlJob()->getTasks()->first()->getState()->getName()); } }
<?php namespace SimplyTestable\ApiBundle\Tests\Command\Task\AssignmentSelectionCommand; use SimplyTestable\ApiBundle\Tests\BaseSimplyTestableTestCase; class UrlDiscoverySelectionTest extends BaseSimplyTestableTestCase { const WORKER_TASK_ASSIGNMENT_FACTOR = 2; public static function setUpBeforeClass() { self::setupDatabaseIfNotExists(); } public function testUrlDiscoveryTaskIsSelectedForAssigment() { $this->createWorkers(1); $this->setHttpFixtures($this->getHttpFixtures($this->getFixturesDataPath(__FUNCTION__). '/HttpResponses')); $canonicalUrl = 'http://example.com/'; $job = $this->getJobService()->getById($this->createAndPrepareJob($canonicalUrl)); $crawlJobContainer = $this->getCrawlJobContainerService()->create($job); $this->getCrawlJobContainerService()->prepare($crawlJobContainer); $this->assertEquals(0, $this->runConsole('simplytestable:task:assign:select')); $this->assertEquals('task-queued-for-assignment', $crawlJobContainer->getCrawlJob()->getTasks()->first()->getState()->getName()); } }
Use the correct Kinvey class
import { Kinvey } from './kinvey'; import { KinveyRackManager } from 'kinvey-javascript-sdk-core/dist/rack/rack'; import { CacheMiddleware as CoreCacheMiddleware } from 'kinvey-javascript-sdk-core/dist/rack/cache'; import { CacheMiddleware } from './cache'; import { HttpMiddleware as CoreHttpMiddleware } from 'kinvey-javascript-sdk-core/dist/rack/http'; import { HttpMiddleware } from './http'; import { Device } from './device'; import { Popup } from './popup'; // Swap Cache Middelware const cacheRack = KinveyRackManager.cacheRack; cacheRack.swap(CoreCacheMiddleware, new CacheMiddleware()); // Swap Http middleware const networkRack = KinveyRackManager.networkRack; networkRack.swap(CoreHttpMiddleware, new HttpMiddleware()); // Expose some globals global.KinveyDevice = Device; global.KinveyPopup = Popup; // Export module.exports = Kinvey;
import { Kinvey } from 'kinvey-javascript-sdk-core/dist/kinvey'; import { KinveyRackManager } from 'kinvey-javascript-sdk-core/dist/rack/rack'; import { CacheMiddleware as CoreCacheMiddleware } from 'kinvey-javascript-sdk-core/dist/rack/cache'; import { CacheMiddleware } from './cache'; import { HttpMiddleware as CoreHttpMiddleware } from 'kinvey-javascript-sdk-core/dist/rack/http'; import { HttpMiddleware } from './http'; import { Device } from './device'; import { Popup } from './popup'; // Swap Cache Middelware const cacheRack = KinveyRackManager.cacheRack; cacheRack.swap(CoreCacheMiddleware, new CacheMiddleware()); // Swap Http middleware const networkRack = KinveyRackManager.networkRack; networkRack.swap(CoreHttpMiddleware, new HttpMiddleware()); // Expose some globals global.KinveyDevice = Device; global.KinveyPopup = Popup; // Export module.exports = Kinvey;
Change resp processing to cassandra -- need to fix tests for postgres
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = 'cassandra' SENTRY_DSN = None USE_FLUENTD = False CASSANDRA_URI = ['127.0.0.1'] CASSANDRA_KEYSPACE = 'scrapi' ELASTIC_URI = 'localhost:9200' ELASTIC_TIMEOUT = 10 ELASTIC_INDEX = 'share' PLOS_API_KEY = 'fakekey' HARVARD_DATAVERSE_API_KEY = 'anotherfakekey' disabled = ['stepic', 'shareok'] FRONTEND_KEYS = [ u'description', u'contributors', u'tags', u'raw', u'title', u'id', u'source', u'dateUpdated' ]
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = 'postgres' SENTRY_DSN = None USE_FLUENTD = False CASSANDRA_URI = ['127.0.0.1'] CASSANDRA_KEYSPACE = 'scrapi' ELASTIC_URI = 'localhost:9200' ELASTIC_TIMEOUT = 10 ELASTIC_INDEX = 'share' PLOS_API_KEY = 'fakekey' HARVARD_DATAVERSE_API_KEY = 'anotherfakekey' disabled = ['stepic', 'shareok'] FRONTEND_KEYS = [ u'description', u'contributors', u'tags', u'raw', u'title', u'id', u'source', u'dateUpdated' ]
Use post.title for page title
'use strict'; var React = require('react'); var paths = require('../paths'); module.exports = { contextTypes: function() { return { getCurrentPathname: React.PropTypes.func.isRequired, getCurrentParams: React.PropTypes.func.isRequired, }; }, getAllPosts: function () { return paths.allPosts(); }, getAllPages: function() { return paths.getPages(); }, getPost: function() { var params = this.context.getCurrentParams(); var post = params.post; var splat = params.splat; if(splat) { return this.getPostForPath(splat + '/' + post); } return this.getPostForPath(post); }, getPage: function() { // remove leading slash return this.getPageForPath(this.context.getCurrentPath().slice(1)); }, getPostForPath: function(path) { return paths.postForPath(path); }, getPageForPath: function(path) { return paths.pageForPath(path); }, getPageTitle: function() { var post = this.getPost(); if(post && post.title) { return post.title; } var routes = this.context.getCurrentRoutes(); var routeName = routes[routes.length - 1].name; if(routeName) { return routeName.replace('/', ''); } return ''; }, };
'use strict'; var React = require('react'); var paths = require('../paths'); module.exports = { contextTypes: function() { return { getCurrentPathname: React.PropTypes.func.isRequired, getCurrentParams: React.PropTypes.func.isRequired, }; }, getAllPosts: function () { return paths.allPosts(); }, getAllPages: function() { return paths.getPages(); }, getPost: function() { var params = this.context.getCurrentParams(); var post = params.post; var splat = params.splat; if(splat) { return this.getPostForPath(splat + '/' + post); } return this.getPostForPath(post); }, getPage: function() { // remove leading slash return this.getPageForPath(this.context.getCurrentPath().slice(1)); }, getPostForPath: function(path) { return paths.postForPath(path); }, getPageForPath: function(path) { return paths.pageForPath(path); }, getPageTitle: function() { var post = this.getPost(); if(post && post.name) { return post.name; } var routes = this.context.getCurrentRoutes(); var routeName = routes[routes.length - 1].name; if(routeName) { return routeName.replace('/', ''); } return ''; }, };
Make alignment a canOnlyBe type
<?php namespace Common\BlockEditor\Blocks; final class QuoteBlock extends AbstractBlock { public function getConfig(): array { return [ 'class' => 'BlockEditor.blocks.Quote', ]; } public function getValidation(): array { return [ 'text' => [ 'type' => 'string', 'required' => true, 'allowedTags' => 'b,i,a[href]', ], 'caption' => [ 'type' => 'string', 'required' => true, 'allowedTags' => 'b,i,a[href]', ], 'alignment' => [ 'canBeOnly' => '["left", "center"]', ], ]; } public function parse(array $data): string { return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data); } public function getJavaScriptUrl(): ?string { return null; } }
<?php namespace Common\BlockEditor\Blocks; final class QuoteBlock extends AbstractBlock { public function getConfig(): array { return [ 'class' => 'BlockEditor.blocks.Quote', ]; } public function getValidation(): array { return [ 'text' => [ 'type' => 'string', 'required' => true, 'allowedTags' => 'b,i,a[href]', ], 'caption' => [ 'type' => 'string', 'required' => true, 'allowedTags' => 'b,i,a[href]', ], 'alignment' => [ 'type' => 'string', ], ]; } public function parse(array $data): string { return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data); } public function getJavaScriptUrl(): ?string { return null; } }
Fix bug with domain warning
var SearchStats = { timeout: null, init: function() { var self = this; if (!SEARCH_STATS_URL) { return; } EventSystem.addEventListener('new_search_executed', function(q) { if (self.timeout) { clearTimeout(self.timeout); } self.timeout = setTimeout(function() { $.post(SEARCH_STATS_URL + '/entries', {q: q}, function(data) { console.log(data); }); }, 5000); }); } };
var SearchStats = { timeout: null, init: function() { self = this; if (!SEARCH_STATS_URL) { return; } EventSystem.addEventListener('new_search_executed', function(q) { if (self.timeout) { clearTimeout(self.timeout); } self.timeout = setTimeout(function() { $.post(SEARCH_STATS_URL + '/entries', {q: q}, function(data) { console.log(data); }); }, 5000); }); } };
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
from pyecmd import * extensions = {} if hasattr(ecmd, "fapi2InitExtension"): extensions["fapi2"] = "ver1" with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version if "fapi2" in extensions: try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
from pyecmd import * with Ecmd(fapi2="ver1"): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
Send start message to channel.
package main import ( "fmt" "io" "io/ioutil" "net/http" "os" "strings" "time" ) func main() { start := time.Now() ch := make(chan string) for _, url := range os.Args[1:] { if !strings.HasPrefix(url, "http://") { url = "http://" + url } go fetch(url, ch) } for range os.Args[1:] { fmt.Println(<-ch) } fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds()) } func fetch(url string, ch chan<- string) { ch <- fmt.Sprintf("Fetching %s...", url) start := time.Now() resp, err := http.Get(url) if err != nil { ch <- fmt.Sprint(err) return } nbytes, err := io.Copy(ioutil.Discard, resp.Body) resp.Body.Close() if err != nil { ch <- fmt.Sprintf("while reading %s: %v", url, err) return } secs := time.Since(start).Seconds() ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) }
package main import ( "fmt" "io" "io/ioutil" "net/http" "os" "strings" "time" ) func main() { start := time.Now() ch := make(chan string) for _, url := range os.Args[1:] { if !strings.HasPrefix(url, "http://") { url = "http://" + url } go fetch(url, ch) } for range os.Args[1:] { fmt.Println(<-ch) } fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds()) } func fetch(url string, ch chan<- string) { start := time.Now() resp, err := http.Get(url) if err != nil { ch <- fmt.Sprint(err) return } nbytes, err := io.Copy(ioutil.Discard, resp.Body) resp.Body.Close() if err != nil { ch <- fmt.Sprintf("while reading %s: %v", url, err) return } secs := time.Since(start).Seconds() ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) }
Remove blank line from qunit test file
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %> // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
Set default locale in test to avoid test failures when different default is used than expected.
# -*- coding: utf-8 -*- """ Unit Test: orchard.app """ import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') app.config['BABEL_DEFAULT_LOCALE'] = 'en' self.app_context = app.app_context() self.app_context.push() self.client = app.test_client(use_cookies = True) def tearDown(self): self.app_context.pop() def test_index(self): response = self.client.get('/') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard!' in data) response = self.client.get('/BMeu') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard, BMeu!' in data)
# -*- coding: utf-8 -*- """ Unit Test: orchard.app """ import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') self.app_context = app.app_context() self.app_context.push() self.client = app.test_client(use_cookies = True) def tearDown(self): self.app_context.pop() def test_index(self): response = self.client.get('/') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard!' in data) response = self.client.get('/BMeu') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard, BMeu!' in data)
Fix {get,set}Object not being available on 2D items
package org.squiddev.plethora.gameplay.modules.glasses.objects; import net.minecraft.item.Item; import org.squiddev.plethora.api.method.MethodResult; import org.squiddev.plethora.api.method.wrapper.FromTarget; import org.squiddev.plethora.api.method.wrapper.Optional; import org.squiddev.plethora.api.method.wrapper.PlethoraMethod; import javax.annotation.Nonnull; /** * An object which contains an item. */ public interface ItemObject { @Nonnull Item getItem(); void setItem(@Nonnull Item item); int getDamage(); void setDamage(int damage); @PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false) static MethodResult getItem(@FromTarget ItemObject object) { return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage()); } @PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false) static void setItem(@FromTarget ItemObject object, Item item, @Optional(defInt = 0) int damage) { object.setItem(item); object.setDamage(damage); } }
package org.squiddev.plethora.gameplay.modules.glasses.objects; import net.minecraft.item.Item; import org.squiddev.plethora.api.method.MethodResult; import org.squiddev.plethora.api.method.wrapper.FromTarget; import org.squiddev.plethora.api.method.wrapper.Optional; import org.squiddev.plethora.api.method.wrapper.PlethoraMethod; import org.squiddev.plethora.gameplay.modules.glasses.objects.object3d.Item3D; import javax.annotation.Nonnull; /** * An object which contains an item. */ public interface ItemObject { @Nonnull Item getItem(); void setItem(@Nonnull Item item); int getDamage(); void setDamage(int damage); @PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false) static MethodResult getItem(@FromTarget Item3D object) { return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage()); } @PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false) static void setItem(@FromTarget Item3D object, Item item, @Optional(defInt = 0) int damage) { object.setItem(item); object.setDamage(damage); } }
Set upscale to True by default for admin asset
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False, 'upscale': True, }, } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False)
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False } } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False)
Add another test case - add multiple words
import nose from lib.wordfilter import Wordfilter # Run with `python -m test.wordfilter_test` class Wordfilter_test: def setup(self): self.wordfilter = Wordfilter() def teardown(self): self.wordfilter = [] def test_loading(self): assert type(self.wordfilter.blacklist) is list def test_badWords(self): assert self.wordfilter.blacklisted('this string contains the word skank') assert self.wordfilter.blacklisted('this string contains the word SkAnK') assert self.wordfilter.blacklisted('this string contains the wordskank') assert self.wordfilter.blacklisted('this string contains the skankword') assert not self.wordfilter.blacklisted('this string is clean!') def test_addWords(self): self.wordfilter.addWords(['clean']) assert self.wordfilter.blacklisted('this string contains the word skank') assert self.wordfilter.blacklisted('this string is clean!') def test_clearList(self): self.wordfilter.clearList() assert not self.wordfilter.blacklisted('this string contains the word skank') self.wordfilter.addWords(['skank']) assert self.wordfilter.blacklisted('this string contains the word skank') def test_add_multiple_words(self): # Arrange self.wordfilter.clearList() # Act self.wordfilter.addWords(['zebra','elephant']) # Assert assert self.wordfilter.blacklisted('this string has zebra in it') assert self.wordfilter.blacklisted('this string has elephant in it') assert not self.wordfilter.blacklisted('this string has nothing in it') if __name__ == "__main__": nose.main()
import nose from lib.wordfilter import Wordfilter # Run with `python -m test.wordfilter_test` class Wordfilter_test: def setup(self): self.wordfilter = Wordfilter() def teardown(self): self.wordfilter = [] def test_loading(self): assert type(self.wordfilter.blacklist) is list def test_badWords(self): assert self.wordfilter.blacklisted('this string contains the word skank') assert self.wordfilter.blacklisted('this string contains the word SkAnK') assert self.wordfilter.blacklisted('this string contains the wordskank') assert self.wordfilter.blacklisted('this string contains the skankword') assert not self.wordfilter.blacklisted('this string is clean!') def test_addWords(self): self.wordfilter.addWords(['clean']) assert self.wordfilter.blacklisted('this string contains the word skank') assert self.wordfilter.blacklisted('this string is clean!') def test_clearList(self): self.wordfilter.clearList(); assert not self.wordfilter.blacklisted('this string contains the word skank') self.wordfilter.addWords(['skank']) assert self.wordfilter.blacklisted('this string contains the word skank') if __name__ == "__main__": nose.main()
Remove turbo links since it messes up my unskilled javascript.
// 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 vendor/assets/javascripts of plugins, if any, 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/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require local_time //= require jquery.purr //= require best_in_place $(document).ready(function() { /* Activating Best In Place */ jQuery(".best_in_place").best_in_place() }); $(document).ready(function() { $('img').each( function() { var o = $(this); if( ! o.attr('title') && o.attr('alt') ) o.attr('title', o.attr('alt') ); }); });
// 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 vendor/assets/javascripts of plugins, if any, 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/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require turbolinks //= require jquery //= require jquery_ujs //= require jquery.turbolinks //= require local_time //= require jquery.purr //= require best_in_place $(document).ready(function() { /* Activating Best In Place */ jQuery(".best_in_place").best_in_place() }); $(document).ready(function() { $('img').each( function() { var o = $(this); if( ! o.attr('title') && o.attr('alt') ) o.attr('title', o.attr('alt') ); }); });
Remove common domain from prod env to get staging to work
(function() { 'use strict'; angular .module('davisCru') .config(config); /** @ngInject */ function config($logProvider, envServiceProvider) { envServiceProvider.config({ domains: { development: ['localhost', 'staging.daviscru.com', 'staging.daviscru.divshot.io'], production: ['daviscru.com', 'www.daviscru.com', 'production.daviscru.divshot.io'] }, vars: { development: { firebaseUrl: 'https://daviscru-staging.firebaseio.com/' }, production: { firebaseUrl: 'https://daviscru.firebaseio.com/' } } }); // run the environment check, so the comprobation is made // before controllers and services are built envServiceProvider.check(); if (envServiceProvider.is('production')) { /// Disable log $logProvider.debugEnabled(false); } else { // Enable log $logProvider.debugEnabled(true); } } })();
(function() { 'use strict'; angular .module('davisCru') .config(config); /** @ngInject */ function config($logProvider, envServiceProvider) { envServiceProvider.config({ domains: { development: ['localhost', 'staging.daviscru.com', 'staging.daviscru.divshot.io'], production: ['daviscru.com', 'www.daviscru.com', 'production.daviscru.divshot.io', 'daviscru.divshot.io'] }, vars: { development: { firebaseUrl: 'https://daviscru-staging.firebaseio.com/' }, production: { firebaseUrl: 'https://daviscru.firebaseio.com/' } } }); // run the environment check, so the comprobation is made // before controllers and services are built envServiceProvider.check(); if (envServiceProvider.is('production')) { /// Disable log $logProvider.debugEnabled(false); } else { // Enable log $logProvider.debugEnabled(true); } } })();
Add flag for dumping a specific field. Only ID field is supported right now. Others can be added very easily.
package main import ( "code.google.com/p/goprotobuf/proto" "flag" "fmt" "github.com/rootsdev/fsbff/fs_data" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { var numRecords = flag.Int("n", 10, "number of records to dump") var field = flag.String("f", "", "field to dump: [a]ll, [i]d") flag.Parse() file, err := os.Open(flag.Arg(0)) check(err) defer file.Close() bytes, err := ioutil.ReadAll(file) check(err) fsPersons := &fs_data.FamilySearchPersons{} err = proto.Unmarshal(bytes, fsPersons) check(err) for i := 0; i < *numRecords; i++ { switch *field { case "i": fmt.Printf("%s\n", fsPersons.Persons[i].GetId()) default: fmt.Printf("fsPersons[%d]=%+v\n\n", i, fsPersons.Persons[i]) } } }
package main import ( "code.google.com/p/goprotobuf/proto" "flag" "fmt" "github.com/rootsdev/fsbff/fs_data" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { var numRecords = flag.Int("n", 10, "number of records to dump") flag.Parse() file, err := os.Open(flag.Arg(0)) check(err) defer file.Close() bytes, err := ioutil.ReadAll(file) check(err) fsPersons := &fs_data.FamilySearchPersons{} err = proto.Unmarshal(bytes, fsPersons) check(err) for i := 0; i < *numRecords; i++ { fmt.Printf("fsPersons[%d]=%+v\n\n", i, fsPersons.Persons[i]) } }
Make thread non-daemon so we don't partially process message. LWR should still stop properly since loop is tracking if manager is alive.
from lwr.managers import status from lwr.lwr_client import amqp_exchange from lwr import manager_endpoint_util import threading import logging log = logging.getLogger(__name__) def bind_manager_to_queue(manager, queue_state, connection_string): lwr_exchange = amqp_exchange.LwrExchange(connection_string, manager.name) def process_messages(body, message): __process_message(manager, body, message) def drain(): __drain(queue_state, lwr_exchange, process_messages) thread_name = "consumer-%s" % connection_string thread = threading.Thread(name=thread_name, target=drain) thread.daemon = False thread.start() # TODO: Think through job recovery, jobs shouldn't complete until after bind # has occurred. def bind_on_status_change(new_status, job_id): payload = manager_endpoint_util.full_status(manager, new_status, job_id) lwr_exchange.publish("status_update", payload) manager.set_state_change_callback(bind_on_status_change) def __drain(queue_state, lwr_exchange, callback): lwr_exchange.consume("setup", callback=callback, check=queue_state) def __process_message(manager, body, message): manager_endpoint_util.submit_job(manager, body) message.ack()
from lwr.managers import status from lwr.lwr_client import amqp_exchange from lwr import manager_endpoint_util import threading import logging log = logging.getLogger(__name__) def bind_manager_to_queue(manager, queue_state, connection_string): lwr_exchange = amqp_exchange.LwrExchange(connection_string, manager.name) def process_messages(body, message): __process_message(manager, body, message) def drain(): __drain(queue_state, lwr_exchange, process_messages) thread_name = "consumer-%s" % connection_string thread = threading.Thread(name=thread_name, target=drain) thread.daemon = True thread.start() # TODO: Think through job recovery, jobs shouldn't complete until after bind # has occurred. def bind_on_status_change(new_status, job_id): payload = manager_endpoint_util.full_status(manager, new_status, job_id) lwr_exchange.publish("status_update", payload) manager.set_state_change_callback(bind_on_status_change) def __drain(queue_state, lwr_exchange, callback): lwr_exchange.consume("setup", callback=callback, check=queue_state) def __process_message(manager, body, message): manager_endpoint_util.submit_job(manager, body) message.ack()
[ADD] Add checks on init file
# -*- coding: utf-8 -*- # ############################################################################## # # Authors: Adrien Peiffer # Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_companyweb checks = [ test_companyweb, ]
# -*- coding: utf-8 -*- # ############################################################################## # # Authors: Adrien Peiffer # Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_companyweb
Use switch in translate function instead
/* jshint esversion: 6 */ window.onload = () => { /* TODO: put in some if (localizationEnabled) block in case people who use non-english browser still wants english extension? */ translate('name', 'title', 'extName'); translate('id', 'battleLink', 'battle'); translate('class', 'by', 'by'); }; function translate (type, name, message) { switch (type) { case 'name': document.getElementsByTagName(name)[0].innerHTML = chrome.i18n.getMessage(message); break; case 'id': document.getElementById(name).innerHTML = chrome.i18n.getMessage(message); break; case 'class': var elements = document.getElementsByClassName(name); console.log(elements.length); for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = chrome.i18n.getMessage(message); } break; } } /* chrome.browserAction.onClicked.addListener(function(tab) { var port = chrome.extension.connect({name: "Sample Communication"}); port.postMessage("Hi BackGround"); port.onMessage.addListener(function(msg) { console.log("message recieved"+ msg); }); }); */
/* jshint esversion: 6 */ window.onload = () => { /* TODO: put in some if (localizationEnabled) block in case people who use non-english browser still wants english extension? */ translate('name', 'title', 'extName'); translate('id', 'battleLink', 'battle'); translate('class', 'by', 'by'); }; function translate (type, name, message) { if (type === 'name') document.getElementsByTagName(name)[0].innerHTML = chrome.i18n.getMessage(message); else if (type === 'id') document.getElementById(name).innerHTML = chrome.i18n.getMessage(message); else if (type === 'class') { var elements = document.getElementsByClassName(name); console.log(elements.length); for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = chrome.i18n.getMessage(message); } } } /* chrome.browserAction.onClicked.addListener(function(tab) { var port = chrome.extension.connect({name: "Sample Communication"}); port.postMessage("Hi BackGround"); port.onMessage.addListener(function(msg) { console.log("message recieved"+ msg); }); }); */
Fix ParseCert() function, add variables, add a return statement
#!/usr/bin/env python3 import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) CertSubject = str(Cert.get_subject())[18:-2] CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ') CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ') CertIssuer = str(Cert.get_issuer())[18:-2] return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate, 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer} CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) Out = ParseCert(CertRaw) print(Out) print(Out['CertSubject']) print(Out['CertStartDate'])
#!/usr/bin/env python3 import datetime import ssl import OpenSSL def GetCert(SiteName, Port): return ssl.get_server_certificate((SiteName, Port)) def ParseCert(CertRaw): Cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, CertRaw) print(str(Cert.get_subject())[18:-2]) print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1], '%Y%m%d%H%M%SZ')) print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1], '%Y%m%d%H%M%SZ')) print(str(Cert.get_issuer())[18:-2]) CertRaw = GetCert('some.domain.tld', 443) print(CertRaw) ParseCert(CertRaw)
Add custom conflict error response
var bcrypt = require( 'bcrypt' ); var appModels = require( '../models' ); var systemError = require( '../utils/error_messages' ).systemError; var conflictError = require( '../utils/error_messages' ).conflictError; exports.isEmailInUse = function ( email, callback ) { appModels.User.findOne( { email: email }, function ( err, user ) { if ( err ) { return callback( systemError( err ) ); } if ( user ) { return callback( null, true ); } return callback( null, false ); } ); }; exports.createUser = function ( email, password, callback ) { var newUserData = { email: email, password: bcrypt.hashSync( password, 8 ), role: "user" }; appModels.User.create( newUserData, function ( err, newUser ) { if ( err ) { if ( err.code === 11000 ) { return callback( conflictError( "Email address is in use" ) ); } return callback( systemError( err ) ); } return callback( null, newUser ); } ); };
var bcrypt = require( 'bcrypt' ); var appModels = require( '../models' ); var systemError = require( '../utils/error_messages' ).systemError; exports.isEmailInUse = function ( email, callback ) { appModels.User.findOne( { email: email }, function ( err, user ) { if ( err ) { return callback( systemError( err ) ); } if ( user ) { return callback( null, true ); } return callback( null, false ); } ); }; exports.createUser = function ( email, password, callback ) { var newUserData = { email: email, password: bcrypt.hashSync( password, 8 ), role: "user" }; appModels.User.create( newUserData, function ( err, newUser ) { if ( err ) { return callback( systemError( err ) ); } return callback( null, newUser ); } ); };
Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`. Currently the usage for `RepresentativeDataset` is an iterator instead of a callable. This fix changes the type signature accordingly. PiperOrigin-RevId: 457393586
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines types required for representative datasets for quantization.""" from typing import Iterable, Mapping, Tuple, Union from tensorflow.python.types import core # A representative sample should be either: # 1. (signature_key, {input_name -> input_tensor}) tuple, or # 2. {input_name -> input_tensor} mappings. # TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays). RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]], Mapping[str, core.Tensor]] # A representative dataset is an iterable of representative samples. RepresentativeDataset = Iterable[RepresentativeSample]
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines types required for representative datasets for quantization.""" from typing import Callable, Iterable, Mapping, Tuple, Union from tensorflow.python.types import core # A representative sample should be either: # 1. (signature_key, {input_name -> input_tensor}) tuple, or # 2. {input_name -> input_tensor} mappings. # TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays). RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]], Mapping[str, core.Tensor]] # A representative dataset should be a callable that returns an iterable # of representative samples. RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
Fix in constructor of currency price tag
<?php namespace Nilz\Money\PriceTag; use Nilz\Money\Currency\ExchangeRate; use Nilz\Money\MoneyInterface; /** * Class CurrencyPriceTag * @author Nilz */ class CurrencyPriceTag extends PriceTag { /** * @var ExchangeRate */ protected $exchangeRate; /** * @param MoneyInterface $netPrice * @param MoneyInterface $grossPrice * @param float $taxPercentage * @param ExchangeRate $exchangeRate */ public function __construct(MoneyInterface $netPrice, MoneyInterface $grossPrice, $taxPercentage, ExchangeRate $exchangeRate) { parent::__construct($netPrice, $grossPrice, $taxPercentage); $this->exchangeRate = $exchangeRate; } /** * @return ExchangeRate */ public function getExchangeRate() { return $this->exchangeRate; } }
<?php namespace Nilz\Money\PriceTag; use Nilz\Money\Currency\ExchangeRate; use Nilz\Money\MoneyInterface; /** * Class CurrencyPriceTag * @author Nilz */ class CurrencyPriceTag extends PriceTag { /** * @var ExchangeRate */ protected $exchangeRate; /** * @param MoneyInterface $netPrice * @param MoneyInterface $grossPrice * @param float $taxPercentage * @param ExchangeRate $exchangeRate */ public function __construct(MoneyInterface $netPrice, MoneyInterface $grossPrice, $taxPercentage, $baseCurrency, ExchangeRate $exchangeRate) { parent::__construct($netPrice, $grossPrice, $taxPercentage); $this->exchangeRate = $exchangeRate; } /** * @return ExchangeRate */ public function getExchangeRate() { return $this->exchangeRate; } }
Convert notify store to new pattern
/** * Notify Store * * The notifications. Essentially a log to emit events. */ // Requires import {register2} from 'janeswalk/dispatcher/AppDispatcher'; import {EventEmitter} from 'events'; import {ActionTypes as AT} from 'janeswalk/constants/JWConstants'; import {changeMethods} from 'janeswalk/utils/Stores'; // The notifications const _log = []; function receiveLogEntry(message, component, level) { _log.push({ time: Date.now(), message: message, level: level }); } const NotifyStore = Object.assign({}, EventEmitter.prototype, changeMethods { getLog: () => _log, getLogFrom: (from) => _log.filter(entry => entry.time >= from), // Register our dispatch token as a static method dispatchToken: register2({ [AT.LOG_INFO]: ({message, component}) => { receiveLogEntry(payload.message, payload.component || 'caw', 'info'); }, [AT.LOG_WARN]: ({message, component}) => { receiveLogEntry(message, component || 'caw', 'warn'); }, [AT.LOG_ERROR]: ({message, component}) => { receiveLogEntry(message, component || 'caw', 'error'); }, [AT.LOG_EMPTY]: () => _log.splice(0), }, () => NotifyStore.emitChange()) }); export default NotifyStore;
/** * Notify Store * * The notifications. Essentially a log to emit events. */ // Requires import {ActionTypes} from '../constants/JWConstants.js'; import {register} from 'janeswalk/dispatcher/AppDispatcher'; import 'Store' from './Store.js'; // The notifications const _log = []; function receiveLogEntry(message, component, level) { _log.push({ time: Date.now(), message: message, level: level }); } const NotifyStore = Object.assign({}, Store, { getLog() { return _log; }, // Register our dispatch token as a static method dispatchToken: register(function(payload) { // Go through the various actions switch(payload.type) { // Route actions case ActionTypes.LOG_INFO: receiveLogEntry(payload.message, payload.component || 'caw', 'info'); NotifyStore.emitChange(); break; case ActionTypes.LOG_WARN: receiveLogEntry(payload.message, payload.component || 'caw', 'warn'); NotifyStore.emitChange(); break; case ActionTypes.LOG_ERROR: receiveLogEntry(payload.message, payload.component || 'caw', 'error'); NotifyStore.emitChange(); break; default: // do nothing } }); }); export default NotifyStore;
Fix typo in unknown service provider error message
var services = { 'travis' : require('./services/travis'), 'circle' : require('./services/circle'), 'buildkite' : require('./services/buildkite'), 'codeship' : require('./services/codeship'), 'drone' : require('./services/drone'), 'appveyor' : require('./services/appveyor'), 'wercker' : require('./services/wercker'), 'jenkins' : require('./services/jenkins'), 'semaphore' : require('./services/semaphore'), 'snap' : require('./services/snap'), 'gitlab' : require('./services/gitlab') }; var detectProvider = function(){ var config; for (var name in services){ if (services[name].detect()){ config = services[name].configuration(); break; } } if (!config){ var local = require('./services/localGit'); config = local.configuration(); if (!config){ throw new Error("Unknown CI service provider. Unable to upload coverage."); } } return config; }; module.exports = detectProvider;
var services = { 'travis' : require('./services/travis'), 'circle' : require('./services/circle'), 'buildkite' : require('./services/buildkite'), 'codeship' : require('./services/codeship'), 'drone' : require('./services/drone'), 'appveyor' : require('./services/appveyor'), 'wercker' : require('./services/wercker'), 'jenkins' : require('./services/jenkins'), 'semaphore' : require('./services/semaphore'), 'snap' : require('./services/snap'), 'gitlab' : require('./services/gitlab') }; var detectProvider = function(){ var config; for (var name in services){ if (services[name].detect()){ config = services[name].configuration(); break; } } if (!config){ var local = require('./services/localGit'); config = local.configuration(); if (!config){ throw new Error("Unknown CI servie provider. Unable to upload coverage."); } } return config; }; module.exports = detectProvider;
Change default format to normal longitude/latitude.
import requests from .api_exception import RakutenApiException from .base_api import BaseApi class TravelApi(BaseApi): def __init__(self, options): super(TravelApi, self).__init__(options) self._default_params['datumType'] = 1 def vacant_hotel_search(self, **kwargs): params = self._dict_to_camel_case(kwargs) params.update(self._default_params) url = self._make_url('/Travel/VacantHotelSearch/20131024') r = requests.get(url, params=params) if r.status_code == 200: result = r.json() hotels = [self._parse_hotel(r) for r in result['hotels']] return hotels else: raise RakutenApiException(r.status_code, r.text) def _parse_hotel(self, hotel_info): hotel = hotel_info['hotel'][0]['hotelBasicInfo'] room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r] hotel['room_infos'] = room_infos return hotel
import requests from .api_exception import RakutenApiException from .base_api import BaseApi class TravelApi(BaseApi): def __init__(self, options): super(TravelApi, self).__init__(options) def vacant_hotel_search(self, **kwargs): params = self._dict_to_camel_case(kwargs) params.update(self._default_params) url = self._make_url('/Travel/VacantHotelSearch/20131024') r = requests.get(url, params=params) if r.status_code == 200: result = r.json() hotels = [self._parse_hotel(r) for r in result['hotels']] return hotels else: raise RakutenApiException(r.status_code, r.text) def _parse_hotel(self, hotel_info): hotel = hotel_info['hotel'][0]['hotelBasicInfo'] room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r] hotel['room_infos'] = room_infos return hotel
Add DisableUpdates field to lib/mdb/Machine.
package mdb import ( "io" ) type Machine struct { Hostname string DisableUpdates string `json:",omitempty"` RequiredImage string `json:",omitempty"` PlannedImage string `json:",omitempty"` } type Mdb struct { Machines []Machine } func (mdb *Mdb) DebugWrite(w io.Writer) error { return mdb.debugWrite(w) } func (mdb *Mdb) Len() int { return len(mdb.Machines) } func (mdb *Mdb) Less(left, right int) bool { if mdb.Machines[left].Hostname < mdb.Machines[right].Hostname { return true } return false } func (mdb *Mdb) Swap(left, right int) { tmp := mdb.Machines[left] mdb.Machines[left] = mdb.Machines[right] mdb.Machines[right] = tmp }
package mdb import ( "io" ) type Machine struct { Hostname string RequiredImage string `json:",omitempty"` PlannedImage string `json:",omitempty"` } type Mdb struct { Machines []Machine } func (mdb *Mdb) DebugWrite(w io.Writer) error { return mdb.debugWrite(w) } func (mdb *Mdb) Len() int { return len(mdb.Machines) } func (mdb *Mdb) Less(left, right int) bool { if mdb.Machines[left].Hostname < mdb.Machines[right].Hostname { return true } return false } func (mdb *Mdb) Swap(left, right int) { tmp := mdb.Machines[left] mdb.Machines[left] = mdb.Machines[right] mdb.Machines[right] = tmp }
Change conditional to check if object is already in array
var model = (function(){ var splashesArray = []; function addSplashes(splashes_in_database){ // Compare existing splashesArray to the splashes list given // If any new spashes, then add new splashes to splashesArray and return them console.log('made it') console.log(splashes_in_database) for (var i = 0; i < splashes_in_database.length; i++){ for (var j = 0; j < splashesArray.length; j++){ if !($.inArray(splashes_in_database[i],splashesArray)){ splashesArray.push(splashes_in_database[i]); } } } for(i=0; i < splashesArray.length; i++) { view.addNewSplash(splashesArray[i]) } } function removeSplashes(){ var now = new Date(); } function getSplashes(){ return splashesArray; } return{ removeSplashes: removeSplashes, addSplashes: addSplashes, getSplashes: getSplashes }; })();
var model = (function(){ var splashesArray = []; function addSplashes(splashes_in_database){ // Compare existing splashesArray to the splashes list given // If any new spashes, then add new splashes to splashesArray and return them console.log('made it') console.log(splashes_in_database) for (var i = 0; i < splashes_in_database.length; i++){ for (var j = 0; j < splashesArray.length; j++){ if(splashes_in_database[i] != splashesArray[j]){ splashesArray.push(splashes_in_database[i]); } } } for(i=0; i < splashesArray.length; i++) { view.addNewSplash(splashesArray[i]) } } function removeSplashes(){ var now = new Date(); } function getSplashes(){ return splashesArray; } return{ removeSplashes: removeSplashes, addSplashes: addSplashes, getSplashes: getSplashes }; })();
Add more ExistOutputKeys (stylesheet and stylesheetparam) svn path=/trunk/eXist-1.0/; revision=146
/* * eXist Open Source Native XML Database * Copyright (C) 2001-03 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage.serializers; public class EXistOutputKeys { public final static String EXPAND_XINCLUDES = "{http://exist-db.org/}expand-xincludes"; public final static String HIGHLIGHT_MATCHES = "{http://exist-db.org/}highlight-matches"; public final static String INDENT_SPACES = "{http://exist-db.org/}indent-spaces"; public final static String STYLESHEET = "{http://exist-db.org/}stylesheet"; public final static String STYLESHEET_PARAM = "{http://exist-db.org/}stylesheet-param"; }
/* * eXist Open Source Native XML Database * Copyright (C) 2001-03 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage.serializers; public class EXistOutputKeys { public final static String EXPAND_XINCLUDES = "{http://exist-db.org/}expand-xincludes"; public final static String HIGHLIGHT_MATCHES = "{http://exist-db.org/}highlight-matches"; public final static String INDENT_SPACES = "{http://exist-db.org/}indent-spaces"; }
Fix CORS handling for POST and DELETE
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; // Create a proxy server pointing at spreadsheets.google.com. //var proxy = httpProxy.createProxyServer({target: 'https://spreadsheets.google.com'}); var proxy = httpProxy.createProxyServer(); https.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); }).listen(process.env.PORT || 5000);
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'Access-Control-Max-Age': '86400', 'Access-Control-Allow-Headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept" }; // Create a proxy server pointing at spreadsheets.google.com. //var proxy = httpProxy.createProxyServer({target: 'https://spreadsheets.google.com'}); var proxy = httpProxy.createProxyServer(); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { res.writeHead(200, CORS_HEADERS); res.end(); return } delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); }).listen(process.env.PORT || 5000);
[FEATURE] Clear session on delete method
var User = require('../models/user.js'), utils = require('../../lib/utils.js'); module.exports = (function(){ function destroy(req, res) { req.session = null res.send({ success: true, session: req.session }) } function create(req, res) { req.session.session = null var user, valid if (req.body.name && req.body.password) { User.findAll({ where: { name: req.body.name }}) .error(function(err){ res.send({ error: 'user not found' }) }) .success(function(results){ user = results[0] if (user) { valid = utils.verifyPassword(req.body.password, user.salt, user.passwordHash) if (valid) { req.session.username = user.name req.session.username = user.name res.send({ success: true, session: { username: user.name } }) } } else { res.send({ error: 'user not found' }) } }) } else { res.send({ error: 'required params: name, password' }) } } function show(req, res) { res.send({ success: true, session: { username: req.session.username } }) } return { create: create, destroy: destroy, show: show } })()
var User = require('../models/user.js'), utils = require('../../lib/utils.js'); module.exports = (function(){ function destroy(req, res) { res.send({ success: true, session: req.session }) } function create(req, res) { req.session.session = null var user, valid if (req.body.name && req.body.password) { User.findAll({ where: { name: req.body.name }}) .error(function(err){ res.send({ error: 'user not found' }) }) .success(function(results){ user = results[0] if (user) { valid = utils.verifyPassword(req.body.password, user.salt, user.passwordHash) if (valid) { req.session.username = user.name req.session.username = user.name res.send({ success: true, session: { username: user.name } }) } } else { res.send({ error: 'user not found' }) } }) } else { res.send({ error: 'required params: name, password' }) } } function show(req, res) { res.send({ success: true, session: { username: req.session.username } }) } return { create: create, destroy: destroy, show: show } })()
itertools: Rename seq.Delete to DeleteIndex to better reflect its purpose
package itertools import "math/rand" type seq struct { i []int } // Creates sequence of values from [0, n) func newSeq(n int) seq { return seq{make([]int, n, n)} } func (me seq) Index(i int) (ret int) { ret = me.i[i] if ret == 0 { ret = i } return } func (me seq) Len() int { return len(me.i) } // Remove the nth value from the sequence. func (me *seq) DeleteIndex(index int) { me.i[index] = me.Index(me.Len() - 1) me.i = me.i[:me.Len()-1] } func ForPerm(n int, callback func(i int) (more bool)) bool { s := newSeq(n) for s.Len() > 0 { r := rand.Intn(s.Len()) if !callback(s.Index(r)) { return false } s.DeleteIndex(r) } return true }
package itertools import "math/rand" type seq struct { i []int } // Creates sequence of values from [0, n) func newSeq(n int) seq { return seq{make([]int, n, n)} } func (me seq) Index(i int) (ret int) { ret = me.i[i] if ret == 0 { ret = i } return } func (me seq) Len() int { return len(me.i) } // Remove the nth value from the sequence. func (me *seq) Delete(index int) { me.i[index] = me.Index(me.Len() - 1) me.i = me.i[:me.Len()-1] } func ForPerm(n int, callback func(i int) (more bool)) bool { s := newSeq(n) for s.Len() > 0 { r := rand.Intn(s.Len()) if !callback(s.Index(r)) { return false } s.Delete(r) } return true }
Remove migrations.RunPython.noop from reverse for Django<1.8
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid, os def gen_uuid(apps, schema_editor): WooeyJob = apps.get_model('wooey', 'WooeyJob') for obj in WooeyJob.objects.all(): obj.uuid = uuid.uuid4() obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0011_script_versioning_cleanup'), ] operations = [ # Add the uuid field with unique=False for existing entries # due to a bug in migrations this will set all to the same uuid migrations.AddField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=False, max_length=255), ), # Set the uuids for existing records migrations.RunPython(gen_uuid), # Set to unique=True migrations.AlterField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=True, max_length=255), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid, os def gen_uuid(apps, schema_editor): WooeyJob = apps.get_model('wooey', 'WooeyJob') for obj in WooeyJob.objects.all(): obj.uuid = uuid.uuid4() obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0011_script_versioning_cleanup'), ] operations = [ # Add the uuid field with unique=False for existing entries # due to a bug in migrations this will set all to the same uuid migrations.AddField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=False, max_length=255), ), # Set the uuids for existing records migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), # Set to unique=True migrations.AlterField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=True, max_length=255), ), ]
Make sure this works the first time you run it
''' Setup script that: /pyquic: - compiles pyquic - copies py_quic into base directory so that we can use the module directly ''' import os import shutil class temp_cd(): def __init__(self, temp_dir): self._temp_dir = temp_dir self._return_dir = os.path.dirname(os.path.realpath(__file__)) def __enter__(self): os.chdir(self._temp_dir) def __exit__(self, type, value, traceback): os.chdir(self._return_dir) def setup_pyquic(): with temp_cd('pyquic/py_quic'): os.system('make') if os.path.exists('quic/py_quic'): shutil.rmtree('quic/py_quic') shutil.copytree('pyquic/py_quic', 'quic/py_quic') def clean_pyquic(): shutil.rmtree('py_quic') os.system('git submodule update --checkout --remote -f') if __name__ == "__main__": setup_pyquic()
''' Setup script that: /pyquic: - compiles pyquic - copies py_quic into base directory so that we can use the module directly ''' import os import shutil class temp_cd(): def __init__(self, temp_dir): self._temp_dir = temp_dir self._return_dir = os.path.dirname(os.path.realpath(__file__)) def __enter__(self): os.chdir(self._temp_dir) def __exit__(self, type, value, traceback): os.chdir(self._return_dir) def setup_pyquic(): with temp_cd('pyquic/py_quic'): os.system('make') shutil.rmtree('quic/py_quic') shutil.copytree('pyquic/py_quic', 'quic/py_quic') def clean_pyquic(): shutil.rmtree('py_quic') os.system('git submodule update --checkout --remote -f') if __name__ == "__main__": setup_pyquic()
server: Use server URL as storage key.
import ms from 'ms'; import createDebug from 'debug'; const debug = createDebug('u-wave-hub'); const servers = new Map(); export function announce(req, res) { const data = req.body servers.set(data.url, { ping: Date.now(), data, }); debug('announce', data.url); const server = servers.get(data.url); res.json({ received: server.data, }); } export function list(req, res) { const response = []; servers.forEach((value) => { response.push(value.data); }); res.json({ servers: response, }); } export function prune() { debug('prune'); servers.forEach((server, url) => { if (server.ping + ms('5 minutes') < Date.now()) { debug('prune', url); servers.delete(url); } }); }
import ms from 'ms'; import createDebug from 'debug'; const debug = createDebug('u-wave-hub'); const servers = new Map(); export function announce(req, res) { servers.set(req.ip, { ping: Date.now(), data: req.body, }); debug('announce', req.ip); const server = servers.get(req.ip); res.json({ received: server.data, }); } export function list(req, res) { const response = []; servers.forEach((value) => { response.push(value.data); }); res.json({ servers: response, }); } export function prune() { debug('prune'); servers.forEach((server, ip) => { if (server.ping + ms('5 minutes') < Date.now()) { debug('prune', ip); servers.delete(ip); } }); }
Fix parsing of the kubeconfig file
"""Describe methods to work with kubeconfig file.""" import pytest import yaml def get_current_context_name(kube_config) -> str: """ Get current-context from kubeconfig. :param kube_config: absolute path to kubeconfig :return: str """ with open(kube_config) as conf: dep = yaml.load(conf) return dep['current-context'] def ensure_context_in_config(kube_config, context_name) -> None: """ Verify that kubeconfig contains specific context and fail if it doesn't. :param kube_config: absolute path to kubeconfig :param context_name: context name to verify :return: """ with open(kube_config) as conf: dep = yaml.load(conf) for contexts in dep['contexts']: if contexts['name'] == context_name: return pytest.fail(f"Failed to find context '{context_name}' in the kubeconfig file: {kube_config}")
"""Describe methods to work with kubeconfig file.""" import pytest import yaml def get_current_context_name(kube_config) -> str: """ Get current-context from kubeconfig. :param kube_config: absolute path to kubeconfig :return: str """ with open(kube_config) as conf: dep = yaml.load(conf) return dep['current-context'] def ensure_context_in_config(kube_config, context_name) -> None: """ Verify that kubeconfig contains specific context and fail if it doesn't. :param kube_config: absolute path to kubeconfig :param context_name: context name to verify :return: """ with open(kube_config) as conf: dep = yaml.load(conf) for users in dep['users']: if users['name'] == context_name: return pytest.fail(f"Failed to find context '{context_name}' in the kubeconfig file: {kube_config}")
Add more specificity to the CI "check."
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ module.exports = function(grunt) { // The `artifacts` directory will usually only ever in YUI's CI system. // If you're in CI, `build-npm` exists, and this task was called in // response to the `postinstall` hook; skip the build. if ((process.env.npm_lifecycle_event === "postinstall" && grunt.file.exists('artifacts') && grunt.file.exists('build-npm')) || 'GRUNT_SKIP_BUILD' in process.env) { grunt.registerTask('build', 'Building YUI', function() { grunt.log.ok('Found GRUNT_SKIP_BUILD in environment, skipping build.'); }); } else { grunt.registerTask('build', 'Building YUI', ['yogi-build', 'npm']); } grunt.registerTask('build-test', 'Building and testing YUI', ['yogi-build', 'npm', 'test']); grunt.registerTask('all', 'Building and testing YUI', ['build-test']); };
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ module.exports = function(grunt) { // The `artifacts` directory will usually only ever in YUI's CI system. // If you're in CI, and `build-npm` exists (meaning YUI's already built), skip the build. if ((grunt.file.exists('artifacts') && grunt.file.exists('build-npm')) || 'GRUNT_SKIP_BUILD' in process.env) { grunt.registerTask('build', 'Building YUI', function() { grunt.log.ok('Found GRUNT_SKIP_BUILD in environment, skipping build.'); }); } else { grunt.registerTask('build', 'Building YUI', ['yogi-build', 'npm']); } grunt.registerTask('build-test', 'Building and testing YUI', ['yogi-build', 'npm', 'test']); grunt.registerTask('all', 'Building and testing YUI', ['build-test']); };
Fix up uncaught ajax error alert message
import DS from 'ember-data'; import JsonApiAdapter from 'ember-json-api/json-api-adapter'; import config from 'flarum/config/environment'; import AlertMessage from 'flarum/components/ui/alert-message'; export default JsonApiAdapter.extend({ host: config.apiURL, ajaxError: function(jqXHR) { var errors = this._super(jqXHR); // Reparse the errors in accordance with the JSON-API spec to fit with // Ember Data style. Hopefully something like this will eventually be a // part of the JsonApiAdapter. if (errors instanceof DS.InvalidError) { var newErrors = {}; for (var i in errors.errors) { var error = errors.errors[i]; newErrors[error.path] = error.detail; } return new DS.InvalidError(newErrors); } // If it's a server error, show an alert message. The alerts controller // has been injected into this adapter. if (errors instanceof JsonApiAdapter.ServerError) { var message = AlertMessage.create({ type: 'warning', message: 'Something went wrong: '+errors.message.errors[0].code }); this.get('alerts').send('alert', message); return; } return errors; } });
import DS from 'ember-data'; import JsonApiAdapter from 'ember-json-api/json-api-adapter'; import config from 'flarum/config/environment'; import AlertMessage from 'flarum/components/ui/alert-message'; export default JsonApiAdapter.extend({ host: config.apiURL, ajaxError: function(jqXHR) { var errors = this._super(jqXHR); // Reparse the errors in accordance with the JSON-API spec to fit with // Ember Data style. Hopefully something like this will eventually be a // part of the JsonApiAdapter. if (errors instanceof DS.InvalidError) { var newErrors = {}; for (var i in errors.errors) { var error = errors.errors[i]; newErrors[error.path] = error.detail; } return new DS.InvalidError(newErrors); } // If it's a server error, show an alert message. The alerts controller // has been injected into this adapter. if (errors instanceof JsonApiAdapter.ServerError) { var message = AlertMessage.create({ type: 'warning', message: errors.message }); this.get('alerts').send('alert', message); return; } return errors; } });
Update error message of UnsupportedOperationException.
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func
Make sure naming tests work - even when eclipselink naming provider present
package org.realityforge.replicant.server.ee; import javax.annotation.Nonnull; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import javax.transaction.TransactionSynchronizationRegistry; import org.realityforge.guiceyloops.server.TestInitialContextFactory; import org.realityforge.guiceyloops.server.TestTransactionSynchronizationRegistry; import org.realityforge.replicant.server.ServerConstants; import static org.testng.Assert.*; public final class RegistryUtil { private RegistryUtil() { } @Nonnull public static TransactionSynchronizationRegistry bind() { try { if ( !NamingManager.hasInitialContextFactoryBuilder() ) { NamingManager.setInitialContextFactoryBuilder( environment -> e -> TestInitialContextFactory.getContext() ); } TestInitialContextFactory.reset(); final Context context = TestInitialContextFactory.getContext().createSubcontext( "java:comp" ); final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry(); registry.putResource( ServerConstants.REPLICATION_INVOCATION_KEY, "Ignored" ); context.bind( "TransactionSynchronizationRegistry", registry ); return registry; } catch ( final NamingException e ) { fail( "Unexpected exception", e ); throw new IllegalStateException(); } } }
package org.realityforge.replicant.server.ee; import javax.annotation.Nonnull; import javax.naming.Context; import javax.naming.NamingException; import javax.transaction.TransactionSynchronizationRegistry; import org.realityforge.guiceyloops.server.TestInitialContextFactory; import org.realityforge.guiceyloops.server.TestTransactionSynchronizationRegistry; import org.realityforge.replicant.server.ServerConstants; import static org.testng.Assert.*; public final class RegistryUtil { private RegistryUtil() { } @Nonnull public static TransactionSynchronizationRegistry bind() { try { TestInitialContextFactory.reset(); final Context context = TestInitialContextFactory.getContext().createSubcontext( "java:comp" ); final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry(); registry.putResource( ServerConstants.REPLICATION_INVOCATION_KEY, "Ignored" ); context.bind( "TransactionSynchronizationRegistry", registry ); return registry; } catch ( final NamingException e ) { fail( "Unexpected exception", e ); throw new IllegalStateException(); } } }
Allow receive of future-dated samples
## Script (Python) "guard_receive_transition" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True
## Script (Python) "guard_receive_transition" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if our Sample's SamplingDate is the future if context.getSample().getSamplingDate() > DateTime(): return False # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if our SamplingDate is the future if context.getSamplingDate() > DateTime(): return False # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True
Update dependency injection extension to make use of FileLocator
<?php namespace Knplabs\TimeBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\FileLocator; class TimeExtension extends Extension { public function configLoad(array $configs, ContainerBuilder $container) { foreach ($configs as $config) { $this->doConfigLoad($config, $container); } } public function doConfigLoad(array $config, ContainerBuilder $container) { if(!$container->hasDefinition('time.templating.helper.time')) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('templating.xml'); $loader->load('twig.xml'); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'time'; } }
<?php namespace Knplabs\TimeBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; class TimeExtension extends Extension { public function configLoad(array $configs, ContainerBuilder $container) { foreach ($configs as $config) { $this->doConfigLoad($config, $container); } } public function doConfigLoad(array $config, ContainerBuilder $container) { if(!$container->hasDefinition('time.templating.helper.time')) { $loader = new XmlFileLoader($container, __DIR__.'/../Resources/config'); $loader->load('templating.xml'); $loader->load('twig.xml'); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'time'; } }
Fix the provided value dist/umd is not an absolute path
// UMD config const path = require('path') const webpack = require('webpack') module.exports = { devtool: 'source-map', entry: { 'js-search': './source/index.js' }, output: { path: path.join(__dirname,'dist/umd'), filename: 'js-search.js', libraryTarget: 'umd', library: 'JsSearch' }, externals: { }, plugins: [ new webpack.optimize.UglifyJsPlugin({ beautify: true, comments: true, mangle: false }) ], module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], include: path.join(__dirname, 'source') } ] } }
// UMD config const path = require('path') const webpack = require('webpack') module.exports = { devtool: 'source-map', entry: { 'js-search': './source/index.js' }, output: { path: 'dist/umd', filename: 'js-search.js', libraryTarget: 'umd', library: 'JsSearch' }, externals: { }, plugins: [ new webpack.optimize.UglifyJsPlugin({ beautify: true, comments: true, mangle: false }) ], module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], include: path.join(__dirname, 'source') } ] } }
Add TrivialNary and create SQLIte DB
package com.englishnary.eridev.android.englishnary; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; public class DevTest extends ActionBarActivity { //Declaro los controles a utilizar Button btn_empezar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dev_test); //Obtengo los controles btn_empezar = (Button)findViewById(R.id.btn_empezar); btn_empezar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentEmpezar = new Intent(DevTest.this,splash_screen.class); startActivity(intentEmpezar); } }); //Creo una instancia de DPreguntas y le paso la instancia de la clase this DPreguntas dPregHelper = new DPreguntas(this); } }
package com.englishnary.eridev.android.englishnary; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; public class DevTest extends ActionBarActivity { //Declaro los controles a utilizar Button btn_empezar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dev_test); //Obtengo los controles btn_empezar = (Button)findViewById(R.id.btn_empezar); btn_empezar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentEmpezar = new Intent(DevTest.this,splash_screen.class); startActivity(intentEmpezar); } }); //Creo una instancia de DPreguntas y le paso la instancia de la clase this DPreguntas dPregHelper = new DPreguntas(this); } }
Add helper method to get all the empires we have some relation with.
package com.galvarez.ttw.model.components; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.artemis.Component; import com.artemis.Entity; import com.galvarez.ttw.model.DiplomaticSystem.Action; import com.galvarez.ttw.model.DiplomaticSystem.State; public final class Diplomacy extends Component { public final Map<Entity, State> relations = new HashMap<>(); public final Map<Entity, Integer> lastChange = new HashMap<>(); public final Map<Entity, Action> proposals = new HashMap<>(); public final EnumSet<State> knownStates = EnumSet.of(State.NONE); public Diplomacy() { } public State getRelationWith(Entity other) { State state = relations.get(other); return state != null ? state : State.NONE; } public Action getProposalTo(Entity other) { Action action = proposals.get(other); return action != null ? action : Action.NO_CHANGE; } /** Get all empires whose state is the one passed as a parameter. */ public List<Entity> getEmpires(State state) { List<Entity> others = new ArrayList<Entity>(); for (Entry<Entity, State> e : relations.entrySet()) { if (e.getValue() == state) others.add(e.getKey()); } return others; } }
package com.galvarez.ttw.model.components; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import com.artemis.Component; import com.artemis.Entity; import com.galvarez.ttw.model.DiplomaticSystem.Action; import com.galvarez.ttw.model.DiplomaticSystem.State; public final class Diplomacy extends Component { public final Map<Entity, State> relations = new HashMap<>(); public final Map<Entity, Integer> lastChange = new HashMap<>(); public final Map<Entity, Action> proposals = new HashMap<>(); public final EnumSet<State> knownStates = EnumSet.of(State.NONE); public Diplomacy() { } public State getRelationWith(Entity other) { State state = relations.get(other); return state != null ? state : State.NONE; } public Action getProposalTo(Entity other) { Action action = proposals.get(other); return action != null ? action : Action.NO_CHANGE; } }
Enforce HTTP Scheme on Open and added docs.
package webbrowser import ( "errors" "net/url" "os/exec" ) var ( ErrCantOpen = errors.New("webbrowser.Open: can't open webpage") ErrNoCandidates = errors.New("webbrowser.Open: no browser candidate found for your OS.") ) // var Candidates []Browser // Browser type Browser interface { Open(string) error } // GenericBrowser type GenericBrowser struct { cmd string args []string } func (gb GenericBrowser) Open(s string) error { u, err := url.Parse(s) if err != nil { return err } // Enforce a scheme so linux and darwin work properly if u.Scheme != "https" { u.Scheme = "http" } s = u.String() cmd := exec.Command(gb.cmd, append(gb.args, s)...) return cmd.Run() } // Open opens an URL on the first available candidate found. func Open(s string) error { if len(Candidates) == 0 { return ErrNoCandidates } for _, b := range Candidates { err := b.Open(s) if err == nil { return nil } } return ErrCantOpen } // Register registers in the Candidates list (append to end). func Register(name Browser) { Candidates = append(Candidates, name) } // RegisterPrep registers in the Candidates list (prepend to start). func RegisterPrep(name Browser) { Candidates = append([]Browser{name}, Candidates...) }
package webbrowser import ( "errors" "net/url" "os/exec" ) var ( ErrCantOpen = errors.New("webbrowser.Open: can't open webpage") ErrNoCandidates = errors.New("webbrowser.Open: no browser candidate found for your OS.") ) // var Candidates []Browser // Browser type Browser interface { Open(string) error } // GenericBrowser type GenericBrowser struct { cmd string args []string } func (gb GenericBrowser) Open(s string) error { u, err := url.Parse(s) if err != nil { return err } u.Scheme = "http" s = u.String() cmd := exec.Command(gb.cmd, append(gb.args, s)...) return cmd.Run() } func Open(s string) error { if len(Candidates) == 0 { return ErrNoCandidates } for _, b := range Candidates { err := b.Open(s) if err == nil { return nil } } return ErrCantOpen } // Register a browser connector and, optionally, connection. func Register(name Browser) { // Append Candidates = append(Candidates, name) // Prepend // Candidates = append([]Browser{name}, Candidates...) }
Change the striping of parameters types (to be more robust)
from Cython.Compiler.Visitor import VisitorTransform from Cython.Compiler.Nodes import CSimpleBaseTypeNode class CDefToDefTransform(VisitorTransform): # Does not really turns cdefed function into defed function, it justs kills # the arguments and the return types of the functions, we rely on the # CodeWriter to get 'def' instead of 'cdef' visit_Node = VisitorTransform.recurse_to_children def visit_CFuncDefNode(self, node): oldbase_type = node.base_type node.base_type = CSimpleBaseTypeNode(0) node.base_type.name = None node.base_type.is_self_arg = False self.strip_args_types(node.declarator.args) return node def visit_DefNode(self, node): self.strip_args_types(node.args) return node def strip_args_types(self, args): for arg in args: oldbase_type = arg.base_type arg.base_type = CSimpleBaseTypeNode(0) arg.base_type.name = None arg.base_type.is_self_arg = oldbase_type.is_self_arg
from Cython.Compiler.Visitor import VisitorTransform from Cython.Compiler.Nodes import CSimpleBaseTypeNode class CDefToDefTransform(VisitorTransform): # Does not really turns cdefed function into defed function, it justs kills # the arguments and the return types of the functions, we rely on the # CodeWriter to get 'def' instead of 'cdef' visit_Node = VisitorTransform.recurse_to_children def visit_CFuncDefNode(self, node): oldbase_type = node.base_type node.base_type = CSimpleBaseTypeNode(0) node.base_type.name = None return node def visit_CArgDeclNode(self, node): oldbase_type = node.base_type node.base_type = CSimpleBaseTypeNode(0) node.base_type.name = None node.base_type.is_self_arg = oldbase_type.is_self_arg return node def visit_CDefExternNode(self, node): return node
Use micromatch.matcher on criteria arrays too should pre-optimize globs by retaining their converted regexes
'use strict'; var micromatch = require('micromatch'); var arrify = require('arrify'); var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) { criteria = arrify(criteria); value = arrify(value); if (arguments.length === 1) { return criteria.length === 1 ? micromatch.matcher(criteria[0]) : anymatch.bind(null, criteria.map(function(criterion) { return micromatch.matcher(criterion); })); } startIndex = startIndex || 0; var string = value[0]; var matchIndex = -1; function testCriteria (criterion, index) { var result; switch (toString.call(criterion)) { case '[object String]': result = string === criterion || micromatch.isMatch(string, criterion); break; case '[object RegExp]': result = criterion.test(string); break; case '[object Function]': result = criterion.apply(null, value); break; default: result = false; } if (result) { matchIndex = index + startIndex; } return result; } var matched = criteria.slice(startIndex, endIndex).some(testCriteria); return returnIndex === true ? matchIndex : matched; }; module.exports = anymatch;
'use strict'; var micromatch = require('micromatch'); var arrify = require('arrify'); var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) { criteria = arrify(criteria); value = arrify(value); if (arguments.length === 1) { return criteria.length === 1 ? micromatch.matcher(criteria[0]) : anymatch.bind(null, criteria); } startIndex = startIndex || 0; var string = value[0]; var matchIndex = -1; function testCriteria (criterion, index) { var result; switch (toString.call(criterion)) { case '[object String]': result = string === criterion || micromatch.isMatch(string, criterion); break; case '[object RegExp]': result = criterion.test(string); break; case '[object Function]': result = criterion.apply(null, value); break; default: result = false; } if (result) { matchIndex = index + startIndex; } return result; } var matched = criteria.slice(startIndex, endIndex).some(testCriteria); return returnIndex === true ? matchIndex : matched; }; module.exports = anymatch;
Rename cache clear menu item.
<?php declare(strict_types=1); /** * @author Alexander Volodin <mr-stanlik@yandex.ru> * @copyright Copyright (c) 2020, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Menu\Item\Factory; use Darvin\AdminBundle\Menu\Item; use Darvin\AdminBundle\Menu\ItemFactoryInterface; use Symfony\Component\Routing\RouterInterface; /** * List cache clear menu item factory */ class ListCacheClearItemFactory implements ItemFactoryInterface { /** * @var \Symfony\Component\Routing\RouterInterface */ private $router; /** * @param \Symfony\Component\Routing\RouterInterface $router Router */ public function __construct(RouterInterface $router) { $this->router = $router; } /** * {@inheritDoc} */ public function getItems(): iterable { yield (new Item('cache_clear')) ->setIndexTitle('cache.action.clear.link') ->setIndexUrl($this->router->generate('darvin_admin_cache_clear_list')) ->setPosition(1100); } }
<?php declare(strict_types=1); /** * @author Alexander Volodin <mr-stanlik@yandex.ru> * @copyright Copyright (c) 2020, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Menu\Item\Factory; use Darvin\AdminBundle\Menu\Item; use Darvin\AdminBundle\Menu\ItemFactoryInterface; use Symfony\Component\Routing\RouterInterface; /** * List cache clear menu item factory */ class ListCacheClearItemFactory implements ItemFactoryInterface { /** * @var \Symfony\Component\Routing\RouterInterface */ private $router; /** * @param \Symfony\Component\Routing\RouterInterface $router Router */ public function __construct(RouterInterface $router) { $this->router = $router; } /** * {@inheritDoc} */ public function getItems(): iterable { yield (new Item('cache')) ->setIndexTitle('cache.action.clear.link') ->setIndexUrl($this->router->generate('darvin_admin_cache_clear_list')) ->setPosition(1100); } }