text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix shellish requirement bump rev to 2.3.1
#!/usr/bin/env python from setuptools import setup, find_packages README = 'README.md' def long_desc(): try: import pypandoc except ImportError: with open(README) as f: return f.read() else: return pypandoc.convert(README, 'rst') setup( name='ecmcli', version='2.3.1', description='Command Line Interface for Cradlepoint ECM', author='Justin Mayfield', author_email='tooker@gmail.com', url='https://github.com/mayfield/ecmcli/', license='MIT', long_description=long_desc(), packages=find_packages(), install_requires=[ 'syndicate==1.2.0', 'shellish>=0.6.0', 'humanize' ], entry_points = { 'console_scripts': ['ecm=ecmcli.main:main'], }, include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ] )
#!/usr/bin/env python from setuptools import setup, find_packages README = 'README.md' def long_desc(): try: import pypandoc except ImportError: with open(README) as f: return f.read() else: return pypandoc.convert(README, 'rst') setup( name='ecmcli', version='2.3.0', description='Command Line Interface for Cradlepoint ECM', author='Justin Mayfield', author_email='tooker@gmail.com', url='https://github.com/mayfield/ecmcli/', license='MIT', long_description=long_desc(), packages=find_packages(), install_requires=[ 'syndicate==1.2.0', 'shellish>=0.5.9', 'humanize' ], entry_points = { 'console_scripts': ['ecm=ecmcli.main:main'], }, include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ] )
Update minor version for release
package com.microsoft.graph.core; public final class Constants { private Constants() { } public static final String APPROOT = "approot"; /** * The content type header */ public static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; /** * The encoding type for getBytes */ public static final String JSON_ENCODING = "UTF-8"; /** * The content type for JSON responses */ public static final String JSON_CONTENT_TYPE = "application/json"; /** * The binary content type header's value */ public static final String BINARY_CONTENT_TYPE = "application/octet-stream"; // Constants for functional tests // TO-DO: document how to register an application for functional // testing purposes public static final String APPID = "app-id"; public static final String USERNAME = "user@email.com"; public static final String PASSWORD = "password"; public static final String VERSION_NAME = "1.7.0"; }
package com.microsoft.graph.core; public final class Constants { private Constants() { } public static final String APPROOT = "approot"; /** * The content type header */ public static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; /** * The encoding type for getBytes */ public static final String JSON_ENCODING = "UTF-8"; /** * The content type for JSON responses */ public static final String JSON_CONTENT_TYPE = "application/json"; /** * The binary content type header's value */ public static final String BINARY_CONTENT_TYPE = "application/octet-stream"; // Constants for functional tests // TO-DO: document how to register an application for functional // testing purposes public static final String APPID = "app-id"; public static final String USERNAME = "user@email.com"; public static final String PASSWORD = "password"; public static final String VERSION_NAME = "1.6.0"; }
Fix django_extensions < 1.6.8 as higher versions do not support Django 1.6*
from setuptools import setup, find_packages setup( name='qmpy', version='0.4.9a', author='S. Kirklin', author_email='scott.kirklin@gmail.com', license='LICENSE.txt', classifiers=["Programming Language :: Python :: 2.7"], packages=find_packages(), scripts=['bin/oqmd', 'bin/qmpy'], url='http://pypi.python.org/pypi/qmpy', description='Suite of computational materials science tools', include_package_data=True, long_description=open('README.md').read(), install_requires=[ "Django >=1.6.2, <1.7", "PuLP", "numpy", "scipy", "MySQL-python", "matplotlib", "networkx", "pytest", "python-memcached", "ase", "django-extensions < 1.6.8", "lxml", "pyspglib == 1.8.3.1", "PyCifRW >= 4.3", "pexpect", "pyparsing", "PyYAML", "scikit-learn" ], )
from setuptools import setup, find_packages setup( name='qmpy', version='0.4.9a', author='S. Kirklin', author_email='scott.kirklin@gmail.com', license='LICENSE.txt', classifiers=["Programming Language :: Python :: 2.7"], packages=find_packages(), scripts=['bin/oqmd', 'bin/qmpy'], url='http://pypi.python.org/pypi/qmpy', description='Suite of computational materials science tools', include_package_data=True, long_description=open('README.md').read(), install_requires=[ "Django >=1.6.2, <1.7", "PuLP", "numpy", "scipy", "MySQL-python", "matplotlib", "networkx", "pytest", "python-memcached", "ase", "django-extensions", "lxml", "pyspglib == 1.8.3.1", "PyCifRW >= 4.3", "pexpect", "pyparsing", "PyYAML", "scikit-learn" ], )
Remove acme challenge and enable forcing https
// This script is used to serve the built files in production and proxy api requests to the service. // Would be preferrable to replace with apache. const express = require('express'); const proxy = require('express-http-proxy'); const compression = require('compression'); const path = require('path'); const app = express(); function forceHttps(request, response, next) { if (request.headers['x-forwarded-proto'] !== 'https') { return response.redirect(301, `https://${request.get('host')}${request.url}`); } return next(); } app.use(compression()); app.use(forceHttps); app.use(express.static(path.join(__dirname, '..', 'build'))); app.use('/api', proxy('https://onboarding-service.tuleva.ee')); app.get('*', (request, response) => response.sendFile(path.join(__dirname, '..', 'build', 'index.html'))); const port = process.env.PORT || 8080; app.listen(port, () => console.log(`Static server running on ${port}`)); // eslint-disable-line
// This script is used to serve the built files in production and proxy api requests to the service. // Would be preferrable to replace with apache. const express = require('express'); const proxy = require('express-http-proxy'); const compression = require('compression'); const path = require('path'); const app = express(); // function forceHttps(request, response, next) { // if (request.headers['x-forwarded-proto'] !== 'https') { // return response.redirect(301, `https://${request.get('host')}${request.url}`); // } // return next(); // } app.use(compression()); // app.use(forceHttps); app.use(express.static(path.join(__dirname, '..', 'build'))); app.use('/api', proxy('https://onboarding-service.tuleva.ee')); app.get('/.well-known/acme-challenge/aqfyXwYn_9RtkQy64cwXdzMrRpjW2B4MwtUbtl7kKPk', (request, response) => response.send('aqfyXwYn_9RtkQy64cwXdzMrRpjW2B4MwtUbtl7kKPk.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE')); app.get('*', (request, response) => response.sendFile(path.join(__dirname, '..', 'build', 'index.html'))); const port = process.env.PORT || 8080; app.listen(port, () => console.log(`Static server running on ${port}`)); // eslint-disable-line
Use global directive to avoid jslint errors
// Avoid jslint errors for known globals /*global L*/ var LocationMap = { 'initialize': function initialize() { // Map centered in NowSecure HQ by default this.map = L.map('map').setView([40.2001925,-89.0876265], 3); this.markerCluster = L.markerClusterGroup(); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(this.map); this.map.addLayer(this.markerCluster); }, 'addMarkers': function addMarkers(markersData) { console.log('Adding ' + markersData.length + ' markers'); markersData.forEach(function(markerData) { var marker = L.marker([markerData.latitude, markerData.longitude]); var text = 'Filename: ' + markerData.filename; if (markerData.datetime) { text += '<br>GPS datetime: ' + markerData.datetime; } marker.bindPopup(text); this.markerCluster.addLayer(marker); }, this); } };
var LocationMap = { 'initialize': function initialize() { // Map centered in NowSecure HQ by default this.map = L.map('map').setView([40.2001925,-89.0876265], 3); this.markerCluster = L.markerClusterGroup(); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(this.map); this.map.addLayer(this.markerCluster); }, 'addMarkers': function addMarkers(markersData) { console.log('Adding ' + markersData.length + ' markers'); markersData.forEach(function(markerData) { var marker = L.marker([markerData.latitude, markerData.longitude]); var text = 'Filename: ' + markerData.filename; if (markerData.datetime) { text += '<br>GPS datetime: ' + markerData.datetime; } marker.bindPopup(text); this.markerCluster.addLayer(marker); }, this); } };
Remove stunnel_pass from the crash reporter
package com.ubergeek42.WeechatAndroid; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import android.app.Application; @ReportsCrashes(formKey = "", formUri = "http://ubergeek42.com/android/submit.php", excludeMatchingSharedPreferencesKeys={"(ssh_pass|ssh_user|password|stunnel_pass)"}, mode = ReportingInteractionMode.NOTIFICATION, resNotifTickerText = R.string.crash_notif_ticker_text, resNotifTitle = R.string.crash_notif_title, resNotifText = R.string.crash_notif_text, resDialogText = R.string.crash_dialog_text, resDialogCommentPrompt = R.string.crash_dialog_comment_prompt ) public class WeechatApplication extends Application { @Override public void onCreate() { super.onCreate(); // The following line triggers the initialization of ACRA ACRA.init(this); } }
package com.ubergeek42.WeechatAndroid; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import android.app.Application; @ReportsCrashes(formKey = "", formUri = "http://ubergeek42.com/android/submit.php", excludeMatchingSharedPreferencesKeys={"(ssh_pass|ssh_user|password)"}, mode = ReportingInteractionMode.NOTIFICATION, resNotifTickerText = R.string.crash_notif_ticker_text, resNotifTitle = R.string.crash_notif_title, resNotifText = R.string.crash_notif_text, resDialogText = R.string.crash_dialog_text, resDialogCommentPrompt = R.string.crash_dialog_comment_prompt ) public class WeechatApplication extends Application { @Override public void onCreate() { super.onCreate(); // The following line triggers the initialization of ACRA ACRA.init(this); } }
Change to new event form instead of to selecting an event
'use strict'; export default class NewEventCtrl { /*@ngInject*/ constructor($scope) { $scope.event = {info:{}}; $scope.stage = { select: false, create: true, assign: false, done: false } $scope.doneSelect = function(create){ $scope.stage.select = false; if (create){ $scope.stage.create = true; } else{ $scope.stage.assign = true; } } $scope.doneCreate = function(){ $scope.stage.create = false; $scope.stage.assign = true; } $scope.doneAssign = function(){ $scope.stage.assign = false; $scope.stage.done = true; } } }
'use strict'; export default class NewEventCtrl { /*@ngInject*/ constructor($scope) { $scope.event = {info:{}}; $scope.stage = { select: true, create: false, assign: false, done: false } $scope.doneSelect = function(create){ $scope.stage.select = false; if (create){ $scope.stage.create = true; } else{ $scope.stage.assign = true; } } $scope.doneCreate = function(){ $scope.stage.create = false; $scope.stage.assign = true; } $scope.doneAssign = function(){ $scope.stage.assign = false; $scope.stage.done = true; } } }
Fix bug with url refernce to server
const PORT = '6882' const ROOT = location.href.indexOf('reuvenliran') > 0 ? 'http://reuvenliran.hopto.org:' : location.href export const ROOT_URL = ROOT.indexOf('8080') ? ROOT.replace('8080', PORT) : ROOT + PORT + '/' export const ROOT_URL_API = ROOT_URL + 'api' export const YOUTUBE_CONSTS = { YOUTUBE: 'Youtube', URL: 'http://www.youtube.com/embed/', API: 'enablejsapi=1', AUTOPLAY: 'autoplay=1', API_URL: 'http://www.youtube.com/iframe_api' } export const DOWNLOAD_YOUTUBE = '//www.youtubeinmp3.com/fetch/?video=https://www.youtube.com/watch?v=' export const BASE_COLOR1 = '#192d50' export const HEADER_FONT_COLOR = '#dfceba' export const BASE_COLOR2 = '#dfceba' export const BASE_COLOR3 = '#f7f6f7' export const TABLE_HEADER_FONT_COLOR = '#4f6073' export const TABLE_FONT_COLOR = '#030b15' export const googleAutoSuggestURL = `//suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=`
const PORT = '6882' const ROOT = location.href.indexOf('localhost') > 0 ? 'http://localhost:' : 'http://192.168.5.102:' export const ROOT_URL = ROOT + PORT + '/' export const ROOT_URL_API = ROOT_URL + 'api' export const YOUTUBE_CONSTS = { YOUTUBE: 'Youtube', URL: 'http://www.youtube.com/embed/', API: 'enablejsapi=1', AUTOPLAY: 'autoplay=1', API_URL: 'http://www.youtube.com/iframe_api' } export const DOWNLOAD_YOUTUBE = '//www.youtubeinmp3.com/fetch/?video=https://www.youtube.com/watch?v=' export const BASE_COLOR1 = '#192d50' export const HEADER_FONT_COLOR = '#dfceba' export const BASE_COLOR2 = '#dfceba' export const BASE_COLOR3 = '#f7f6f7' export const TABLE_HEADER_FONT_COLOR = '#4f6073' export const TABLE_FONT_COLOR = '#030b15' export const googleAutoSuggestURL = `//suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=`
Use original LexicalIDs in Access
from thinglang.lexer.symbols.base import LexicalIdentifier, LexicalAccess from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thinglang.utils.type_descriptors import ValueType class Access(BaseToken): def __init__(self, slice): super(Access, self).__init__(slice) self.target = [x for x in slice if not isinstance(x, LexicalAccess)] def describe(self): return '.'.join(str(x) for x in self.target) class ArgumentListPartial(ListInitializationPartial): pass class ArgumentListDecelerationPartial(ArgumentListPartial): pass class ArgumentList(ListInitialization): pass class MethodCall(BaseToken, ValueType): def __init__(self, slice): super(MethodCall, self).__init__(slice) self.target, self.arguments = slice self.value = self if not self.arguments: self.arguments = ArgumentList() def describe(self): return 'target={}, args={}'.format(self.target, self.arguments) def replace(self, original, replacement): self.arguments.replace(original, replacement) class ReturnStatement(DefinitionPairToken): def __init__(self, slice): super().__init__(slice) self.value = slice[1]
from thinglang.lexer.symbols.base import LexicalIdentifier from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thinglang.utils.type_descriptors import ValueType class Access(BaseToken): def __init__(self, slice): super(Access, self).__init__(slice) self.target = [x.value for x in slice if isinstance(x, LexicalIdentifier)] def describe(self): return '.'.join(self.target) class ArgumentListPartial(ListInitializationPartial): pass class ArgumentListDecelerationPartial(ArgumentListPartial): pass class ArgumentList(ListInitialization): pass class MethodCall(BaseToken, ValueType): def __init__(self, slice): super(MethodCall, self).__init__(slice) self.target, self.arguments = slice self.value = self if not self.arguments: self.arguments = ArgumentList() def describe(self): return 'target={}, args={}'.format(self.target, self.arguments) def replace(self, original, replacement): self.arguments.replace(original, replacement) class ReturnStatement(DefinitionPairToken): def __init__(self, slice): super().__init__(slice) self.value = slice[1]
Test asset method name correction - method name was mismatching the purpose (using an `object` hint)
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ declare(strict_types=1); namespace ProxyManagerTestAsset; /** * Class with a object type hint in a method - used to test iterable type hint generation * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class ObjectTypeHintClass { /** * @param object $parameter * * @return object */ public function objectTypeHintMethod(object $parameter) { return $parameter; } }
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ declare(strict_types=1); namespace ProxyManagerTestAsset; /** * Class with a object type hint in a method - used to test iterable type hint generation * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class ObjectTypeHintClass { /** * @param object $parameter * * @return object */ public function iterableTypeHintMethod(object $parameter) { return $parameter; } }
Use bson's JSON util to handle ObjectIds in a JSON context
import os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)
Return easily identifiable values from User methods.
class User(object): """An importable dummy class used for testing purposes.""" class_attribute = 'foo' @staticmethod def static_method(): return 'static_method return value' @classmethod def class_method(cls): return 'class_method return value' def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def instance_method(self): return 'instance_method return value' def method_with_varargs(self, *args): return 'method_with_varargs return value' def method_with_default_args(self, foo, bar='baz'): return 'method_with_default_args return value' def method_with_varkwargs(self, **kwargs): return 'method_with_varkwargs return value' def method_with_positional_arguments(self, foo): return 'method_with_positional_arguments return value'
class User(object): """An importable dummy class used for testing purposes.""" class_attribute = 'foo' @staticmethod def static_method(): pass @classmethod def class_method(cls): return 'class method' def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def instance_method(self): pass def method_with_varargs(self, *args): pass def method_with_default_args(self, foo, bar='baz'): pass def method_with_varkwargs(self, **kwargs): pass def method_with_positional_arguments(self, foo): pass
Fix tiny typo - will help for google searches!
/*! { "name": "Local Storage", "property": "localstorage", "caniuse": "namevalue-storage", "tags": ["storage"], "knownBugs": [], "notes": [], "warnings": [], "polyfills": [ "joshuabell-polyfill", "cupcake", "storagepolyfill", "amplifyjs", "yui-cacheoffline" ] } !*/ define(['Modernizr'], function(Modernizr) { // In FF4, if disabled, window.localStorage should === null. // Normally, we could not test that directly and need to do a // `('localStorage' in window) && ` test first because otherwise Firefox will // throw bugzil.la/365772 if cookies are disabled // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem // will throw the exception: // QUOTA_EXCEEDED_ERROR DOM Exception 22. // Peculiarly, getItem and removeItem calls do not throw. // Because we are forced to try/catch this, we'll go aggressive. // Just FWIW: IE8 Compat mode supports these features completely: // www.quirksmode.org/dom/html5.html // But IE8 doesn't support either with local files Modernizr.addTest('localstorage', function() { var mod = 'modernizr'; try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch (e) { return false; } }); });
/*! { "name": "Local Storage", "property": "localstorage", "caniuse": "namevalue-storage", "tags": ["storage"], "knownBugs": [], "notes": [], "warnings": [], "polyfills": [ "joshuabell-polyfill", "cupcake", "storagepolyfill", "amplifyjs", "yui-cacheoffline" ] } !*/ define(['Modernizr'], function(Modernizr) { // In FF4, if disabled, window.localStorage should === null. // Normally, we could not test that directly and need to do a // `('localStorage' in window) && ` test first because otherwise Firefox will // throw bugzil.la/365772 if cookies are disabled // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem // will throw the exception: // QUOTA_EXCEEDED_ERRROR DOM Exception 22. // Peculiarly, getItem and removeItem calls do not throw. // Because we are forced to try/catch this, we'll go aggressive. // Just FWIW: IE8 Compat mode supports these features completely: // www.quirksmode.org/dom/html5.html // But IE8 doesn't support either with local files Modernizr.addTest('localstorage', function() { var mod = 'modernizr'; try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch (e) { return false; } }); });
Use LoginFailedError if password != hash
package forms import ( "bones/entities" "bones/repositories" "bones/validation" "code.google.com/p/go.crypto/bcrypt" "errors" "net/http" ) var LoginFailedError = errors.New("Login failed") type LoginForm struct { Request *http.Request `schema:"-"` User *entities.User `schema:"-"` Email string `schema:"email"` Password string `schema:"password"` } func (f *LoginForm) Validate() error { validate := validation.New() validate.String(f.Email).NotEmpty("Email cannot be blank") validate.String(f.Password).NotEmpty("Password cannot be blank") return validate.Result() } func (f *LoginForm) Save() error { var err error f.User, err = repositories.Users.FindByEmail(f.Email) if err != nil { if err == repositories.NotFoundError { return LoginFailedError } return err } err = bcrypt.CompareHashAndPassword([]byte(f.User.Password), []byte(f.Password)) if err != nil { return LoginFailedError } // TODO save session to repository, update cookie in action return nil }
package forms import ( "bones/entities" "bones/repositories" "bones/validation" "code.google.com/p/go.crypto/bcrypt" "errors" "net/http" ) var LoginFailedError = errors.New("Login failed") type LoginForm struct { Request *http.Request `schema:"-"` User *entities.User `schema:"-"` Email string `schema:"email"` Password string `schema:"password"` } func (f *LoginForm) Validate() error { validate := validation.New() validate.String(f.Email).NotEmpty("Email cannot be blank") validate.String(f.Password).NotEmpty("Password cannot be blank") return validate.Result() } func (f *LoginForm) Save() error { var err error f.User, err = repositories.Users.FindByEmail(f.Email) if err != nil { if err == repositories.NotFoundError { return LoginFailedError } return err } err = bcrypt.CompareHashAndPassword([]byte(f.User.Password), []byte(f.Password)) if err != nil { return err } // TODO save session to repository, update cookie in action return nil }
Fix not being able to /status offline players
package org.sweetiebelle.mcprofiler.bukkit; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; import net.milkbowl.vault.chat.Chat; /** * This class will allow for multiple Permissions Plugins to be easily * supported. * */ class PermissionsController { private Chat chat; PermissionsController() { RegisteredServiceProvider<Chat> rsp = Bukkit.getServer().getServicesManager().getRegistration(Chat.class); this.chat = rsp.getProvider(); } /** * Worker class for getting a prefix from a permissions plugin. * * @param uuid player UUID * @return the prefix, or &b if no prefix providing plugin was found. */ public String getPrefix(final UUID uuid) { if (chat != null) { OfflinePlayer player = Bukkit.getServer().getOfflinePlayer(uuid); String pref = chat.getPlayerPrefix((String) null, player); return pref.replace('&', ChatColor.COLOR_CHAR); } return ChatColor.AQUA + ""; } }
package org.sweetiebelle.mcprofiler.bukkit; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import net.milkbowl.vault.chat.Chat; /** * This class will allow for multiple Permissions Plugins to be easily * supported. * */ class PermissionsController { private Chat chat; PermissionsController() { RegisteredServiceProvider<Chat> rsp = Bukkit.getServer().getServicesManager().getRegistration(Chat.class); this.chat = rsp.getProvider(); } /** * Worker class for getting a prefix from a permissions plugin. * * @param uuid player UUID * @return the prefix, or b if no prefix providing plugin was found. */ public String getPrefix(final UUID uuid) { if (chat != null) { Player player = Bukkit.getServer().getPlayer(uuid); String pref = chat.getPlayerPrefix(player); return pref.replace('&', ChatColor.COLOR_CHAR); } return "b"; } }
Test for decompile against all classes in the primary resource
package me.coley.recaf; import me.coley.recaf.decompile.fernflower.FernFlowerDecompiler; import me.coley.recaf.workspace.*; import org.junit.jupiter.api.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; public class DecompileTest extends Base { private Workspace workspace; @BeforeEach public void setup() { try { JavaResource resource = new JarResource(getClasspathFile("inherit.jar")); resource.getClasses(); resource.getResources(); workspace = new Workspace(resource); } catch(IOException ex) { fail(ex); } } @Nested public class FernFlower { @Test public void testFernFlower() { FernFlowerDecompiler decompiler = new FernFlowerDecompiler(); for (String name : workspace.getPrimaryClassNames()) { String decomp = decompiler.decompile(workspace, name); assertNotNull(decomp); } } } }
package me.coley.recaf; import me.coley.recaf.decompile.fernflower.FernFlowerDecompiler; import me.coley.recaf.workspace.*; import org.junit.jupiter.api.*; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; public class DecompileTest extends Base { private Workspace workspace; @BeforeEach public void setup() { try { JavaResource resource = new JarResource(getClasspathFile("inherit.jar")); resource.getClasses(); resource.getResources(); workspace = new Workspace(resource); } catch(IOException ex) { fail(ex); } } @Nested public class FernFlower { @Test public void testFernFlower() { String className = "test/Yoda"; FernFlowerDecompiler decompiler = new FernFlowerDecompiler(); String decomp = decompiler.decompile(workspace, className); assertNotNull(decomp); } } }
Return immediately if not search string provided
/** * Determines whether one string may be found within another string, returning true or false as appropriate. * @param {String} subjectString The string to process. * @param {String} searchString A string to be searched for within the original string. * @param {Number} [position=0] The position in the original string at which to begin searching for searchString; defaults to 0. * @returns {Boolean} True if searchString is found within subjectString, else false. */ function contains(subjectString, searchString, position) { 'use strict'; var subjectLength, searchLength; if (!searchString) { return false; } if (String.prototype.includes) { return subjectString.includes(searchString, position); } position = parseInt(position, 10) || 0; subjectLength = subjectString.length; searchLength = searchString.length; return position + searchLength <= subjectLength ? subjectString.indexOf(searchString, position) !== -1 : false; }
/** * Determines whether one string may be found within another string, returning true or false as appropriate. * @param {String} subjectString The string to process. * @param {String} searchString A string to be searched for within the original string. * @param {Number} [position=0] The position in the original string at which to begin searching for searchString; defaults to 0. * @returns {Boolean} True if searchString is found within subjectString, else false. */ function contains(subjectString, searchString, position) { 'use strict'; var subjectLength, searchLength; if (String.prototype.includes) { return subjectString.includes(searchString, position); } if (!searchString) { return false; } position = parseInt(position, 10) || 0; subjectLength = subjectString.length; searchLength = searchString.length; return position + searchLength <= subjectLength ? subjectString.indexOf(searchString, position) !== -1 : false; }
Remove references to plugins in multiple bundles config It looks like they don't need to be excluded at all.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. require.config({ baseUrl: process._RJS_baseUrl(2), // relative to this config file (not baseUrl) dir: "../build-output/_multiple-bundles", modules: [ { name: "readium-js", create: true, include: ["readium_js/Readium"], exclude: ["readium-external-libs", "readium-shared-js", "readium-cfi-js"] } ] //, // unlike with single-bundle, this does not work! :( // paths: // { // "version": // process._RJS_rootDir(2) + '/build-output/version', // } });
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. require.config({ baseUrl: process._RJS_baseUrl(2), // relative to this config file (not baseUrl) dir: "../build-output/_multiple-bundles", modules: [ { name: "readium-js", create: true, include: ["readium_js/Readium"], exclude: ["readium-external-libs", "readium-shared-js", "readium-cfi-js", "readium-plugin-example", "readium-plugin-annotations"] } ] //, // unlike with single-bundle, this does not work! :( // paths: // { // "version": // process._RJS_rootDir(2) + '/build-output/version', // } });
Add adminKey, will be for early access to dz2 Can be turned on with `launchctl setenv KEYBASE_FEATURES admin`
/* @flow */ import getenv from 'getenv' // To enable a feature, include it in the environment variable KEYBASE_FEATURES. // For example, KEYBASE_FEATURES=tracker2,login,awesomefeature const tracker2Key = 'tracker2' const loginKey = 'login' const mobileAppsExistKey = 'mobileAppsExist' const adminKey = 'admin' type FeatureFlags = { 'tracker2': boolean, 'login': boolean, 'mobileAppsExist': boolean, 'admin': boolean } let features = getenv.array('KEYBASE_FEATURES', 'string', '') const tracker2 = features.includes(tracker2Key) || features.includes(adminKey) const login = features.includes(loginKey) const mobileAppsExist = features.includes(mobileAppsExistKey) const admin = features.include(adminKey) const ff: FeatureFlags = { tracker2, login, mobileAppsExist, admin } if (__DEV__) { console.log('Features', ff) } export default ff export { tracker2, login, mobileAppsExist, admin }
/* @flow */ import getenv from 'getenv' // To enable a feature, include it in the environment variable KEYBASE_FEATURES. // For example, KEYBASE_FEATURES=tracker2,login,awesomefeature const tracker2Key = 'tracker2' const loginKey = 'login' const mobileAppsExistKey = 'mobileAppsExist' type FeatureFlags = { 'tracker2': boolean, 'login': boolean, 'mobileAppsExist': boolean } let features = getenv.array('KEYBASE_FEATURES', 'string', '') const tracker2 = features.includes(tracker2Key) const login = features.includes(loginKey) const mobileAppsExist = features.includes(mobileAppsExistKey) const ff: FeatureFlags = { tracker2, login, mobileAppsExist } if (__DEV__) { console.log('Features', ff) } export default ff export { tracker2, login, mobileAppsExist }
Add baseline for error baseline
//// [objectTypesWithOptionalProperties2.ts] // Illegal attempts to define optional methods var a: { x()?: number; // error } interface I { x()?: number; // error } class C { x()?: number; // error } interface I2<T> { x()?: T; // error } class C2<T> { x()?: T; // error } var b = { x()?: 1 // error } //// [objectTypesWithOptionalProperties2.js] // Illegal attempts to define optional methods var a; var C = (function () { function C() { } C.prototype.x = ; return C; })(); var C2 = (function () { function C2() { } C2.prototype.x = ; return C2; })(); var b = { x: function () { }, 1: // error // error };
//// [objectTypesWithOptionalProperties2.ts] // Illegal attempts to define optional methods var a: { x()?: number; // error } interface I { x()?: number; // error } class C { x()?: number; // error } interface I2<T> { x()?: T; // error } class C2<T> { x()?: T; // error } var b = { x()?: 1 // error } //// [objectTypesWithOptionalProperties2.js] // Illegal attempts to define optional methods var a; var C = (function () { function C() { } C.prototype.x = ; return C; })(); var C2 = (function () { function C2() { } C2.prototype.x = ; return C2; })(); var b = { x: function () { }, 1: // error };
Set API URL for production
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true 'query-params-new': true }, }, APP: { API_NAMESPACE: '', } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.APP.API_HOST = process.env.API_URL; } if (environment === 'test') { } if (environment === 'production') { ENV.APP.API_HOST = 'http://api.freemusic.ninja'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true 'query-params-new': true }, }, APP: { API_NAMESPACE: '', } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.APP.API_HOST = process.env.API_URL; } if (environment === 'test') { } if (environment === 'production') { } return ENV; };
Fix render error for list group item children
/** * breit-wheeler * * Copyright © 2016 Allen Smith &lt;loranallensmith@github.com&gt;. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /** @jsx etch.dom */ import etch from 'etch'; import classNames from 'classnames'; import EtchComponent from './etch-component'; import Icon from './icon'; class ListGroupItem extends EtchComponent { render() { let itemType = this.properties.header === true ? 'header' : 'item'; let classes = classNames( [`list-group-${itemType}`], { 'active': this.properties.active === true }, this.properties.classNames, ); return ( <li {...this.properties.attributes} className={classes}> {this.children.map(function(child) { return child.render(); })} </li> ); } } export default ListGroupItem;
/** * breit-wheeler * * Copyright © 2016 Allen Smith &lt;loranallensmith@github.com&gt;. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /** @jsx etch.dom */ import etch from 'etch'; import classNames from 'classnames'; import EtchComponent from './etch-component'; import Icon from './icon'; class ListGroupItem extends EtchComponent { render() { let itemType = this.properties.header === true ? 'header' : 'item'; let classes = classNames( [`list-group-${itemType}`], { 'active': this.properties.active === true }, this.properties.classNames, ); return ( <li {...this.properties.attributes} className={classes}> {this.children.map(function(child) { return {child} })} </li> ); } } export default ListGroupItem;
Remove weak dependency on oauth-encryption. Only the accounts-add-service package uses it and it only uses it when it exists, and if a services uses oauth, it would already require oauth-encryption, so there is no reason to add the dependency there either.
Package.describe({ name: 'brettle:accounts-multiple', version: '0.0.1', summary: 'Handles users that login with multiple services.', git: 'git@github.com:brettle/meteor-accounts-multiple.git', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); api.use('accounts-base', 'server'); api.use('underscore', 'server'); api.addFiles('accounts-multiple-server.js', 'server'); api.export('AccountsMultiple'); }); Package.onTest(function(api) { api.use('brettle:accounts-multiple'); api.use('brettle:accounts-testing-support'); api.use('brettle:accounts-anonymous'); api.use('tinytest'); api.use('underscore'); api.use('accounts-password'); api.addFiles('accounts-multiple-server-tests.js', 'server'); });
Package.describe({ name: 'brettle:accounts-multiple', version: '0.0.1', summary: 'Handles users that login with multiple services.', git: 'git@github.com:brettle/meteor-accounts-multiple.git', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); api.use('accounts-base', 'server'); api.use('underscore', 'server'); api.use('oauth-encryption', 'server', 'weak'); api.addFiles('accounts-multiple-server.js', 'server'); api.export('AccountsMultiple'); }); Package.onTest(function(api) { api.use('brettle:accounts-multiple'); api.use('brettle:accounts-testing-support'); api.use('brettle:accounts-anonymous'); api.use('tinytest'); api.use('underscore'); api.use('accounts-password'); api.addFiles('accounts-multiple-server-tests.js', 'server'); });
Update faves to items, remove guest middleware
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Item; use Auth; class ItemsController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); } public function readItems() { $items = Item::with('category')->get(); return $items; } public function storeItem(Request $request) { $data = new Item(); $data->name = $request->name; $data->category_id = $request->category_id; $data->user_id = Auth::user()->id; $data->save(); return $data; } public function deleteItem(Request $request) { Item::find($request->id)->delete (); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Item; use Auth; class ItemsController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); } public function readItems() { $faves = Item::all(); return $faves; } public function storeItem(Request $request) { $data = new Item(); $data->name = $request->name; $data->user_id = Auth::user()->id; $data->save(); return $data; } public function deleteItem(Request $request) { Item::find($request->id)->delete (); } }
[DVI-34] Make code conform to Checkstyle standards
/** * Copyright (C) 2009 - 2010 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.security.option; import com.opengamma.financial.Currency; import com.opengamma.id.Identifier; import com.opengamma.util.time.Expiry; /** * An American equity option security. */ public class AmericanVanillaEquityOptionSecurity extends EquityOptionSecurity implements AmericanVanillaOption { /** * Creates the security. * @param optionType the type of option CALL or PUT * @param strike the strike price * @param expiry the expire date * @param underlyingIdentifier Identifier for underlying equity * @param currency currency in which it trades * @param pointValue the option point value * @param exchange exchange where the option trades */ public AmericanVanillaEquityOptionSecurity(final OptionType optionType, final double strike, final Expiry expiry, final Identifier underlyingIdentifier, final Currency currency, final double pointValue, final String exchange) { super(optionType, strike, expiry, underlyingIdentifier, currency, pointValue, exchange); } //------------------------------------------------------------------------- @Override public <T> T accept(final OptionVisitor<T> visitor) { return visitor.visitAmericanVanillaOption(this); } @Override public <T> T accept(final EquityOptionSecurityVisitor<T> visitor) { return visitor.visitAmericanVanillaEquityOptionSecurity(this); } }
/** * Copyright (C) 2009 - 2010 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.security.option; import com.opengamma.financial.Currency; import com.opengamma.id.Identifier; import com.opengamma.id.UniqueIdentifier; import com.opengamma.util.time.Expiry; /** * An American equity option security. */ public class AmericanVanillaEquityOptionSecurity extends EquityOptionSecurity implements AmericanVanillaOption { /** * Creates the security. * @param optionType * @param strike * @param expiry * @param underlyingIdentifier * @param currency * @param exchange */ public AmericanVanillaEquityOptionSecurity(final OptionType optionType, final double strike, final Expiry expiry, final Identifier underlyingIdentifier, final Currency currency, final double pointValue, final String exchange) { super(optionType, strike, expiry, underlyingIdentifier, currency, pointValue, exchange); } //------------------------------------------------------------------------- @Override public <T> T accept(final OptionVisitor<T> visitor) { return visitor.visitAmericanVanillaOption(this); } @Override public <T> T accept(final EquityOptionSecurityVisitor<T> visitor) { return visitor.visitAmericanVanillaEquityOptionSecurity(this); } }
Add riot.render.tag function to create raw tag
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') riot.render = function(tagName, opts) { var tag = riot.render.tag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return riot.render.tag(tagName, opts).root } riot.render.tag = function(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag }
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') function createTag(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag } riot.render = function(tagName, opts) { var tag = createTag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return createTag(tagName, opts).root }
Fix incorrect naming of registerSqsFifoConnector method
<?php namespace Maqe\LaravelSqsFifo; use Illuminate\Support\ServiceProvider; use Maqe\LaravelSqsFifo\Connectors\SqsFifoConnector; class LaravelSqsFifoServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $queueManager = $this->app['queue']; $this->registerSqsFifoConnector($queueManager); } /** * Register the Amazon SQS FIFO queue connector. * * @param \Illuminate\Queue\QueueManager $manager * @return void */ protected function registerSqsFifoConnector($manager) { $manager->addConnector('sqsfifo', function () { return new SqsFifoConnector; }); } }
<?php namespace Maqe\LaravelSqsFifo; use Illuminate\Support\ServiceProvider; use Maqe\LaravelSqsFifo\Connectors\SqsFifoConnector; class LaravelSqsFifoServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $queueManager = $this->app['queue']; $this->registerSqsFifoConnector($queueManager); } /** * Register the Amazon SQS FIFO queue connector. * * @param \Illuminate\Queue\QueueManager $manager * @return void */ protected function registerSqsConnector($manager) { $manager->addConnector('sqsfifo', function () { return new SqsFifoConnector; }); } }
Add tests for pbias and nashsutcliffe
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
Enable SerializeFeature.MapSortField for deterministic order
package com.alibaba.json.bvt.jsonp; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; /** * Created by wenshao on 21/02/2017. */ public class JSONPParseTest3 extends TestCase { public void test_f() throws Exception { String text = "parent.callback ({'id':1, 'name':'ido)nans'},1,2 ); /**/ "; JSONPObject jsonpObject = (JSONPObject) JSON.parseObject(text, JSONPObject.class); assertEquals("parent.callback", jsonpObject.getFunction()); assertEquals(3, jsonpObject.getParameters().size()); JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); assertEquals(1, param.get("id")); assertEquals("ido)nans", param.get("name")); String json = JSON.toJSONString(jsonpObject, SerializerFeature.BrowserSecure, SerializerFeature.MapSortField); assertEquals("/**/parent.callback({\"id\":1,\"name\":\"ido\\u0029nans\"},1,2)", json); } }
package com.alibaba.json.bvt.jsonp; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; /** * Created by wenshao on 21/02/2017. */ public class JSONPParseTest3 extends TestCase { public void test_f() throws Exception { String text = "parent.callback ({'id':1, 'name':'ido)nans'},1,2 ); /**/ "; JSONPObject jsonpObject = (JSONPObject) JSON.parseObject(text, JSONPObject.class); assertEquals("parent.callback", jsonpObject.getFunction()); assertEquals(3, jsonpObject.getParameters().size()); JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); assertEquals(1, param.get("id")); assertEquals("ido)nans", param.get("name")); String json = JSON.toJSONString(jsonpObject, SerializerFeature.BrowserSecure); assertEquals("/**/parent.callback({\"name\":\"ido\\u0029nans\",\"id\":1},1,2)", json); } }
Add another test to make sure you can import settings and change them before importing the singleton
import unittest from nose.tools import * import mock from gargoyle.settings import manager import gargoyle.models class TestGargoyle(unittest.TestCase): other_engine = dict() def test_gargoyle_global_is_a_switch_manager(self): reload(gargoyle.singleton) self.assertIsInstance(gargoyle.singleton.gargoyle, gargoyle.models.Manager) def test_consructs_manager_with_storage_engine_from_settings(self): with mock.patch('gargoyle.models.Manager') as init: init.return_value = None reload(gargoyle.singleton) expected = ((), {'storage': manager.storage_engine}) eq_(init.call_args, expected) def test_can_change_storage_engine_before_importing(self): with mock.patch('gargoyle.models.Manager') as init: init.return_value = None manager.storage_engine = self.other_engine reload(gargoyle.singleton) expected = ((), dict(storage=self.other_engine)) eq_(init.call_args, expected)
import unittest from nose.tools import * import mock from gargoyle.settings import manager import gargoyle.models class TestGargoyle(unittest.TestCase): def test_gargoyle_global_is_a_switch_manager(self): reload(gargoyle.singleton) self.assertIsInstance(gargoyle.singleton.gargoyle, gargoyle.models.Manager) def test_consructs_manager_with_storage_engine_from_settings(self): with mock.patch('gargoyle.models.Manager') as init: init.return_value = None reload(gargoyle.singleton) expected = ((), {'storage': manager.storage_engine}) eq_(init.call_args, expected)
Add label for tail usage Signed-off-by: David Gageot <aa743a0aaec8f7d7a1f01442503957f4d7a2d634@gageot.net>
/* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "strings" ) // SkaffoldOptions are options that are set by command line arguments not included // in the config file itself type SkaffoldOptions struct { ConfigurationFile string Cleanup bool Notification bool Tail bool Profiles []string CustomTag string Namespace string } // Labels returns a map of labels to be applied to all deployed // k8s objects during the duration of the run func (opts *SkaffoldOptions) Labels() map[string]string { labels := map[string]string{} if opts.Cleanup { labels["cleanup"] = "true" } if opts.Tail { labels["tail"] = "true" } if opts.Namespace != "" { labels["namespace"] = opts.Namespace } if len(opts.Profiles) > 0 { labels["profiles"] = strings.Join(opts.Profiles, ",") } return labels }
/* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "strings" ) // SkaffoldOptions are options that are set by command line arguments not included // in the config file itself type SkaffoldOptions struct { ConfigurationFile string Cleanup bool Notification bool Tail bool Profiles []string CustomTag string Namespace string } // Labels returns a map of labels to be applied to all deployed // k8s objects during the duration of the run func (opts *SkaffoldOptions) Labels() map[string]string { labels := map[string]string{} if opts.Cleanup { labels["cleanup"] = "true" } if opts.Namespace != "" { labels["namespace"] = opts.Namespace } if len(opts.Profiles) > 0 { labels["profiles"] = strings.Join(opts.Profiles, ",") } return labels }
Fix string extraction. The "ignore" setting was getting us lots of non-string stuff.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Functionality for resolving ASCII printable strings within the debuggee's address space. """ from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'replace', maxlen) sz = pwndbg.memory.read(address, len(sz)) if not all(s in string.printable for s in sz.rstrip('\x00')): return None sz = str(sz) except Exception as e: return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...'
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Functionality for resolving ASCII printable strings within the debuggee's address space. """ from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'ignore') sz = str(sz) except Exception as e: return None if not all(s in string.printable for s in sz.rstrip('\x00')): return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...'
Check if mirage is installed
import os from core.utils.Executor import _convert_subprocess_cmd import subprocess from core.exceptions.Exceptions import OPAMConfigurationExeception def check_environment() -> bool: __opam_env__ = [ 'CAML_LD_LIBRARY_PATH', 'MANPATH', 'PERL5LIB', 'OCAML_TOPLEVEL_PATH', 'PATH' ] for var in __opam_env__: if not os.environ.get(var, None): raise OPAMConfigurationExeception PATH = os.environ.get('PATH') for path in PATH.split(':'): if path.endswith( os.path.join('.opam', 'system', 'bin') ): return True def check_mirage(): try: subprocess.check_call( _convert_subprocess_cmd('which mirage') ) except subprocess.CalledProcessError: return False else: return True
import os from core.exceptions.Exceptions import OPAMConfigurationExeception def check_environment() -> bool: __opam_env__ = [ 'CAML_LD_LIBRARY_PATH', 'MANPATH', 'PERL5LIB', 'OCAML_TOPLEVEL_PATH', 'PATH' ] for var in __opam_env__: if not os.environ.get(var, None): raise OPAMConfigurationExeception PATH = os.environ.get('PATH') for path in PATH.split(':'): if path.endswith( os.path.join('.opam', 'system', 'bin') ): return True
Improve the stop grid command test
package com.groupon.seleniumgridextras.tasks; import com.groupon.seleniumgridextras.config.RuntimeConfig; import com.sun.net.httpserver.HttpServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.net.InetSocketAddress; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class StopGridTest { private StopGrid task; private HttpServer server; private final int port = 9999; @Before public void setUp() throws Exception { task = new StopGrid(); server = HttpServer.create(new InetSocketAddress(port), 0); server.setExecutor(null); server.start(); } @After public void tearDown() throws Exception { server.stop(0); } @Test public void testGetWindowsCommand() throws Exception { assertTrue(task.getWindowsCommand("5555").contains("taskkill -F -IM ")); } @Test public void testGetLinuxCommand() throws Exception { String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid(); assertEquals(expected, task.getLinuxCommand(port)); final String portToNeverBeFound = "4444444444444444444444444444444"; assertEquals("", task.getLinuxCommand(portToNeverBeFound)); } }
package com.groupon.seleniumgridextras.tasks; import com.groupon.seleniumgridextras.config.RuntimeConfig; import com.sun.net.httpserver.HttpServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.net.InetSocketAddress; import static org.junit.Assert.assertEquals; public class StopGridTest { private StopGrid task; private HttpServer server; private final int port = 9999; @Before public void setUp() throws Exception { task = new StopGrid(); server = HttpServer.create(new InetSocketAddress(port), 0); server.setExecutor(null); server.start(); } @After public void tearDown() throws Exception { server.stop(0); } @Test public void testGetWindowsCommand() throws Exception { assertEquals( "",task.getWindowsCommand("5555")); } @Test public void testGetLinuxCommand() throws Exception { String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid(); assertEquals(expected, task.getLinuxCommand(port)); final String portToNeverBeFound = "4444444444444444444444444444444"; assertEquals("", task.getLinuxCommand(portToNeverBeFound)); } }
Check if source isn't object instead of is string We may wanna pass in different types like buffers for Node.js.
// Return Promise const mergeImages = (sources = [], options = { format: 'image/png' }) => new Promise(resolve => { // Setup browser/node specific variables const canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas'); const Image = options.Canvas ? options.Canvas.Image : window.Image; // Load sources const images = sources.map(source => new Promise(resolve => { // Convert strings to objects if (source.constructor.name !== 'Object') { source = { src: source }; } // Resolve source and img when loaded const img = new Image(); img.onload = () => resolve(Object.assign({}, source, { img })); img.src = source.src; })); // Get canvas context const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions const getSize = dim => options[dim] || Math.max(...images.map(image => image.img[dim])); canvas.width = getSize('width'); canvas.height = getSize('height'); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL(options.format)); }); }); module.exports = mergeImages;
// Return Promise const mergeImages = (sources = [], options = { format: 'image/png' }) => new Promise(resolve => { // Setup browser/node specific variables const canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas'); const Image = options.Canvas ? options.Canvas.Image : window.Image; // Load sources const images = sources.map(source => new Promise(resolve => { // Convert strings to objects if (typeof source === 'string') { source = { src: source }; } // Resolve source and img when loaded const img = new Image(); img.onload = () => resolve(Object.assign({}, source, { img })); img.src = source.src; })); // Get canvas context const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions const getSize = dim => options[dim] || Math.max(...images.map(image => image.img[dim])); canvas.width = getSize('width'); canvas.height = getSize('height'); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL(options.format)); }); }); module.exports = mergeImages;
Change format in input file Signed-off-by: soupette <0a59f0508aa203bc732745954131d022d9f538a9@gmail.com>
import React from 'react'; import PropTypes from 'prop-types'; import { get } from 'lodash'; import { prefixFileUrlWithBackendUrl } from 'strapi-helper-plugin'; import CardPreview from '../CardPreview'; import Flex from '../Flex'; import Chevron from './Chevron'; const InputFilePreview = ({ file, onClick, isSlider }) => { const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'small', 'url'], file.url)); return ( <Flex key={file.id} style={{ height: '100%' }} alignItems="center" justifyContent="space-between" > {isSlider && <Chevron side="left" onClick={() => onClick(false)} />} <CardPreview hasIcon url={fileUrl} type={file.mime} /> {isSlider && <Chevron side="right" onClick={() => onClick(true)} />} </Flex> ); }; InputFilePreview.propTypes = { file: PropTypes.object, isSlider: PropTypes.bool, onClick: PropTypes.func.isRequired, }; InputFilePreview.defaultProps = { isSlider: false, file: null, }; export default InputFilePreview;
import React from 'react'; import PropTypes from 'prop-types'; import { get } from 'lodash'; import { prefixFileUrlWithBackendUrl } from 'strapi-helper-plugin'; import CardPreview from '../CardPreview'; import Flex from '../Flex'; import Chevron from './Chevron'; const InputFilePreview = ({ file, onClick, isSlider }) => { const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'thumbnail', 'url'], file.url)); return ( <Flex key={file.id} style={{ height: '100%' }} alignItems="center" justifyContent="space-between" > {isSlider && <Chevron side="left" onClick={() => onClick(false)} />} <CardPreview hasIcon url={fileUrl} type={file.mime} /> {isSlider && <Chevron side="right" onClick={() => onClick(true)} />} </Flex> ); }; InputFilePreview.propTypes = { file: PropTypes.object, isSlider: PropTypes.bool, onClick: PropTypes.func.isRequired, }; InputFilePreview.defaultProps = { isSlider: false, file: null, }; export default InputFilePreview;
Work around for dump setting issue.
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): try: os.remove("local/total_settings.py") except: pass with open("local/total_settings.py", "w") as f: for key, value in dump_attrs(settings): if type(value) in (list, tuple, dict): print >>f, key, "=", value elif type(value) in (str, ): print >>f, key, "=", '"'+str(value)+'"' else: print >>f, key, "=", '"'+str(value)+'"'
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): try: os.remove("local/total_settings.py") except: pass with open("local/total_settings.py", "w") as f: for key, value in dump_attrs(settings): if type(value) in (list, tuple, dict): print >>f, key, "=", value elif type(value) in (str, ): print >>f, key, "=", '"'+str(value)+'"' else: print >>f, key, "=", str(value)
Allow empty conversations to be serialized A conversation may exist without any content. The serializer then returns an empty message value.
def user(model): if not model.is_authenticated(): return {} return { 'id': model.id, 'display_name': model.display_name, 'first_name': model.first_name, 'last_name': model.last_name, } def category(model): return { 'id': model.id, 'name': model.name, 'parent': model.parent_id, } def conversation(model): participants = [_['id'] for _ in model.participants.order_by('id').values('id')] newest_message = model.messages.order_by('-created_at').first() return { 'id': model.id, 'name': model.name, 'participants': participants, 'message': conversation_message(newest_message), } def conversation_message(model): if model: return { 'id': model.id, 'sender': model.sent_by_id, 'created_at': model.created_at.isoformat(), 'content': model.content, } else: return None
def user(model): if not model.is_authenticated(): return {} return { 'id': model.id, 'display_name': model.display_name, 'first_name': model.first_name, 'last_name': model.last_name, } def category(model): return { 'id': model.id, 'name': model.name, 'parent': model.parent_id, } def conversation(model): participants = [_['id'] for _ in model.participants.order_by('id').values('id')] newest_message = model.messages.order_by('-created_at').first() return { 'id': model.id, 'name': model.name, 'participants': participants, 'message': conversation_message(newest_message), } def conversation_message(model): return { 'id': model.id, 'sender': model.sent_by_id, 'created_at': model.created_at.isoformat(), 'content': model.content, }
Upgrade to prompt_toolkit 0.57. (Should give much better performance.)
#!/usr/bin/env python import os from setuptools import setup, find_packages long_description = open( os.path.join( os.path.dirname(__file__), 'README.rst' ) ).read() setup( name='pymux', author='Jonathan Slenders', version='0.3', license='LICENSE', url='https://github.com/jonathanslenders/', description='Pure Python terminal multiplexer.', long_description=long_description, packages=find_packages('.'), install_requires = [ 'prompt_toolkit==0.57', 'pyte>=0.4.10', 'six>=1.9.0', 'docopt>=0.6.2', ], entry_points={ 'console_scripts': [ 'pymux = pymux.entry_points.run_pymux:run', ] }, )
#!/usr/bin/env python import os from setuptools import setup, find_packages long_description = open( os.path.join( os.path.dirname(__file__), 'README.rst' ) ).read() setup( name='pymux', author='Jonathan Slenders', version='0.3', license='LICENSE', url='https://github.com/jonathanslenders/', description='Pure Python terminal multiplexer.', long_description=long_description, packages=find_packages('.'), install_requires = [ 'prompt_toolkit==0.56', 'pyte>=0.4.10', 'six>=1.9.0', 'docopt>=0.6.2', ], entry_points={ 'console_scripts': [ 'pymux = pymux.entry_points.run_pymux:run', ] }, )
Fix alias service detail display
import Ember from 'ember'; import Service from 'ui/models/service'; const esc = Ember.Handlebars.Utils.escapeExpression; var DnsService = Service.extend({ type: 'dnsService', intl: Ember.inject.service(), healthState: 'healthy', displayDetail: function() { let intl = this.get('intl'); let toTranslation = intl.tHtml('generic.to'); let noneTranslation = intl.tHtml('generic.none'); var services = ''; (this.get('consumedServicesWithNames')||[]).forEach((map, idx) => { services += '<span>'+ (idx === 0 ? '' : ', ') + (map.get('service.environmentId') === this.get('environmentId') ? '' : esc(map.get('service.displayEnvironment')) + '/') + esc(map.get('service.displayName')) + '</span>'; }); var out = '<label>'+ toTranslation +': </label>' + services || '<span class="text-muted">'+ noneTranslation +'</span>'; return out.htmlSafe(); }.property('consumedServicesWithNames.@each.{name,service}','consumedServicesUpdated', 'intl._locale'), }); export default DnsService;
import Ember from 'ember'; import Service from 'ui/models/service'; const esc = Ember.Handlebars.Utils.escapeExpression; var DnsService = Service.extend({ type: 'dnsService', intl: Ember.inject.service(), healthState: function() { let out = this.get('intl').intl.t('generic.healthy'); return out; }.property('intl._locale'), displayDetail: function() { let intl = this.get('intl'); let toTranslation = intl.tHtml('generic.to'); let noneTranslation = intl.tHtml('generic.none'); var services = ''; (this.get('consumedServicesWithNames')||[]).forEach((map, idx) => { services += '<span>'+ (idx === 0 ? '' : ', ') + (map.get('service.environmentId') === this.get('environmentId') ? '' : esc(map.get('service.displayEnvironment')) + '/') + esc(map.get('service.displayName')) + '</span>'; }); var out = '<label>'+ toTranslation +': </label>' + services || '<span class="text-muted">'+ noneTranslation +'</span>'; return out; }.property('consumedServicesWithNames.@each.{name,service}','consumedServicesUpdated', 'intl._locale'), }); export default DnsService;
Select the first overlay by default
/* See license.txt for terms of usage */ define(function(require, exports, module) { // Dependencies const React = require("react"); const { PopupPanel } = require("popup-panel"); const { OverlayStore } = require("overlay-store"); // Get overlay data from persistent store. var state = { overlays: [], selection: null } // Render panel content var panel = React.render(PopupPanel(state), document.body); // Handle refresh events sent from the chrome scope and refresh // the panel content (panel component). window.addEventListener("refresh", onRefresh); function onRefresh(event) { var data = JSON.parse(event.data); // xxxHonza: properly pick the default selection panel.setState({overlays: data, selection: data[0]}); } // Display the page content when it's ready to avoid flashing // during the page load. document.addEventListener("load", event => { document.body.removeAttribute("collapsed"); }, true); // Panel is loaded, let the chrome content send the first // 'refresh' message. postChromeMessage("panel-ready"); // End of main.js });
/* See license.txt for terms of usage */ define(function(require, exports, module) { // Dependencies const React = require("react"); const { PopupPanel } = require("popup-panel"); const { OverlayStore } = require("overlay-store"); // Get overlay data from persistent store. var state = { overlays: [], selection: null } // Render panel content var panel = React.render(PopupPanel(state), document.body); // Handle refresh events sent from the chrome scope and refresh // the panel content (panel component). window.addEventListener("refresh", onRefresh); function onRefresh(event) { var data = JSON.parse(event.data); panel.setState({overlays: data}); } // Display the page content when it's ready to avoid flashing // during the page load. document.addEventListener("load", event => { document.body.removeAttribute("collapsed"); }, true); // Panel is loaded, let the chrome content send the first // 'refresh' message. postChromeMessage("panel-ready"); // End of main.js });
Mark rule name as non-configurable Summary: This diff effectively changes nothing because, `name` attribute is fetched from unconfigured graph node from hash map by string, and it will simply fail if `name` is `select` (see also D17633433). But it's still better to add the annotation * for documentation * for compatibity with future buck where coersion is done on unconfigured graph Reviewed By: bobyangyf shipit-source-id: b26aac039b
/* * Copyright 2017-present Facebook, 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 com.facebook.buck.core.description.arg; import com.facebook.buck.core.sourcepath.SourcePath; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; import java.util.Set; import org.immutables.value.Value; /** Common arguments for build rules (but not configuration rules) */ public interface CommonDescriptionArg extends ConstructorArg, HasTargetCompatibleWith { @Hint(isConfigurable = false) String getName(); ImmutableSet<SourcePath> getLicenses(); @Value.NaturalOrder ImmutableSortedSet<String> getLabels(); @Value.Derived default boolean labelsContainsAnyOf(Set<String> labels) { return !Sets.intersection(this.getLabels(), labels).isEmpty(); } }
/* * Copyright 2017-present Facebook, 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 com.facebook.buck.core.description.arg; import com.facebook.buck.core.sourcepath.SourcePath; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; import java.util.Set; import org.immutables.value.Value; /** Common arguments for build rules (but not configuration rules) */ public interface CommonDescriptionArg extends ConstructorArg, HasTargetCompatibleWith { String getName(); ImmutableSet<SourcePath> getLicenses(); @Value.NaturalOrder ImmutableSortedSet<String> getLabels(); @Value.Derived default boolean labelsContainsAnyOf(Set<String> labels) { return !Sets.intersection(this.getLabels(), labels).isEmpty(); } }
Fix pachage in problem 2
package problem_2 import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestProblem_2(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Problem 2") } var _ = Describe("fibGenerator", func() { It("gives the first few Fibonacci numbers", func() { c := fibGenerator() Expect(<-c).To(Equal(1)) Expect(<-c).To(Equal(2)) Expect(<-c).To(Equal(3)) Expect(<-c).To(Equal(5)) Expect(<-c).To(Equal(8)) Expect(<-c).To(Equal(13)) }) }) var _ = Describe("EvenFibonacciSum", func() { It("works with a limit of 1", func() { Expect(EvenFibonacciSum(1)).To(Equal(0)) }) It("works with a limit of 2", func() { Expect(EvenFibonacciSum(2)).To(Equal(2)) }) It("works with a limit of 3", func() { Expect(EvenFibonacciSum(3)).To(Equal(2)) }) It("works with a limit of 8", func() { Expect(EvenFibonacciSum(8)).To(Equal(10)) }) })
package problem_2_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestProblem_2(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Problem 2") } var _ = Describe("fibGenerator", func() { It("gives the first few Fibonacci numbers", func() { c := fibGenerator() Expect(<-c).To(Equal(1)) Expect(<-c).To(Equal(2)) Expect(<-c).To(Equal(3)) Expect(<-c).To(Equal(5)) Expect(<-c).To(Equal(8)) Expect(<-c).To(Equal(13)) }) }) var _ = Describe("EvenFibonacciSum", func() { It("works with a limit of 1", func() { Expect(EvenFibonacciSum(1)).To(Equal(0)) }) It("works with a limit of 2", func() { Expect(EvenFibonacciSum(2)).To(Equal(2)) }) It("works with a limit of 3", func() { Expect(EvenFibonacciSum(3)).To(Equal(2)) }) It("works with a limit of 8", func() { Expect(EvenFibonacciSum(8)).To(Equal(10)) }) })
Add parent_location_id to TableChart datapoints
import Reflux from 'reflux' import api from 'data/api' const DatapointActions = Reflux.createActions({ 'fetchDatapoints': { children: ['completed', 'failed'], asyncResult: true }, 'clearDatapoints': 'clearDatapoints' }) // API CALLS // --------------------------------------------------------------------------- DatapointActions.fetchDatapoints.listen(params => { const query = _prepDatapointsQuery(params) DatapointActions.fetchDatapoints.promise(api.datapoints(query)) }) // ACTION HELPERS // --------------------------------------------------------------------------- const _prepDatapointsQuery = (params) => { let query = { indicator__in: params.indicator_ids, campaign_start: params.start_date, campaign_end: params.end_date, chart_type: params.type, chart_uuid: params.uuid } const type = params.type const needsChildrenLocations = type === 'ChoroplethMap' || type === 'MapChart' || type === 'BubbleMap' || type === 'TableChart' if (needsChildrenLocations) { query['parent_location_id__in'] = params.location_ids } else { query['location_id__in'] = params.location_ids } if (params.indicator_filter) { query['filter_indicator'] = params.indicator_filter.type query['filter_value'] = params.indicator_filter.value } return query } export default DatapointActions
import Reflux from 'reflux' import api from 'data/api' const DatapointActions = Reflux.createActions({ 'fetchDatapoints': { children: ['completed', 'failed'], asyncResult: true }, 'clearDatapoints': 'clearDatapoints' }) // API CALLS // --------------------------------------------------------------------------- DatapointActions.fetchDatapoints.listen(params => { const query = _prepDatapointsQuery(params) DatapointActions.fetchDatapoints.promise(api.datapoints(query)) }) // ACTION HELPERS // --------------------------------------------------------------------------- const _prepDatapointsQuery = (params) => { let query = { indicator__in: params.indicator_ids, campaign_start: params.start_date, campaign_end: params.end_date, chart_type: params.type, chart_uuid: params.uuid } if (params.type === 'ChoroplethMap' || params.type === 'MapChart' || params.type === 'BubbleMap') { query['parent_location_id__in'] = params.location_ids } else { query['location_id__in'] = params.location_ids } if (params.indicator_filter) { query['filter_indicator'] = params.indicator_filter.type query['filter_value'] = params.indicator_filter.value } return query } export default DatapointActions
Allow a custom log handler as optional parameter
function log(method, level, input) { const args = [level].concat([].slice.call(input)); console[method].apply(console, args); // eslint-disable-line no-console } export const None = 0; export const Error = 1; export const Warn = 2; export const Info = 3; export const Debug = 4; export default function(_, method, handler) { let level = _ || None; let handler = handler || log; return { level(_) { if (arguments.length) { level = +_; return this; } else { return level; } }, error() { if (level >= Error) handler(method || 'error', 'ERROR', arguments); return this; }, warn() { if (level >= Warn) handler(method || 'warn', 'WARN', arguments); return this; }, info() { if (level >= Info) handler(method || 'log', 'INFO', arguments); return this; }, debug() { if (level >= Debug) handler(method || 'log', 'DEBUG', arguments); return this; } }; }
function log(method, level, input) { const args = [level].concat([].slice.call(input)); console[method].apply(console, args); // eslint-disable-line no-console } export const None = 0; export const Error = 1; export const Warn = 2; export const Info = 3; export const Debug = 4; export default function(_, method) { let level = _ || None; return { level(_) { if (arguments.length) { level = +_; return this; } else { return level; } }, error() { if (level >= Error) log(method || 'error', 'ERROR', arguments); return this; }, warn() { if (level >= Warn) log(method || 'warn', 'WARN', arguments); return this; }, info() { if (level >= Info) log(method || 'log', 'INFO', arguments); return this; }, debug() { if (level >= Debug) log(method || 'log', 'DEBUG', arguments); return this; } }; }
Fix error while factoring out fade effect
package com.twotoasters.jazzylistview.effects; import android.view.View; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; import com.twotoasters.jazzylistview.JazzyEffect; import com.twotoasters.jazzylistview.JazzyListView; public class FadeEffect implements JazzyEffect { private static final int DURATION_MULTIPLIER = 5; @Override public void initView(View item, int position, int scrollDirection) { ViewHelper.setAlpha(item, JazzyListView.TRANSPARENT); } @Override public void setupAnimation(View item, int position, int scrollDirection, ViewPropertyAnimator animator) { animator.setDuration(JazzyListView.DURATION * DURATION_MULTIPLIER); animator.alpha(JazzyListView.OPAQUE); } }
package com.twotoasters.jazzylistview.effects; import android.view.View; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; import com.twotoasters.jazzylistview.JazzyEffect; import com.twotoasters.jazzylistview.JazzyListView; public class FadeEffect implements JazzyEffect { private static final int DURATION_MULTIPLIER = 5; @Override public void initView(View item, int position, int scrollDirection) { ViewHelper.setAlpha(item, JazzyListView.TRANSPARENT); } @Override public void setupAnimation(View item, int position, int scrollDirection, ViewPropertyAnimator animator) { animator.setDuration(animator.getDuration() * JazzyListView.DURATION * DURATION_MULTIPLIER); animator.alpha(JazzyListView.OPAQUE); } }
Add test for shuffleArray helper
import HelpersModule from './helpers'; describe('Helpers', () => { let factory; beforeEach(window.module(HelpersModule)); beforeEach(inject((_Helpers_) => { factory = _Helpers_; })); describe('Factory', () => { it('subtracts values', () => { let what = 1; let from = 3; let expectedResult = 2; let result = factory.safeSubtract(what, from); expect(result).to.eq(expectedResult); }); it('subtracts down to 0 only', () => { let what = 3; let from = 1; let expectedResult = 0; let result = factory.safeSubtract(what, from); expect(result).to.eq(expectedResult); }); it('shuffles arrays', () => { let source = [ 1, 2, 3 ]; let shuffled = factory.shuffleArray(source); expect(shuffled).not.to.eql(source); }); }); });
import HelpersModule from './helpers'; describe('Helpers', () => { let factory; beforeEach(window.module(HelpersModule)); beforeEach(inject((_Helpers_) => { factory = _Helpers_; })); describe('Factory', () => { it('subtracts values', () => { let what = 1; let from = 3; let expectedResult = 2; let result = factory.safeSubtract(what, from); expect(result).to.eq(expectedResult); }); it('subtracts down to 0 only', () => { let what = 3; let from = 1; let expectedResult = 0; let result = factory.safeSubtract(what, from); expect(result).to.eq(expectedResult); }); }); });
Update [MediaContainer] children with the correct `section` object
from plex.objects.core.base import Property from plex.objects.container import Container from plex.objects.library.section import Section class MediaContainer(Container): section = Property(resolver=lambda: MediaContainer.construct_section) title1 = Property title2 = Property identifier = Property art = Property thumb = Property view_group = Property('viewGroup') view_mode = Property('viewMode', int) media_tag_prefix = Property('mediaTagPrefix') media_tag_version = Property('mediaTagVersion') no_cache = Property('nocache', bool) allow_sync = Property('allowSync', bool) mixed_parents = Property('mixedParents', bool) @staticmethod def construct_section(client, node): attribute_map = { 'key': 'librarySectionID', 'uuid': 'librarySectionUUID', 'title': 'librarySectionTitle' } return Section.construct(client, node, attribute_map, child=True) def __iter__(self): for item in super(MediaContainer, self).__iter__(): item.section = self.section yield item
from plex.objects.core.base import Property from plex.objects.container import Container from plex.objects.library.section import Section class MediaContainer(Container): section = Property(resolver=lambda: MediaContainer.construct_section) title1 = Property title2 = Property identifier = Property art = Property thumb = Property view_group = Property('viewGroup') view_mode = Property('viewMode', int) media_tag_prefix = Property('mediaTagPrefix') media_tag_version = Property('mediaTagVersion') no_cache = Property('nocache', bool) allow_sync = Property('allowSync', bool) mixed_parents = Property('mixedParents', bool) @staticmethod def construct_section(client, node): attribute_map = { 'key': 'librarySectionID', 'uuid': 'librarySectionUUID', 'title': 'librarySectionTitle' } return Section.construct(client, node, attribute_map, child=True)
Set the default timezone to 'UTC'.
<?php /** * * This file is part of the Apix Project. * * (c) Franck Cassedanne <franck at ouarz.net> * * @license http://opensource.org/licenses/BSD-3-Clause New BSD License * */ namespace Apix; date_default_timezone_set('UTC'); define('DEBUG', true); define('UNIT_TEST', true); define('APP_TOPDIR', realpath(__DIR__ . '/../../php')); define('APP_TESTDIR', realpath(__DIR__ . '/php')); define('APP_VENDOR', realpath(__DIR__ . '/../../../vendor')); // Composer $loader = require APP_VENDOR . '/autoload.php'; $loader->add('Apix', APP_TESTDIR); // Apix Autoloader (PEAR) // require APP_VENDOR . '/apix/autoloader/src/php/Apix/Autoloader.php'; // Autoloader::init( // array(APP_TOPDIR, APP_TESTDIR, APP_VENDOR) // );
<?php /** * * This file is part of the Apix Project. * * (c) Franck Cassedanne <franck at ouarz.net> * * @license http://opensource.org/licenses/BSD-3-Clause New BSD License * */ namespace Apix; define('DEBUG', true); define('UNIT_TEST', true); define('APP_TOPDIR', realpath(__DIR__ . '/../../php')); define('APP_TESTDIR', realpath(__DIR__ . '/php')); define('APP_VENDOR', realpath(__DIR__ . '/../../../vendor')); // Composer $loader = require APP_VENDOR . '/autoload.php'; $loader->add('Apix', APP_TESTDIR); // Apix Autoloader (PEAR) // require APP_VENDOR . '/apix/autoloader/src/php/Apix/Autoloader.php'; // Autoloader::init( // array(APP_TOPDIR, APP_TESTDIR, APP_VENDOR) // );
Change the monkey patching order
from django.conf import settings from django.conf.urls.defaults import * from .profiles import urls as profiles_urls from django.views.generic.simple import direct_to_template from funfactory import monkeypatches monkeypatches.patch() import badger badger.autodiscover() from django.contrib import admin admin.autodiscover() from badger import Progress #from badger_multiplayer.models import Badge, Award, Nomination from badger.models import Badge, Award urlpatterns = patterns('', url(r'^$', 'badger.views.home', name='home'), (r'^notification/', include('notification.urls')), (r'^badges/', include('badger_multiplayer.urls')), (r'^badges/', include('badger.urls')), (r'^browserid/', include('django_browserid.urls')), (r'^profiles/', include(profiles_urls)), (r'^accounts/', include('django.contrib.auth.urls')), (r'^admin/', include(admin.site.urls)), ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: # Remove leading and trailing slashes so the regex matches. media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
from django.conf import settings from django.conf.urls.defaults import * from .profiles import urls as profiles_urls from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() import badger badger.autodiscover() from funfactory import monkeypatches monkeypatches.patch() from badger import Progress #from badger_multiplayer.models import Badge, Award, Nomination from badger.models import Badge, Award urlpatterns = patterns('', url(r'^$', 'badger.views.home', name='home'), (r'^notification/', include('notification.urls')), (r'^badges/', include('badger_multiplayer.urls')), (r'^badges/', include('badger.urls')), (r'^browserid/', include('django_browserid.urls')), (r'^profiles/', include(profiles_urls)), (r'^accounts/', include('django.contrib.auth.urls')), (r'^admin/', include(admin.site.urls)), ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: # Remove leading and trailing slashes so the regex matches. media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Deal with the Django app refactoring.
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_runner(request): if not is_configured(): return from django.test.simple import DjangoTestSuiteRunner try: import django django.setup() except AttributeError: pass runner = DjangoTestSuiteRunner(interactive=False) runner.setup_test_environment() request.addfinalizer(runner.teardown_test_environment) config = runner.setup_databases() def teardown_database(): runner.teardown_databases(config) request.addfinalizer(teardown_database) return runner
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_runner(request): if not is_configured(): return from django.test.simple import DjangoTestSuiteRunner runner = DjangoTestSuiteRunner(interactive=False) runner.setup_test_environment() request.addfinalizer(runner.teardown_test_environment) config = runner.setup_databases() def teardown_database(): runner.teardown_databases(config) request.addfinalizer(teardown_database) return runner
Implement simple logging to console.
/** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.ios; import cli.System.Console; import playn.core.Log; class IOSLog implements Log { // TODO: stack traces @Override public void debug(String msg) { Console.WriteLine("DEBUG: " + msg); } @Override public void debug(String msg, Throwable e) { debug(msg + ": " + e.getMessage()); } @Override public void info(String msg) { Console.WriteLine(msg); } @Override public void info(String msg, Throwable e) { info(msg + ": " + e.getMessage()); } @Override public void warn(String msg) { Console.WriteLine("WARN: " + msg); } @Override public void warn(String msg, Throwable e) { warn(msg + ": " + e.getMessage()); } @Override public void error(String msg) { Console.WriteLine("ERROR: " + msg); } @Override public void error(String msg, Throwable e) { error(msg + ": " + e.getMessage()); } }
/** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.ios; import playn.core.Log; class IOSLog implements Log { @Override public void error(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void error(String msg) { throw new RuntimeException("TODO"); } @Override public void info(String msg) { throw new RuntimeException("TODO"); } @Override public void info(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void debug(String msg) { throw new RuntimeException("TODO"); } @Override public void debug(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void warn(String msg) { throw new RuntimeException("TODO"); } @Override public void warn(String msg, Throwable e) { throw new RuntimeException("TODO"); } }
Add else to into populate board to create a div elemento for the not used squares
// View $(document).ready(function() { console.log("Ready!"); // initialize the game and create a board var game = new Game(); PopulateBoard(game.flattenBoard()); //Handles clicks on the checkers board $(".board").on("click", function(e){ e.preventDefault(); game.test(game); }) // .board on click, a funciton }) // end (document).ready var PopulateBoard = function(board){ board.forEach(function(value, index){ if (value == "green"){ console.log("GREEN"); console.log(index); $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="green"></a>')); } else if (value == "blue"){ console.log("blue"); // $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="blue"></a>')); } else if (value == "empty"){ console.log("Empty"); } else { $(".board").append($.parseHTML('<div class="null"></div>')); } }) }
// View $(document).ready(function() { console.log("Ready!"); // initialize the game and create a board var game = new Game(); PopulateBoard(game.flattenBoard()); //Handles clicks on the checkers board $(".board").on("click", function(e){ e.preventDefault(); game.test(game); }) // .board on click, a funciton }) // end (document).ready var PopulateBoard = function(board){ board.forEach(function(value, index){ if (value == "green"){ console.log("GREEN"); console.log(index); $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="green"></a>')); } else if (value == "blue"){ console.log("blue"); // $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="blue"></a>')); } else if (value == "empty"){ console.log("Empty"); } }) }
Include data folder and specific test dependencies
from setuptools import setup, find_packages import sys import versioneer project_name = 'menpo3d' # Versioneer allows us to automatically generate versioning from # our git tagging system which makes releases simpler. versioneer.VCS = 'git' versioneer.versionfile_source = '{}/_version.py'.format(project_name) versioneer.versionfile_build = '{}/_version.py'.format(project_name) versioneer.tag_prefix = 'v' # tags are like v1.2.0 versioneer.parentdir_prefix = project_name + '-' # dirname like 'menpo-v1.2.0' install_requires = ['menpo==0.4.0', 'cyassimp==0.2.0', 'cyrasterize==0.2.0'] # These dependencies currently don't work on Python 3 if sys.version_info.major == 2: install_requires.append('mayavi==4.3.1') install_requires.append('menpo-pyvrml97==2.3.0a4') setup(name=project_name, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='MenpoKit providing tools for 3D Computer Vision research', author='James Booth', author_email='james.booth08@imperial.ac.uk', packages=find_packages(), package_data={'menpo3d': ['data/*']}, install_requires=install_requires, tests_require=['nose==1.3.4', 'mock==1.0.1'] )
from setuptools import setup, find_packages import sys import versioneer project_name = 'menpo3d' # Versioneer allows us to automatically generate versioning from # our git tagging system which makes releases simpler. versioneer.VCS = 'git' versioneer.versionfile_source = '{}/_version.py'.format(project_name) versioneer.versionfile_build = '{}/_version.py'.format(project_name) versioneer.tag_prefix = 'v' # tags are like v1.2.0 versioneer.parentdir_prefix = project_name + '-' # dirname like 'menpo-v1.2.0' install_requires = ['menpo==0.4.0', 'cyassimp==0.2.0', 'cyrasterize==0.2.0'] # These dependencies currently don't work on Python 3 if sys.version_info.major == 2: install_requires.append('mayavi==4.3.1') install_requires.append('menpo-pyvrml97==2.3.0a4') setup(name=project_name, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='MenpoKit providing tools for 3D Computer Vision research', author='James Booth', author_email='james.booth08@imperial.ac.uk', packages=find_packages(), install_requires=install_requires )
Make sure the device is detected as catgory
module.exports = function (RED) { function LgtvRequest2Node(n) { RED.nodes.createNode(this, n); var node = this; this.tv = n.tv; this.tvConn = RED.nodes.getNode(this.tv); if (this.tvConn) { this.tvConn.register(node); this.on('close', function (done) { node.tvConn.deregister(node, done); }); node.on('input', function (msg) { node.tvConn.request(msg.topic, msg.payload, function (err, res) { if (!err) { node.send({payload: res}); } else { node.send({payload: false}); } }); }); } else { this.error('No TV Configuration'); } } RED.nodes.registerType('lgtv-request2', LgtvRequest2Node); };
module.exports = function (RED) { function LgtvRequestNode(n) { RED.nodes.createNode(this, n); var node = this; this.tv = n.tv; this.tvConn = RED.nodes.getNode(this.tv); if (this.tvConn) { this.tvConn.register(node); this.on('close', function (done) { node.tvConn.deregister(node, done); }); node.on('input', function (msg) { node.tvConn.request(msg.topic, msg.payload, function (err, res) { if (!err) { node.send({payload: res}); } else { node.send({payload: false}); } }); }); } else { this.error('No TV Configuration'); } } RED.nodes.registerType('lgtv-request2', LgtvRequestNode); };
refactor(src): Remove whitespace and '.' delims
import pluralize, { singular } from 'pluralize'; function normalize(slug: string): string { return singular(slug.toLowerCase()).replace(/(-|_)+/g, '_'); } function urlify(slug: string): string { return pluralize(slug).replace('_', '-'); } const formats = { pascal(slug: string): string { return slug .split('_') .map(word => `${word.charAt(0).toUpperCase()}${word.substr(1)}`) .join(' '); }, camel(slug: string): string { const splitSlug = slug.split('_'); return [ splitSlug[0], formats.pascal(splitSlug.slice(1).join('_')).replace(' ', ''), ].join(''); }, }; export default function slugizoid(slug: string = ''): string { const _original = slug; const _normalized = normalize(slug); return { toString(options: { format: 'pascal' | 'camel', plural: boolean }): string { const { format, plural } = Object.assign( { format: 'pascal', plural: false }, options ); return (plural ? pluralize : singular)(formats[format](_normalized)); }, equals(slug: string): boolean { return normalize(slug) === _normalized; }, slugify(): string { return _normalized; }, urlify(): string { return urlify(_normalized); }, }; }
import pluralize, { singular } from 'pluralize'; function normalize(slug: string): string { return singular(slug.toLowerCase()).replace(/(-|_|\.|\s)+/g, '_'); } function urlify(slug: string): string { return pluralize(slug).replace('_', '-'); } const formats = { pascal(slug: string): string { return slug .split('_') .map(word => `${word.charAt(0).toUpperCase()}${word.substr(1)}`) .join(' '); }, camel(slug: string): string { const splitSlug = slug.split('_'); return [ splitSlug[0], formats.pascal(splitSlug.slice(1).join('_')).replace(' ', ''), ].join(''); }, }; export default function slugizoid(slug: string = ''): string { const _original = slug; const _normalized = normalize(slug); return { toString(options: { format: 'pascal' | 'camel', plural: boolean }): string { const { format, plural } = Object.assign( { format: 'pascal', plural: false }, options ); return (plural ? pluralize : singular)(formats[format](_normalized)); }, equals(slug: string): boolean { return normalize(slug) === _normalized; }, slugify(): string { return _normalized; }, urlify(): string { return urlify(_normalized); }, }; }
Add pause/resume examples on demo
import React from 'react' import ReactDOM from 'react-dom' import VoicePlayer from './voice-player' class Demo extends React.Component { state = { play: true, pause: false } render () { return ( <div> <button onClick={() => this.setState({ play: true })}>Play</button> <button onClick={() => this.setState({ pause: true })}>Pause</button> <button onClick={() => this.setState({ pause: false })}>Resume</button> <VoicePlayer play={this.state.play} pause={this.state.pause} text="Welcome to the jungle! We got fun and games" onPause={() => console.info('pause')} onResume={() => console.info('resume')} onStart={() => console.info('start')} onEnd={() => console.info('end')} /> </div> ) } } ReactDOM.render( <Demo />, document.getElementById('root') )
import React from 'react' import ReactDOM from 'react-dom' import VoicePlayer from './voice-player' class Demo extends React.Component { state = { play: true, pause: false } render () { return ( <div> <button onClick={() => this.setState({ play: true })}>Play</button> <button onClick={() => this.setState({ pause: true })}>Pause</button> <button onClick={() => this.setState({ pause: false })}>Resume</button> <button onClick={() => this.setState({ cancel: true })}>Resume</button> <VoicePlayer text="Welcome to React Voice Components! Please turn off the lights before leaving" lang="en-us" play={this.state.play} pause={this.state.pause} /> </div> ) } } ReactDOM.render( <Demo />, document.getElementById('root') )
Fix changed interface in bCrypt
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var config = require('../config'); var UserSchema = new Schema({ username: {type: String, required: true, index: {unique: true}}, email: {type: String, required: true, unique: true}, password: {type: String, required: true}, role: {type: String, required: true, default: 'user'} }) UserSchema.pre('save', function(next) { var user = this; // only hash the password if it has been modified (or is new) if (!user.isModified('password')) return next(); // generate a salt bcrypt.genSalt(config.SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); // hash the password using our new salt bcrypt.hash(user.password, salt, undefined, function(err, hash) { if (err) return next(err); // override the cleartext password with the hashed one user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; module.exports = mongoose.model('User', UserSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var config = require('../config'); var UserSchema = new Schema({ username: {type: String, required: true, index: {unique: true}}, email: {type: String, required: true, unique: true}, password: {type: String, required: true}, role: {type: String, required: true, default: 'user'} }) UserSchema.pre('save', function(next) { var user = this; // only hash the password if it has been modified (or is new) if (!user.isModified('password')) return next(); // generate a salt bcrypt.genSalt(config.SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); // hash the password using our new salt bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); // override the cleartext password with the hashed one user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; module.exports = mongoose.model('User', UserSchema);
Sort beans names in stream
package com.mpalourdio.hello; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({WebSecurityConfig.class}) public class Application { public static void main(final String[] args) { final ApplicationContext ctx = SpringApplication.run(Application.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.stream(beanNames) .sorted() .forEach(System.out::println); } }
package com.mpalourdio.hello; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({WebSecurityConfig.class}) public class Application { public static void main(final String[] args) { final ApplicationContext ctx = SpringApplication.run(Application.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); Arrays.stream(beanNames).forEach(System.out::println); } }
Fix TTL for redis store of meat messages, to 24 hours
var fs = require("fs"); var shasum = require("sha1"); var redis = require("redis"); var client = redis.createClient(); var meatReader = require("./lib/meatReader"); var validations = require("./validations"); client.on("error", function (err) { console.error("Error " + err); }); validations.exclude = validations.exclude.map(function (v) { return new RegExp(v); }); function save(message, info) { var ttl = 60 * 60 * 24; var key = shasum(info.fingerprint + message); client.set(key, message, "EX", ttl) && console.log("entered", message); }; function validate(message) { var valid = true; for(var i=0; i < validations.exclude.length; i++) { var v = validations.exclude[i]; if (v.test(message)) { valid = false; break; } } return valid; }; meatReader.connect(); meatReader.on({ data: function(message, info) { validate(message) && save(message, info); } });
var fs = require("fs"); var shasum = require("sha1"); var redis = require("redis"); var client = redis.createClient(); var meatreader = require("./lib/readmeats"); var validations = require("./validations"); client.on("error", function (err) { console.error("Error " + err); }); validations.exclude = validations.exclude.map(function (v) { return new RegExp(v); }); function save(message, info) { var key = shasum(info.fingerprint + message); client.set(key, message) && console.log("entered", message); }; function validate(message) { var valid = true; for(var i=0; i < validations.exclude.length; i++) { var v = validations.exclude[i]; if (v.test(message)) { valid = false; break; } } // valid ? console.log("yes", message) : console.log("no", message); return valid; }; // fs.readFile("./validations.json", function (err, validations) { meatreader.connect(); meatreader.on({ data: function(message, info) { validate(message) && save(message, info); } }); // });
Add initial function definition and documentation for function to do conversion
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. """
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million']
Fix a misspelling in a comment Change-Id: If049cef6def1249fd0f70e16385aa7a4167edbde
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystoneclient import base class Extension(base.Resource): """Represents an Identity API extension.""" def __repr__(self): return "<Extension %s>" % self._info class ExtensionManager(base.ManagerWithFind): """Manager class for listing Identity API extensions.""" resource_class = Extension def list(self): """List all available extensions.""" return self._list('/extensions', 'extensions')
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystoneclient import base class Extension(base.Resource): """Represents an Identity API extension.""" def __repr__(self): return "<Extension %s>" % self._info class ExtensionManager(base.ManagerWithFind): """Manager class for listing Identity API extensions.""" resource_class = Extension def list(self): """List all available extentions.""" return self._list('/extensions', 'extensions')
State: Add history object for thread and for board
export default { status: { isScrolling: false, // app scroll currentPage: "home", // currentPage isHeaderVisible: false, // if currentPage == "content" alertMessage: null, // reveal status to user providers: ["4chan", "reddit"], provider: "4chan", boardID: null, threadID: null, }, boardList: { // obj for each provider: {4chan: [], reddit: []} didInvalidate: false, favourites: [] // [{id:'4chan', board: 'g'}, ...] }, board: { receivedAt: 0, // unix timestamp isFetching: false, didInvalidate: false, searchWord: null, filterWords: [], posts: [], watch: [], limit: 30 // infinite scroll }, boardHistory: { "4chan": {}, "reddit": {} }, thread: { receivedAt: 0, // unix timestamp isActive: false, isFetching: false, didInvalidate: false, posts: [], }, threadHistory: { "4chan": {}, "reddit": {} }, post: { isAuthenticated: false, type: null, // thread/comment references: [], message: null, // user input upload: null // canReply }, settings: require('./settings') }
export default { status: { isScrolling: false, // app scroll currentPage: "home", // currentPage isHeaderVisible: false, // if currentPage == "content" alertMessage: null, // reveal status to user providers: ["4chan", "reddit"], provider: "4chan", boardID: null, threadID: null, }, boardList: { // obj for each provider: {4chan: [], reddit: []} didInvalidate: false, favourites: [] // [{id:'4chan', board: 'g'}, ...] }, board: { receivedAt: 0, // unix timestamp isFetching: false, didInvalidate: false, searchWord: null, filterWords: [], history: {}, posts: [], watch: [], limit: 30 // infinite scroll }, thread: { receivedAt: 0, // unix timestamp isActive: false, isFetching: false, didInvalidate: false, history: {}, posts: [], }, post: { isAuthenticated: false, type: null, // thread/comment references: [], message: null, // user input upload: null // canReply }, settings: require('./settings') }
Allow descriptor to be passed to TextAreaEditor (for eventual use in SyntaxTextArea setup) git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1501283 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 01f17010a645702a55d9b28ceee63611c282acfd
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.testbeans.gui; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; /** * Allow direct specification of property editors. */ public enum TypeEditor { FileEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new FileEditor(descriptor); }}, PasswordEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new PasswordEditor(); }}, TableEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TableEditor(); }}, TextAreaEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TextAreaEditor(descriptor); }}, ; // Some editors may need the descriptor abstract PropertyEditor getInstance(PropertyDescriptor descriptor); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.testbeans.gui; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; /** * Allow direct specification of property editors. */ public enum TypeEditor { FileEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new FileEditor(descriptor); }}, PasswordEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new PasswordEditor(); }}, TableEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TableEditor(); }}, TextAreaEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TextAreaEditor(); }}, ; // Some editors may need the descriptor abstract PropertyEditor getInstance(PropertyDescriptor descriptor); }
Adjust version in download url
from setuptools import setup setup( name='pyhunter', packages=['pyhunter'], version='0.2', description='An (unofficial) Python wrapper for the Hunter.io API', author='Quentin Durantay', author_email='quentin.durantay@gmail.com', url='https://github.com/VonStruddle/PyHunter', download_url='https://github.com/VonStruddle/PyHunter/archive/0.2.tar.gz', install_requires=['requests'], keywords=['hunter', 'hunter.io', 'lead generation', 'lead enrichment'], classifiers=[ 'Development Status :: 3 - Alpha', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ], )
from setuptools import setup setup( name='pyhunter', packages=['pyhunter'], version='0.2', description='An (unofficial) Python wrapper for the Hunter.io API', author='Quentin Durantay', author_email='quentin.durantay@gmail.com', url='https://github.com/VonStruddle/PyHunter', download_url='https://github.com/VonStruddle/PyHunter/archive/0.1.tar.gz', install_requires=['requests'], keywords=['hunter', 'hunter.io', 'lead generation', 'lead enrichment'], classifiers=[ 'Development Status :: 3 - Alpha', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ], )
Fix failing TestMarketplace test by ensuring vanilla authentication and authorization
from tastypie import http from tastypie.authentication import Authentication from tastypie.authorization import Authorization from test_utils import RequestFactory from amo.tests import TestCase from mkt.api.base import MarketplaceResource class TestMarketplace(TestCase): def setUp(self): self.resource = MarketplaceResource() # Ensure that we have proper authentication and authorization. self.resource._meta.authentication = Authentication() self.resource._meta.authorization = Authorization() self.request = RequestFactory().post('/') def test_form_encoded(self): """ Regression test of bug #858403: ensure that a 400 (and not 500) is raised when an unsupported Content-Type header is passed to an API endpoint. """ self.request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' with self.assertImmediate(http.HttpBadRequest): self.resource.dispatch('list', self.request)
from tastypie import http from tastypie.authorization import Authorization from test_utils import RequestFactory from amo.tests import TestCase from mkt.api.base import MarketplaceResource class TestMarketplace(TestCase): def setUp(self): self.resource = MarketplaceResource() self.resource._meta.authorization = Authorization() self.request = RequestFactory().post('/') def test_form_encoded(self): """ Regression test of bug #858403: ensure that a 400 (and not 500) is raised when an unsupported Content-Type header is passed to an API endpoint. """ self.request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' with self.assertImmediate(http.HttpBadRequest): self.resource.dispatch('list', self.request)
Fix CIPANGO-99: Creating a DiameterServletRequest without specifying the destinationhost field leads to a null pointer exception when sending a the request git-svn-id: cb8625e300c3faf843aa2977f1eda3273db846e7@506 657f710f-be33-0410-a596-71a6d81f68ef
// ======================================================================== // Copyright 2010 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.diameter.router; import java.util.Hashtable; import java.util.Map; import org.cipango.diameter.node.DiameterRequest; import org.cipango.diameter.node.Peer; public class DefaultRouter implements DiameterRouter { private Map<String, Peer> _peers = new Hashtable<String, Peer>(); public Peer getRoute(DiameterRequest request) { if (request.getDestinationHost() == null) return null; return _peers.get(request.getDestinationHost()); } public void peerAdded(Peer peer) { _peers.put(peer.getHost(), peer); } public void peerRemoved(Peer peer) { _peers.remove(peer.getHost()); } }
// ======================================================================== // Copyright 2010 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.diameter.router; import java.util.Hashtable; import java.util.Map; import org.cipango.diameter.node.DiameterRequest; import org.cipango.diameter.node.Node; import org.cipango.diameter.node.Peer; public class DefaultRouter implements DiameterRouter { private Map<String, Peer> _peers = new Hashtable<String, Peer>(); public Peer getRoute(DiameterRequest request) { return _peers.get(request.getDestinationHost()); } public void peerAdded(Peer peer) { _peers.put(peer.getHost(), peer); } public void peerRemoved(Peer peer) { _peers.remove(peer.getHost()); } }
Update code comment for use in PHPStorm.
<?php /** * ZucchiDoctrine (http://zucchi.co.uk) * * @link http://github.com/zucchi/ZucchiDoctrine for the canonical source repository * @copyright Copyright (c) 2005-2013 Zucchi Limited. (http://zucchi.co.uk) * @license http://zucchi.co.uk/legals/bsd-license New BSD License */ namespace ZucchiDoctrine\EntityManager; use Doctrine\ORM\EntityManager; use Zend\ServiceManager\ServiceManager; trait EntityManagerAwareTrait { /** * @var \Doctrine\ORM\EntityManager */ protected $entityManager; /** * set the entity manager * @param EntityManager $em * @return $this */ public function setEntityManager(EntityManager $em) { $this->entityManager = $em; return $this; } /** * get the currently set Entity Manager * @return EntityManager */ public function getEntityManager() { if (!$this->entityManager && method_exists($this, 'getServiceManager')) { $sm = $this->getServiceManager(); if ($sm instanceof ServiceManager) { $this->entityManager = $sm->get('doctrine.entitymanager.orm_default'); } } return $this->entityManager; } }
<?php /** * ZucchiDoctrine (http://zucchi.co.uk) * * @link http://github.com/zucchi/ZucchiDoctrine for the canonical source repository * @copyright Copyright (c) 2005-2013 Zucchi Limited. (http://zucchi.co.uk) * @license http://zucchi.co.uk/legals/bsd-license New BSD License */ namespace ZucchiDoctrine\EntityManager; use Doctrine\ORM\EntityManager; use Zend\ServiceManager\ServiceManager; trait EntityManagerAwareTrait { /** * @var Doctrine\ORM\EntityManager */ protected $entityManager; /** * set the entity manager * @param EntityManager $em * @return $this */ public function setEntityManager(EntityManager $em) { $this->entityManager = $em; return $this; } /** * get the currently set Entity Manager * @return EntityManager */ public function getEntityManager() { if (!$this->entityManager && method_exists($this, 'getServiceManager')) { $sm = $this->getServiceManager(); if ($sm instanceof ServiceManager) { $this->entityManager = $sm->get('doctrine.entitymanager.orm_default'); } } return $this->entityManager; } }
Remove trailing slash (needed for jetty-upgrade)
//Establish the WebSocket connection and set up event handlers var webSocket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/chat"); webSocket.onmessage = function (msg) { updateChat(msg); }; webSocket.onclose = function () { alert("WebSocket connection closed") }; //Send message if "Send" is clicked id("send").addEventListener("click", function () { sendMessage(id("message").value); }); //Send message if enter is pressed in the input field id("message").addEventListener("keypress", function (e) { if (e.keyCode === 13) { sendMessage(e.target.value); } }); //Send a message if it's not empty, then clear the input field function sendMessage(message) { if (message !== "") { webSocket.send(message); id("message").value = ""; } } //Update the chat-panel, and the list of connected users function updateChat(msg) { var data = JSON.parse(msg.data); insert("chat", data.userMessage); id("userlist").innerHTML = ""; data.userlist.forEach(function (user) { insert("userlist", "<li>" + user + "</li>"); }); } //Helper function for inserting HTML as the first child of an element function insert(targetId, message) { id(targetId).insertAdjacentHTML("afterbegin", message); } //Helper function for selecting element by id function id(id) { return document.getElementById(id); }
//Establish the WebSocket connection and set up event handlers var webSocket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/chat/"); webSocket.onmessage = function (msg) { updateChat(msg); }; webSocket.onclose = function () { alert("WebSocket connection closed") }; //Send message if "Send" is clicked id("send").addEventListener("click", function () { sendMessage(id("message").value); }); //Send message if enter is pressed in the input field id("message").addEventListener("keypress", function (e) { if (e.keyCode === 13) { sendMessage(e.target.value); } }); //Send a message if it's not empty, then clear the input field function sendMessage(message) { if (message !== "") { webSocket.send(message); id("message").value = ""; } } //Update the chat-panel, and the list of connected users function updateChat(msg) { var data = JSON.parse(msg.data); insert("chat", data.userMessage); id("userlist").innerHTML = ""; data.userlist.forEach(function (user) { insert("userlist", "<li>" + user + "</li>"); }); } //Helper function for inserting HTML as the first child of an element function insert(targetId, message) { id(targetId).insertAdjacentHTML("afterbegin", message); } //Helper function for selecting element by id function id(id) { return document.getElementById(id); }
Remove toString method, add setters
package uk.ac.ebi.spot.goci.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by emma on 27/11/14. * * @author emma * <p> * Model object representing status assigned to studies */ @Entity public class CurationStatus { @Id @GeneratedValue private Long id; private String status; private String seqnbr; // JPA no-args constructor public CurationStatus() { } public CurationStatus(Long id, String curationStatus, String seqnbr) { this.id = id; this.status = curationStatus; this.seqnbr = seqnbr; } public Long getId() { return id; } public String getStatus() { return status; } public String getSeqnbr() { return seqnbr; } public void setId(Long id) { this.id = id; } public void setStatus(String status) { this.status = status; } public void setSeqnbr(String seqnbr) { this.seqnbr = seqnbr; } }
package uk.ac.ebi.spot.goci.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by emma on 27/11/14. * * @author emma * <p> * Model object representing status assigned to studies */ @Entity public class CurationStatus { @Id @GeneratedValue private Long id; private String status; private String seqnbr; // JPA no-args constructor public CurationStatus() { } public CurationStatus(Long id, String curationStatus, String seqnbr) { this.id = id; this.status = curationStatus; this.seqnbr = seqnbr; } public Long getId() { return id; } public String getStatus() { return status; } public String getSeqnbr() { return seqnbr; } @Override public String toString() { return "CurationStatus{" + "id=" + id + ", curationStatus='" + status + '\'' + ", seqnbr='" + seqnbr + '\'' + '}'; } }
Call the custom tenon files
//= require jquery //= require jquery_ujs // -- Plugins, in alphabetical order //= require backstretch //= require bootstrap //= require bootstrap.collapse //= require bootstrap.modal //= require bootstrap.tabs //= require canvasjs.min //= require cocoon //= require imagesloaded //= require jquery-fileupload/basic //= require jquery-fileupload/vendor/tmpl //= require jquery.debounce //= require jquery.equalHeights //= require jquery.hoverIntent //= require jquery.Jcrop //= require jquery.mousewheel //= require jquery.radioSlider //= require jquery.twoLevelSort //= require jquery.ui.sortable //= require medium-editor //= require select2 // -- Plugins that need to be loaded in order //= require moment //= require bootstrap.datetimepicker //= require lodash //= require underscore.string //= require underscore.inflection // -- Tenon things, don't mess with the order //= require ./tenon //= require ./tenon_dispatcher //= require_tree ./templates //= require_tree ./controllers //= require_tree ./features //= require tenon_addons //= require_self $(function() { Tenon.init(); });
//= require jquery //= require jquery_ujs // -- Plugins, in alphabetical order //= require backstretch //= require bootstrap //= require bootstrap.collapse //= require bootstrap.modal //= require bootstrap.tabs //= require canvasjs.min //= require cocoon //= require imagesloaded //= require jquery-fileupload/basic //= require jquery-fileupload/vendor/tmpl //= require jquery.debounce //= require jquery.equalHeights //= require jquery.hoverIntent //= require jquery.Jcrop //= require jquery.mousewheel //= require jquery.radioSlider //= require jquery.twoLevelSort //= require jquery.ui.sortable //= require medium-editor //= require select2 // -- Plugins that need to be loaded in order //= require moment //= require bootstrap.datetimepicker //= require lodash //= require underscore.string //= require underscore.inflection // -- Tenon things, don't mess with the order //= require ./tenon //= require ./tenon_dispatcher //= require_tree ./templates //= require_tree ./controllers //= require_tree ./features //= require_self $(function() { Tenon.init(); });
Add CSS class names depending on the type
<?php $socialLinks = [ 'Facebook' => 'https://www.facebook.com/', 'Twitter' => 'https://twitter.com/', 'Twitch' => 'https://www.twitch.tv/', 'YouTube' => 'https://www.youtube.com/channel/', 'Instagram' => 'https://www.instagram.com/', 'Discord' => 'https://www.discord.gg/', ] ?> @foreach($socialLinks as $title => $url) <?php $name = strtolower($title) ?> @if (Config::get('app.'.$name)) @if (isset($wrapperTag)) {!! '<'.$wrapperTag.'>' !!} @endif <a class="social-link social-link-{{ strtolower($title) }}" href="{{ $url }}{{ Config::get('app.'.$name) }}" target="_blank" title="{{ $title }}">{!! HTML::fontIcon($name) !!}</a> @if (isset($wrapperTag)) {!! '</'.$wrapperTag.'>' !!} @endif @endif @endforeach
<?php $socialLinks = [ 'Facebook' => 'https://www.facebook.com/', 'Twitter' => 'https://twitter.com/', 'Twitch' => 'https://www.twitch.tv/', 'YouTube' => 'https://www.youtube.com/channel/', 'Instagram' => 'https://www.instagram.com/', 'Discord' => 'https://www.discord.gg/', ] ?> @foreach($socialLinks as $title => $url) <?php $name = strtolower($title) ?> @if (Config::get('app.'.$name)) @if (isset($wrapperTag)) {!! '<'.$wrapperTag.'>' !!} @endif <a class="social-link" href="{{ $url }}{{ Config::get('app.'.$name) }}" target="_blank" title="{{ $title }}">{!! HTML::fontIcon($name) !!}</a> @if (isset($wrapperTag)) {!! '</'.$wrapperTag.'>' !!} @endif @endif @endforeach
Stop bots from randomly disconnecting
import os import json import time import socket from subprocess import call import requests from test import test_activity from build import compile_bundle # Fixes a weird bug... it might create some though :P os.environ['http_proxy'] = '' # HOST = 'http://localhost:5001' HOST = 'http://aslo-bot-master.sugarlabs.org' print 'Waiting for 1st task' while True: try: r = requests.get(HOST + '/task') except requests.exceptions.ConnectionError, e: continue if r.status_code == 404: time.sleep(7) continue task = r.json() print 'Got new task' call(['git', 'clone', 'https://www.github.com/' + task['gh'], 'dl']) result = test_activity(task['bundle_id'], task['gh']) data = {'result': result, 'file': compile_bundle(), 'bundle_id': task['bundle_id'], 'task_id': task['task_id']} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(HOST + '/done', data=json.dumps(data), headers=headers) call(['rm', '-rf', 'dl']) print 'Mined 1 activity:', task['bundle_id'], task['gh']
import os import json import time import socket from subprocess import call import requests from test import test_activity from build import compile_bundle # Fixes a weird bug... it might create some though :P os.environ['http_proxy'] = '' # HOST = 'http://localhost:5001' HOST = 'http://aslo-bot-master.sugarlabs.org' print 'Waiting for 1st task' while True: r = requests.get(HOST + '/task') if r.status_code == 404: time.sleep(7) continue task = r.json() print 'Got new task' call(['git', 'clone', 'https://www.github.com/' + task['gh'], 'dl']) result = test_activity(task['bundle_id'], task['gh']) data = {'result': result, 'file': compile_bundle(), 'bundle_id': task['bundle_id'], 'task_id': task['task_id']} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(HOST + '/done', data=json.dumps(data), headers=headers) call(['rm', '-rf', 'dl']) print 'Mined 1 activity:', task['bundle_id'], task['gh']
Reset validation status on unchecking item
var tliRegister = tliRegister || {}; tliRegister.discountCodes = function() { var init = function() { initCodeItemEnabling(); }, initCodeItemEnabling = function() { $('#discount-code-items input:checkbox') .change(handlePricingItemChange) .each(handlePricingItemChange); }, handlePricingItemChange = function() { var row = $(this).closest('tr'), chekbox = this; $('input[type=number]', row) .prop('disabled', !$(chekbox).prop('checked')) .each(function() { if (!$(chekbox).prop('checked')) { $(this).val($(this).attr('data-value-original')); $('.has-error', row).each(function() { $(this).children('.help-block').slideUp(function() { $(this).remove(); }); $(this).removeClass('has-error'); }); } }); } return { init: init } }();
var tliRegister = tliRegister || {}; tliRegister.discountCodes = function() { var init = function() { initCodeItemEnabling(); }, initCodeItemEnabling = function() { $('#discount-code-items input:checkbox') .change(handlePricingItemChange) .each(handlePricingItemChange); }, handlePricingItemChange = function() { var row = $(this).closest('tr'), chekbox = this; $('input[type=number]', row) .prop('disabled', !$(chekbox).prop('checked')) .each(function() { if (!$(chekbox).prop('checked')) { $(this).val($(this).attr('data-value-original')); } }); } return { init: init } }();
Prepare for the next release.
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.1.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide'], classifiers = [] )
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.0.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=1.6.2', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide'], classifiers = [] )
Check if it is disconnected by default
<?php namespace spec\Nats; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ConnectionSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Nats\Connection'); } function it_has_ping_count_to_zero() { $this->pingsCount()->shouldBe(0); } function it_has_pubs_count_to_zero() { $this->pubsCount()->shouldBe(0); } function it_has_reconnects_count_to_zero() { $this->reconnectsCount()->shouldBe(0); } function it_has_subscriptions_count_to_zero() { $this->subscriptionsCount()->shouldBe(0); } function it_subscriptions_array_is_empty() { $this->getSubscriptions()->shouldHaveCount(0); } function it_is_disconnected() { $this->isConnected()->shouldBe(false); } }
<?php namespace spec\Nats; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ConnectionSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Nats\Connection'); } function it_has_ping_count_to_zero() { $this->pingsCount()->shouldBe(0); } function it_has_pubs_count_to_zero() { $this->pubsCount()->shouldBe(0); } function it_has_reconnects_count_to_zero() { $this->reconnectsCount()->shouldBe(0); } function it_has_subscriptions_count_to_zero() { $this->subscriptionsCount()->shouldBe(0); } function it_subscriptions_array_is_empty() { $this->getSubscriptions()->shouldHaveCount(0); } }
Document message format for minion server
#!/usr/bin/env python import server import supervisor class MinionServer(server.Server): def __init__(self, ip, port): super(MinionServer, self).__init__(ip, port) def handle(self, data): """Start a worker. Message format: { 'image': 'image name' 'numprocs': number of workers, 'args': 'extra arguments for "docker run -d image ..."' } """ supervisor.start( 'worker.conf', target='worker_{}'.format(data['image']), image=data['image'], numprocs=data.get('numprocs', 1), args=data.get('args', '')) return {'status': 'ok'} def main(): server = MinionServer('*', 1234) server.start() server.join() if __name__ == '__main__': main()
#!/usr/bin/env python import server import supervisor class MinionServer(server.Server): def __init__(self, ip, port): super(MinionServer, self).__init__(ip, port) def handle(self, data): supervisor.start( 'worker.conf', target='worker_{}'.format(data['image']), image=data['image'], numprocs=data.get('numprocs', 1), args=data.get('args', '')) return {'status': 'ok'} def main(): server = MinionServer('*', 1234) server.start() server.join() if __name__ == '__main__': main()
Fix "moment is not defined" bug for ard channels
const moment = require('moment-timezone'); class Show { static get INTERMISSION() { return new Show('Sendepause'); } constructor(title) { this.title = title; } isRunningNow() { return this.startTime.isBefore() && this.endTime.isAfter(); } fixMidnightTime() { if (this.startTime.isAfter(this.endTime)) { // show runs at midnight if (moment.tz('Europe/Berlin').hour() < 12) { // now is morning - startTime was yesterday this.startTime.subtract(1, 'd'); } else { // now is evening - end time is tomorrow this.endTime.add(1, 'd'); } } } clone() { let show = new Show(this.title); show.channel = this.channel; show.subtitle = this.subtitle; show.startTime = this.startTime; show.endTime = this.endTime; return show; } } module.exports = Show;
class Show { static get INTERMISSION() { return new Show('Sendepause'); } constructor(title) { this.title = title; } isRunningNow() { return this.startTime.isBefore() && this.endTime.isAfter(); } fixMidnightTime() { if (this.startTime.isAfter(this.endTime)) { // show runs at midnight if (moment().hour() < 12) { // now is morning - startTime was yesterday this.startTime.subtract(1, 'd'); } else { // now is evening - end time is tomorrow this.endTime.add(1, 'd'); } } } clone() { let show = new Show(this.title); show.channel = this.channel; show.subtitle = this.subtitle; show.startTime = this.startTime; show.endTime = this.endTime; return show; } } module.exports = Show;
Simplify signed byte calc to a unsigned one
onmessage = function(e) { var command = e.command; var packed = command.compressedBytes; var buf_length = packed.length; var buf_pos = 0; var buf = new Uint8Array(buf); function checkOutputSpace(n) { if (buf_pos + n > buf_length) { buf_length *= 2; var new_buf = new Uint8Array(buf_length); new_buf.set(buf); buf = new_buf; } } var pos = 0; while (pos < packed.length) { var b = packed[pos++]; if (b & 0x80) { if (b === 0x80) continue; var count = 257 - b; var rep = packed[pos++]; checkOutputSpace(count); for (var i = 0; i < count; i++) { buf[buf_pos++] = rep; } } else { var length = b + 1; checkOutputSpace(length); buf.set(packed.subarray(pos, pos + length), buf_pos); pos += length; buf_pos += length; } } postMessage(buf, [buf.buffer]); };
onmessage = function(e) { var command = e.command; var packed = command.compressedBytes; var buf_length = packed.length; var buf_pos = 0; var buf = new Uint8Array(buf); function checkOutputSpace(n) { if (buf_pos + n > buf_length) { buf_length *= 2; var new_buf = new Uint8Array(buf_length); new_buf.set(buf); buf = new_buf; } } var pos = 0; while (pos < packed.length) { var b = packed[pos++]; if (b & 0x80) { if (b === 0x80) continue; var count = 1 - (b << 24 >> 24); var rep = packed[pos++]; checkOutputSpace(count); for (var i = 0; i < count; i++) { buf[buf_pos++] = rep; } } else { var length = b + 1; checkOutputSpace(length); buf.set(packed.subarray(pos, pos + length), buf_pos); pos += length; buf_pos += length; } } postMessage(buf, [buf.buffer]); };
Remove session cookie print in teardown
import flask import os.path import datetime import urllib.parse from .. import database from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../configs/")) configs = configmanager.ConfigManager(configPath = CONFIG_PATH) authConfig = configs["auth"] app = flask.Flask(__name__, static_folder = STATIC_PATH) app.secret_key = authConfig["signing_key"] app.register_blueprint(controllers.user.blueprint) app.register_blueprint(controllers.admin.blueprint) @app.teardown_request def teardown_request(exception = None): databaseConnection = database.ConnectionManager.getMainConnection() databaseConnection.session.close()
import flask import os.path import datetime import urllib.parse from .. import database from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../configs/")) configs = configmanager.ConfigManager(configPath = CONFIG_PATH) authConfig = configs["auth"] app = flask.Flask(__name__, static_folder = STATIC_PATH) app.secret_key = authConfig["signing_key"] app.register_blueprint(controllers.user.blueprint) app.register_blueprint(controllers.admin.blueprint) @app.teardown_request def teardown_request(exception = None): print(flask.session) databaseConnection = database.ConnectionManager.getMainConnection() databaseConnection.session.close()
Use PREFIX pseudo-constant where appropriate.
var modulr = (function(global) { var _modules = {}, _aliases = {}, _cache = {}, PREFIX = '__module__'; // Prefix identifiers to avoid issues in IE. function log(str) { if (global.console && console.log) { console.log(str); } } function require(identifier) { var m, key = PREFIX + identifier; log('Required module "' + identifier + '".'); if (_aliases[key]) { key = _aliases[key]; log('Found module "' + identifier + '" as alias of module "' + key.replace(PREFIX, '') + '".'); } if (!_cache[key]) { m = _modules[key]; if (!m) { throw 'Can\'t find module "' + identifier + '".'; } _cache[key] = m(require, {}); } return _cache[key]; } function cache(identifier, fn) { var key = PREFIX + identifier; log('Cached module "' + identifier + '".'); if (_modules[key]) { throw 'Can\'t ovewrite module "' + identifier + '".'; } _modules[key] = fn; } function alias(alias, identifier) { log('Linked "' + alias + '" to module "' + identifier + '".'); _aliases[PREFIX + alias] = PREFIX + identifier; } return { require: require, cache: cache, alias: alias }; })(this);
var modulr = (function(global) { var _modules = {}, _aliases = {}, _cache = {}, PREFIX = '__module__'; // Prefix identifiers to avoid issues in IE. function log(str) { if (global.console && console.log) { console.log(str); } } function require(identifier) { var m, key = PREFIX + identifier; log('Required module "' + identifier + '".'); if (_aliases[key]) { key = _aliases[key]; log('Found module "' + identifier + '" as alias of module "' + key.replace('__module__', '') + '".'); } if (!_cache[key]) { m = _modules[key]; if (!m) { throw 'Can\'t find module "' + identifier + '".'; } _cache[key] = m(require, {}); } return _cache[key]; } function cache(identifier, fn) { var key = PREFIX + identifier; log('Cached module "' + identifier + '".'); if (_modules[key]) { throw 'Can\'t ovewrite module "' + identifier + '".'; } _modules[key] = fn; } function alias(alias, identifier) { log('Linked "' + alias + '" to module "' + identifier + '".'); _aliases[PREFIX + alias] = PREFIX + identifier; } return { require: require, cache: cache, alias: alias }; })(this);
Add in the first checkin date if it doesn't exist
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import get_object_or_404 from django.db import models, migrations def add_initial_date(apps, schema_editor): Machine = apps.get_model("server", "Machine") for machine in Machine.objects.all(): if not machine.first_checkin: machine.first_checkin = machine.last_checkin machine.save() class Migration(migrations.Migration): dependencies = [ ('server', '0005_auto_20150717_1827'), ] operations = [ migrations.AddField( model_name='machine', name='first_checkin', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='machine', name='sal_version', field=models.TextField(null=True, blank=True), ), migrations.RunPython(add_initial_date), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('server', '0005_auto_20150717_1827'), ] operations = [ migrations.AddField( model_name='machine', name='first_checkin', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='machine', name='sal_version', field=models.TextField(null=True, blank=True), ), ]
Implement positive exit code if feed is not valid
/** * @file * Run validation by CLI */ var Q = require('q'); var getOptions = require('../actions/cli/get-options'); var suppressMessages = require('../actions/suppress'); var validateByW3c = require('../actions/validate-by-w3c'); var getReporter = require('../reporter'); function main() { getOptions() .then(function (options) { return Q.all([ {options: options}, validateByW3c(options.url) ]); }) .then(function (data) { var ctx = data[0]; var validationData = suppressMessages(data[1], ctx.options); var reporter = getReporter(ctx.options.reporter); console.log(reporter(validationData, ctx.options)); process.exit(validationData.isValid ? 0 : 1); }) .done(); } if (module === require.main) { main(); }
/** * @file * Run validation by CLI */ var Q = require('q'); var getOptions = require('../actions/cli/get-options'); var suppressMessages = require('../actions/suppress'); var validateByW3c = require('../actions/validate-by-w3c'); var getReporter = require('../reporter'); function main() { getOptions() .then(function (options) { return Q.all([ {options: options}, validateByW3c(options.url) ]); }) .then(function (data) { var ctx = data[0]; var validationData = suppressMessages(data[1], ctx.options); var reporter = getReporter(ctx.options.reporter); console.log(reporter(validationData, ctx.options)); }) .done(); } if (module === require.main) { main(); }
Add addNotify() which just calls super.addNotify() to fix applet problem
package java.awt; /** * Canvas - * * Copyright (c) 1998 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * @author J. Mehlitz */ public class Canvas extends Component { public Canvas() { // Canvases usually get their own update events, not being updated // sync within their parents flags |= IS_ASYNC_UPDATED; } ClassProperties getClassProperties () { return ClassAnalyzer.analyzeAll( getClass(), true); } public Graphics getGraphics () { Graphics g = super.getGraphics(); if ( g != null ) g.setTarget( this); return g; } // Sun's version of this class apparently has this method. So we put // one here so applets compiled against kaffe's version of this class // will call the right method when they do super.addNotify(). public void addNotify () { super.addNotify(); } public void paint( Graphics g) { // Canvas is a nativeLike Component, i.e. its background would // normally be blanked by the native window system g.clearRect( 0, 0, width, height); } }
package java.awt; /** * Canvas - * * Copyright (c) 1998 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * @author J. Mehlitz */ public class Canvas extends Component { public Canvas() { // Canvases usually get their own update events, not being updated // sync within their parents flags |= IS_ASYNC_UPDATED; } ClassProperties getClassProperties () { return ClassAnalyzer.analyzeAll( getClass(), true); } public Graphics getGraphics () { Graphics g = super.getGraphics(); if ( g != null ) g.setTarget( this); return g; } public void paint( Graphics g) { // Canvas is a nativeLike Component, i.e. its background would // normally be blanked by the native window system g.clearRect( 0, 0, width, height); } }
Update to most recent UserFactor
<?php namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class UserFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = User::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name, 'email' => $this->faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), ]; } /** * Define the model's unverified state. * * @return \Illuminate\Database\Eloquent\Factories\Factory */ public function unverified() { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, ]; }); } }
<?php namespace Database\Factories; /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\User; use Illuminate\Support\Str; use Faker\Generator as Faker; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => Str::random(10), ]; });
Read clientId and clientSecret from fuelsdk-test.properties.
// // PrintAllLists.java - // // Prints the names of all lists in the ExactTarget account // represented by the specified CLIENT_ID and CLIENT_SECRET. // // Copyright (C) 2013 ExactTarget // // Author(s): Ian Murdock <imurdock@exacttarget.com> // package com.exacttarget.fuelsdk.examples; import com.exacttarget.fuelsdk.ETClient; import com.exacttarget.fuelsdk.ETConfiguration; import com.exacttarget.fuelsdk.ETList; import com.exacttarget.fuelsdk.ETListService; import com.exacttarget.fuelsdk.ETSdkException; import com.exacttarget.fuelsdk.ETServiceResponse; public class PrintAllLists { public static void main(String[] args) throws ETSdkException { ETConfiguration configuration = new ETConfiguration("/fuelsdk-test.properties"); ETClient client = new ETClient(configuration); ETListService service = client.getListService(); ETServiceResponse<ETList> response = service.get(client); for (ETList list : response.getResults()) { System.out.println(list.getName()); } } }
// // PrintAllLists.java - // // Prints the names of all lists in the ExactTarget account // represented by the specified CLIENT_ID and CLIENT_SECRET. // // Copyright (C) 2013 ExactTarget // // Author(s): Ian Murdock <imurdock@exacttarget.com> // package com.exacttarget.fuelsdk.examples; import com.exacttarget.fuelsdk.ETClient; import com.exacttarget.fuelsdk.ETConfiguration; import com.exacttarget.fuelsdk.ETList; import com.exacttarget.fuelsdk.ETListService; import com.exacttarget.fuelsdk.ETSdkException; import com.exacttarget.fuelsdk.ETServiceResponse; public class PrintAllLists { private static final String CLIENT_ID = "PUT_CLIENT_ID_HERE"; private static final String CLIENT_SECRET = "PUT_CLIENT_SECRET_HERE"; public static void main(String[] args) throws ETSdkException { ETConfiguration configuration = new ETConfiguration(); configuration.setClientId(CLIENT_ID); configuration.setClientSecret(CLIENT_SECRET); ETClient client = new ETClient(configuration); ETListService service = client.getListService(); ETServiceResponse<ETList> response = service.get(client); for (ETList list : response.getResults()) { System.out.println(list.getName()); } } }
Change resazible window to false
package com.kduda.battleships; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml")); // setUserAgentStylesheet(STYLESHEET_CASPIAN); primaryStage.setTitle("Battleships"); primaryStage.setScene(new Scene(root); primaryStage.setResizable(false); primaryStage.show(); } }
package com.kduda.battleships; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml")); // setUserAgentStylesheet(STYLESHEET_CASPIAN); primaryStage.setTitle("Battleships"); primaryStage.setScene(new Scene(root,1024,768)); primaryStage.show(); } }
Make sure activation status/email is returned when creating a user
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Api\Serializer; class CurrentUserSerializer extends UserSerializer { /** * {@inheritdoc} */ protected function getDefaultAttributes($user) { $attributes = parent::getDefaultAttributes($user); $attributes += [ 'isActivated' => $user->is_activated, 'email' => $user->email, 'readTime' => $this->formatDate($user->read_time), 'unreadNotificationsCount' => (int) $user->getUnreadNotificationsCount(), 'newNotificationsCount' => (int) $user->getNewNotificationsCount(), 'preferences' => (array) $user->preferences ]; return $attributes; } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Api\Serializer; class CurrentUserSerializer extends UserSerializer { /** * {@inheritdoc} */ protected function getDefaultAttributes($user) { $attributes = parent::getDefaultAttributes($user); $attributes += [ 'readTime' => $this->formatDate($user->read_time), 'unreadNotificationsCount' => (int) $user->getUnreadNotificationsCount(), 'newNotificationsCount' => (int) $user->getNewNotificationsCount(), 'preferences' => (array) $user->preferences ]; return $attributes; } }
Revert "Warn about deprecated "panel-include" tag" This reverts commit 3d71a8e3eb9828e5412ec9e6060e6b28d98bd3a4.
/* * Axelor Business Solutions * * Copyright (C) 2005-2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.meta.schema.views; import com.fasterxml.jackson.annotation.JsonTypeName; import javax.xml.bind.annotation.XmlType; @XmlType @JsonTypeName("include") public class PanelInclude extends FormInclude {}
/* * Axelor Business Solutions * * Copyright (C) 2005-2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.meta.schema.views; import com.fasterxml.jackson.annotation.JsonTypeName; import java.lang.invoke.MethodHandles; import javax.xml.bind.annotation.XmlType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Deprecated @XmlType @JsonTypeName("include") public class PanelInclude extends FormInclude { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public PanelInclude() { logger.warn("Usage of \"panel-include\" tag is deprecated. Use view extensions instead."); } }
Return the result of calling emit on emittery
const SubscriberAggregator = require("./SubscriberAggregator"); const Emittery = require("emittery"); class EventManager { constructor(eventManagerOptions) { const { logger, muteReporters, globalConfig } = eventManagerOptions; // Keep a reference to these so it can be cloned // if necessary in truffle-config this.initializationOptions = eventManagerOptions; this.emitter = new Emittery(); const initializationOptions = { emitter: this.emitter, globalConfig, logger, muteReporters }; this.initializeSubscribers(initializationOptions); } emit(event, data) { return this.emitter.emit(event, data); } initializeSubscribers(initializationOptions) { new SubscriberAggregator(initializationOptions); } } module.exports = EventManager;
const SubscriberAggregator = require("./SubscriberAggregator"); const Emittery = require("emittery"); class EventManager { constructor(eventManagerOptions) { const { logger, muteReporters, globalConfig } = eventManagerOptions; // Keep a reference to these so it can be cloned // if necessary in truffle-config this.initializationOptions = eventManagerOptions; this.emitter = new Emittery(); const initializationOptions = { emitter: this.emitter, globalConfig, logger, muteReporters }; this.initializeSubscribers(initializationOptions); } emit(event, data) { this.emitter.emit(event, data); } initializeSubscribers(initializationOptions) { new SubscriberAggregator(initializationOptions); } } module.exports = EventManager;
Bump version to 1.9.22.1 and depend on the CloudStorageClient 1.9.22.1
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing Pipeline lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEnginePipeline", version="1.9.22.1", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine pipeline data processing", url="https://github.com/GoogleCloudPlatform/appengine-pipelines", license="Apache License 2.0", description=("Enable asynchronous pipeline style data processing on " "App Engine"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.22", ], extras_require={'python2.5': ["simplejson >= 3.6.5"]} )
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing Pipeline lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEnginePipeline", version="1.9.21.1", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine pipeline data processing", url="https://github.com/GoogleCloudPlatform/appengine-pipelines", license="Apache License 2.0", description=("Enable asynchronous pipeline style data processing on " "App Engine"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.21", ], extras_require={'python2.5': ["simplejson >= 3.6.5"]} )
Mark dojango as 0.5.6 alpha
VERSION = (0, 5, 6, 'alpha', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
VERSION = (0, 5, 5, 'final', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
Fix expose Lodash global by default.
/** * Module dependencies. */ var _ = require('lodash'); var async = require('async'); /** * exposeGlobals() * * Expose certain global variables * (if config says so) * * @api private */ module.exports = function exposeGlobals() { var sails = this; sails.log.verbose('Exposing global variables... (you can disable this by modifying the properties in `sails.config.globals`)'); // Globals explicitly disabled if (sails.config.globals === false) { return; } sails.config.globals = sails.config.globals || {}; // Provide global access (if allowed in config) if (sails.config.globals._ !== false) { global['_'] = _; } if (sails.config.globals.async !== false) { global['async'] = async; } if (sails.config.globals.sails !== false) { global['sails'] = sails; } // `services` hook takes care of globalizing services (if enabled) // `orm` hook takes care of globalizing models and adapters (if enabled) };
/** * Module dependencies. */ var _ = require('lodash'); var async = require('async'); /** * exposeGlobals() * * Expose certain global variables * (if config says so) * * @api private */ module.exports = function exposeGlobals() { var sails = this; sails.log.verbose('Exposing global variables... (you can disable this by modifying the properties in `sails.config.globals`)'); // Globals explicitly disabled if (sails.config.globals === false) { return; } sails.config.globals = sails.config.globals || {}; // Provide global access (if allowed in config) if (sails.config.globals._) { global['_'] = _; } if (sails.config.globals.async !== false) { global['async'] = async; } if (sails.config.globals.sails !== false) { global['sails'] = sails; } // `services` hook takes care of globalizing services (if enabled) // `orm` hook takes care of globalizing models and adapters (if enabled) };
Fix breaking bug when using a context path
window.registerExtension('issueresolver/entrypoint', function (options) { options.el.id='issueresolver-page'; options.el.className='page page-limited'; var location = options.router.createLocation('/static/issueresolver'); var loader = function() { requirejs.config({ baseUrl: location.basename + location.pathname }); requirejs(['main'], function(main) { main.main(options); }); }; // Adding the script tag to the head as suggested before var script = document.createElement('script'); script.type = 'text/javascript'; script.src = location.basename + location.pathname + '/require.js'; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = loader; script.onload = loader; // Fire the loading options.el.appendChild(script);     return function () { // No clean-up needed    }; });
window.registerExtension('issueresolver/entrypoint', function (options) { options.el.id='issueresolver-page'; options.el.className='page page-limited'; var loader = function() { requirejs.config({ baseUrl: '/static/issueresolver' }); requirejs(['main'], function(main) { main.main(options); }); }; // Adding the script tag to the head as suggested before var script = document.createElement('script'); script.type = 'text/javascript'; script.src = '/static/issueresolver/require.js'; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = loader; script.onload = loader; // Fire the loading options.el.appendChild(script);     return function () { // No clean-up needed    }; });
Change order of moment arguments
import moment from 'moment-timezone'; import AbstractFormat from './abstract'; export default class DateFormat extends AbstractFormat { format(dateValue, dateFormat, locale, timezone) { return this .moment(dateValue, locale, timezone) .format(dateFormat); } moment(dateValue, locale, timezone) { return moment(dateValue) .locale(locale || this._i18n.locale()) .tz(timezone || this._i18n.timezone()); } parse(dateValue, dateFormat, locale, timezone) { const result = moment.tz( dateValue, dateFormat, locale || this._i18n.locale(), true, timezone || this._i18n.timezone() ); return result.isValid() ? result.toDate() : null; } }
import moment from 'moment'; import 'moment-timezone'; import AbstractFormat from './abstract'; export default class DateFormat extends AbstractFormat { format(dateValue, dateFormat, locale, timezone) { return this .moment(locale, timezone, dateValue) .format(dateFormat); } moment(locale, timezone, dateValue) { return moment(dateValue) .locale(locale || this._i18n.locale()) .tz(timezone || this._i18n.timezone()); } parse(dateValue, dateFormat, locale, timezone) { const result = moment.tz( dateValue, dateFormat, locale || this._i18n.locale(), true, timezone || this._i18n.timezone() ); return result.isValid() ? result.toDate() : null; } }
Simplify a bit and obey code convention
var istanbul = require('istanbul'); module.exports = function (runner, options) { mocha.reporters.Base.call(this, runner); var reporterOpts = { dir: 'coverage' }, reporters = ['text-summary', 'html']; options = options || {}; if (options.reporters) reporters = options.reporters.split(','); if (process.env.ISTANBUL_REPORTERS) reporters = process.env.ISTANBUL_REPORTERS.split(','); if (options.reportDir) reporterOpts.dir = options.reportDir; if (process.env.ISTANBUL_REPORT_DIR) reporterOpts.dir = process.env.ISTANBUL_REPORT_DIR; runner.on('end', function(){ var cov = global.__coverage__ || {}, collector = new istanbul.Collector(); collector.add(cov); reporters.forEach(function(reporter) { istanbul.Report.create(reporter, reporterOpts).writeReport(collector, true); }); }); };
var istanbul = require('istanbul'), /** * Expose `Istanbul`. */ exports = module.exports = Istanbul; /** * Initialize a new Istanbul reporter. * * @param {Runner} runner * @param {Object} options * @public */ function Istanbul(runner, options) { mocha.reporters.Base.call(this, runner); var reporterOpts = { dir: 'coverage' }, reporters = ['text-summary', 'html']; options = options || {}; if (options.reporters) reporters = options.reporters.split(','); if (process.env.ISTANBUL_REPORTERS) reporters = process.env.ISTANBUL_REPORTERS.split(','); if (options.reportDir) reporterOpts.dir = options.reportDir; if (process.env.ISTANBUL_REPORT_DIR) reporterOpts.dir = process.env.ISTANBUL_REPORT_DIR; runner.on('end', function(){ var cov = global.__coverage__ || {}, collector = new istanbul.Collector(); collector.add(cov); reporters.forEach(function(reporter) { istanbul.Report.create(reporter, reporterOpts).writeReport(collector, true); }); }); }
Resolve CLIMATE-147 - Add tests for regionSelectParams service - Add getParameters test. git-svn-id: https://svn.apache.org/repos/asf/incubator/climate/trunk@1496037 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 3d2be98562f344323a5532ca5757850d175ba25c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ 'use strict'; describe('OCW Services', function() { beforeEach(module('ocw.services')); describe('RegionSelectParams', function() { it('should initialize the regionSelectParams service', function() { inject(function(regionSelectParams) { expect(regionSelectParams).not.toEqual(null); }); }); it('should provide the getParameters function', function() { inject(function(regionSelectParams) { expect(regionSelectParams.getParameters()).not.toEqual(null); }); }); }); });
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ 'use strict'; describe('OCW Services', function() { beforeEach(module('ocw.services')); describe('RegionSelectParams', function() { it('should initialize the regionSelectParams service', function() { inject(function(regionSelectParams) { expect(regionSelectParams).not.toEqual(null); }); }); }); });
Remove not necessary catch-rethrow because exception is not handled
package de.holisticon.util.tracee.configuration; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Properties; /** * @author Daniel Wegener (Holisticon AG) */ public final class TraceePropertiesFileLoader { public static final String TRACEE_PROPERTIES_FILE = "tracee.properties"; public Properties loadTraceeProperties() throws IOException { final Properties propertiesFromFile = new Properties(); final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> traceePropertyFiles = loader.getResources(TRACEE_PROPERTIES_FILE); while (traceePropertyFiles.hasMoreElements()) { final URL url = traceePropertyFiles.nextElement(); InputStream stream = null; try { stream = url.openStream(); propertiesFromFile.load(stream); } finally { try { if (stream != null) stream.close(); } catch (IOException ignored) {} } } return propertiesFromFile; } }
package de.holisticon.util.tracee.configuration; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Properties; /** * @author Daniel Wegener (Holisticon AG) */ public final class TraceePropertiesFileLoader { public static final String TRACEE_PROPERTIES_FILE = "tracee.properties"; public Properties loadTraceeProperties() throws IOException { final Properties propertiesFromFile = new Properties(); final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> traceePropertyFiles = loader.getResources(TRACEE_PROPERTIES_FILE); while (traceePropertyFiles.hasMoreElements()) { final URL url = traceePropertyFiles.nextElement(); InputStream stream = null; try { stream = url.openStream(); propertiesFromFile.load(stream); } catch (IOException e) { throw e; } finally { try { if (stream != null) stream.close(); } catch (IOException ignored) {} } } return propertiesFromFile; } }
Use database connection instead of old-style functions
import sys from django.conf import settings from django.test.utils import setup_test_environment, teardown_test_environment import nose from nose.config import Config, all_config_files from nose.plugins.manager import DefaultPluginManager def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): """ Run tests with nose instead of defualt test runner """ setup_test_environment() from django.db import connection old_name = settings.DATABASE_NAME connection.creation.create_test_db(verbosity, autoclobber=not interactive) argv_backup = sys.argv # we have to strip script name before passing to nose sys.argv = argv_backup[0:1] config = Config(files=all_config_files(), plugins=DefaultPluginManager()) nose.run(config=config) sys.argv = argv_backup connection.creation.destroy_test_db(old_name, verbosity) teardown_test_environment() #TODO: return len(result.failures) + len(result.errors) run_tests.__test__ = False
from django.test.utils import setup_test_environment, teardown_test_environment from django.db.backends.creation import create_test_db, destroy_test_db import nose def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): """ Run tests with nose instead of defualt test runner """ setup_test_environment() old_name = settings.DATABASE_NAME create_test_db(verbosity, autoclobber=not interactive) argv_backup = sys.argv # we have to strip script name before passing to nose sys.argv = argv_backup[0:1] config = Config(files=all_config_files(), plugins=DefaultPluginManager()) nose.run(config=config) sys.argv = argv_backup destroy_test_db(old_name, verbosity) teardown_test_environment() run_tests.__test__ = False
Fix error parsing dates in release notes menu
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { fetchRecentNews } from '../../../actions/systemActions'; import withAsyncData from '../hocs/AsyncDataContainer'; import RecentNewsMenu from './RecentNewsMenu'; const MAX_ITEMS = 8; const RecentNewsMenuContainer = ({ recentNews }) => ( <React.Fragment> {recentNews && ( <RecentNewsMenu newsItems={recentNews[0].notes.slice(0, MAX_ITEMS)} subTitle={moment(recentNews[0].date, 'YYYY-M-DD').fromNow()} /> )} </React.Fragment> ); RecentNewsMenuContainer.propTypes = { // from parent // from state recentNews: PropTypes.array, // from compositional chain }; const mapStateToProps = state => ({ fetchStatus: state.system.recentNews.fetchStatus, recentNews: state.system.recentNews.releases, }); const fetchAsyncData = dispatch => dispatch(fetchRecentNews()); export default connect(mapStateToProps)( withAsyncData(fetchAsyncData)( RecentNewsMenuContainer ) );
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { fetchRecentNews } from '../../../actions/systemActions'; import withAsyncData from '../hocs/AsyncDataContainer'; import RecentNewsMenu from './RecentNewsMenu'; const MAX_ITEMS = 8; const RecentNewsMenuContainer = ({ recentNews }) => ( <React.Fragment> {recentNews && ( <RecentNewsMenu newsItems={recentNews[0].notes.slice(0, MAX_ITEMS)} subTitle={moment(recentNews[0].notes.date, 'YYYY-MM-DD').fromNow()} /> )} </React.Fragment> ); RecentNewsMenuContainer.propTypes = { // from parent // from state recentNews: PropTypes.array, // from compositional chain }; const mapStateToProps = state => ({ fetchStatus: state.system.recentNews.fetchStatus, recentNews: state.system.recentNews.releases, }); const fetchAsyncData = dispatch => dispatch(fetchRecentNews()); export default connect(mapStateToProps)( withAsyncData(fetchAsyncData)( RecentNewsMenuContainer ) );