text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Increment version number for git master
"""Scrypt for Python""" __version__ = '1.2.0-git' # First, try loading libscrypt _done = False try: from pylibscrypt import * except ImportError: pass else: _done = True # If that didn't work, try the scrypt module if not _done: try: from pyscrypt import * except ImportError: pass else: _done = True # Unless we are on pypy, we want to try libsodium as well if not _done: import platform if platform.python_implementation() != 'PyPy': try: from pylibsodium import * except ImportError: pass else: _done = True # If that didn't work either, the inlined Python version if not _done: try: from pypyscrypt_inline import * except ImportError: pass else: _done = True # Finally the non-inlined if not _done: from pypyscrypt import * __all__ = ['scrypt', 'scrypt_mcf', 'scrypt_mcf_check'] # Clean up pydoc output del __path__ del consts
'Scrypt for Python' __version__ = '1.1.0' # First, try loading libscrypt _done = False try: from pylibscrypt import * except ImportError: pass else: _done = True # If that didn't work, try the scrypt module if not _done: try: from pyscrypt import * except ImportError: pass else: _done = True # Unless we are on pypy, we want to try libsodium as well if not _done: import platform if platform.python_implementation() != 'PyPy': try: from pylibsodium import * except ImportError: pass else: _done = True # If that didn't work either, the inlined Python version if not _done: try: from pypyscrypt_inline import * except ImportError: pass else: _done = True # Finally the non-inlined if not _done: from pypyscrypt import * __all__ = ['scrypt', 'scrypt_mcf', 'scrypt_mcf_check'] # Clean up pydoc output del __path__ del consts
Rename tests to avoid name re-use
import ML.naivebayes as naivebayes import data def test_gaussian_naive_bayes(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.GaussianNaiveBayes() nb.fit(X, y) for index, row in enumerate(X): predicted_y = nb.predict(row) assert predicted_y == y[index] def test_gaussian_naive_bayes_probs(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.GaussianNaiveBayes() nb.fit(X, y) y_probabilities = nb.predict(X[0], probabilities=True) assert y_probabilities[y[0]] == 1.0 def test_bernoulli_naive_bayes(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.BernoulliNaiveBayes() nb.fit(X, y) for index, row in enumerate(X): predicted_y = nb.predict(row) assert predicted_y == y[index] def test_bernoulli_naive_bayes_probs(): X, y = data.categorical_2Dmatrix_bernoulli_data() nb = naivebayes.BernoulliNaiveBayes() nb.fit(X, y) y_probabilities = nb.predict(X[0], probabilities=True) assert y_probabilities[y[0]] == 1.0
import ML.naivebayes as naivebayes import data import numpy as np def test_gaussian_naive_bayes(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.GaussianNaiveBayes() nb.fit(X, y) for index, row in enumerate(X): predicted_y = nb.predict(row) assert predicted_y == y[index] def test_gaussian_naive_bayes(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.GaussianNaiveBayes() nb.fit(X, y) y_probabilities = nb.predict(X[0], probabilities=True) assert y_probabilities[y[0]] == 1.0 def test_bernoulli_naive_bayes(): X, y = data.categorical_2Dmatrix_data() nb = naivebayes.BernoulliNaiveBayes() nb.fit(X, y) for index, row in enumerate(X): predicted_y = nb.predict(row) assert predicted_y == y[index] def test_bernoulli_naive_bayes(): X, y = data.categorical_2Dmatrix_bernoulli_data() nb = naivebayes.BernoulliNaiveBayes() nb.fit(X, y) y_probabilities = nb.predict(X[0], probabilities=True) assert y_probabilities[y[0]] == 1.0
Hide body of the index page when redirecting
var utils = require('utils'); var $ = require('jquery'); var AppId = { app_id: ( document.location.port === '8080' ) ? 1168 : ( ( document.location.hostname.indexOf('github.io') >= 0 ) ? 1180 : 1169 ), redirectOauth: function oauthLogin(){ document.location = 'https://oauth.binary.com/oauth2/authorize?app_id=' + this.app_id + '&l=' + window.lang.toUpperCase(); }, oauthLogin: function getToken(done) { var queryStr = utils.parseQueryString(); var tokenList = []; Object.keys(queryStr).forEach(function(key){ if ( key.indexOf('token') === 0 ) { tokenList.push(queryStr[key]); } }); if (tokenList.length) { $('#main').hide(); utils.addAllTokens(tokenList, function(){ document.location.pathname += ((document.location.pathname.slice(-1) === '/')?'':'/') + 'bot.html'; }); } else { if (done) { done(); } } }, removeTokenFromUrl: function removeTokenFromUrl(){ var queryStr = utils.parseQueryString(); if (queryStr.token1) { document.location.href = document.location.href.split('?')[0]; } }, getAppId: function getAppId(){ return this.app_id; } }; module.exports = AppId;
var utils = require('utils'); var AppId = { app_id: ( document.location.port === '8080' ) ? 1168 : ( ( document.location.hostname.indexOf('github.io') >= 0 ) ? 1180 : 1169 ), redirectOauth: function oauthLogin(){ document.location = 'https://oauth.binary.com/oauth2/authorize?app_id=' + this.app_id + '&l=' + window.lang.toUpperCase(); }, oauthLogin: function getToken(done) { var queryStr = utils.parseQueryString(); var tokenList = []; Object.keys(queryStr).forEach(function(key){ if ( key.indexOf('token') === 0 ) { tokenList.push(queryStr[key]); } }); if (tokenList.length) { utils.addAllTokens(tokenList, function(){ document.location.pathname += ((document.location.pathname.slice(-1) === '/')?'':'/') + 'bot.html'; }); } else { if (done) { done(); } } }, removeTokenFromUrl: function removeTokenFromUrl(){ var queryStr = utils.parseQueryString(); if (queryStr.token1) { document.location.href = document.location.href.split('?')[0]; } }, getAppId: function getAppId(){ return this.app_id; } }; module.exports = AppId;
Return the correct class in getFacadeAccessor function
<?php /* * This file is part of Bestboysmedialab-LanguageList * * (c) 2016 best boys media lab GmbH & Co. KG * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * * @category Bestboysmedialab * @package LanguageList * @copyright (c) 2016 best boys media lab GmbH & Co. KG <volker.ansmann@bestboys-medialab.com> * @link http://www.bestboys-medialab.com */ namespace Bestboysmedialab\LanguageList; use Illuminate\Support\Facades\Facade; /** * LanguageListFacade * * @author Volker Ansmann <volker.ansmann@bestboys-medialab.com> */ class LanguageListFacade extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return LanguageList::class; } }
<?php /* * This file is part of Bestboysmedialab-LanguageList * * (c) 2016 best boys media lab GmbH & Co. KG * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * * @category Bestboysmedialab * @package LanguageList * @copyright (c) 2016 best boys media lab GmbH & Co. KG <volker.ansmann@bestboys-medialab.com> * @link http://www.bestboys-medialab.com */ namespace Bestboysmedialab\LanguageList; use Illuminate\Support\Facades\Facade; /** * LanguageListFacade * * @author Volker Ansmann <volker.ansmann@bestboys-medialab.com> */ class LanguageListFacade extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'languagelist'; } }
Change element location rule to evade Zombie error during form reset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru"> <head> <title>Basic Form</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body> <h1>Basic Form Page</h1> <form method="POST" action="basic_form_post.php"> <input name="first_name" value="Firstname" type="text" /> <input id="lastn" name="last_name" value="Lastname" type="text" /> <input type="reset" id="Reset" /> <input type="submit" id="Save" /> </form> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru"> <head> <title>Basic Form</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body> <h1>Basic Form Page</h1> <form method="POST" action="basic_form_post.php"> <input name="first_name" value="Firstname" type="text" /> <input id="lastn" name="last_name" value="Lastname" type="text" /> <input type="reset" value="Reset" /> <input type="submit" value="Save" /> </form> </body> </html>
Advance the minor version to reflect the bug fixes
#from distutils.core import setup from setuptools import setup setup( name='django-auth_mac', version='0.1.2', description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01", author='Nicholas Devenish', author_email='n.devenish@gmail.com', packages=['auth_mac', 'auth_mac.tests'], license=open('LICENSE.txt').read(), long_description=open('README.rst').read(), url='https://github.com/ndevenish/auth_mac', keywords = ['django', 'authorization', 'MAC'], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Development Status :: 2 - Pre-Alpha", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=['Django >= 1.3'], zip_safe=False, )
#from distutils.core import setup from setuptools import setup setup( name='django-auth_mac', version='0.1.1', description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01", author='Nicholas Devenish', author_email='n.devenish@gmail.com', packages=['auth_mac', 'auth_mac.tests'], license=open('LICENSE.txt').read(), long_description=open('README.rst').read(), url='https://github.com/ndevenish/auth_mac', keywords = ['django', 'authorization', 'MAC'], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Development Status :: 2 - Pre-Alpha", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=['Django >= 1.3'], zip_safe=False, )
Address review comment: Link to issue.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. https://clusterhq.atlassian.net/browse/FLOC-1269 will deal with semantics of expiring data, which should happen so stale information isn't treated as correct. """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. (Follow up issue will deal with semantics of expiring data, which should happen so stale information isn't stored. This needs some extra work for the agent resending state even when it doesn't change, etc..) """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
Remove excludeFilter that is now enabled by default.
package ${package}.config; import org.springframework.context.annotation.*; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.tiles2.TilesConfigurer; import org.springframework.web.servlet.view.tiles2.TilesViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "${package}" }) @Import(PersistenceConfig.class) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean public TilesViewResolver configureTilesViewResolver() { return new TilesViewResolver(); } @Bean public TilesConfigurer configureTilesConfigurer() { TilesConfigurer configurer = new TilesConfigurer(); configurer.setDefinitions(new String[] {"/WEB-INF/tiles/tiles.xml", "/WEB-INF/views/**/views.xml"}); return configurer; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/").addResourceLocations("/recourses/**"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
package ${package}.config; import org.springframework.context.annotation.*; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.tiles2.TilesConfigurer; import org.springframework.web.servlet.view.tiles2.TilesViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "${package}" }, excludeFilters = @Filter(type = FilterType.ANNOTATION, value = Configuration.class)) @Import(PersistenceConfig.class) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean public TilesViewResolver configureTilesViewResolver() { return new TilesViewResolver(); } @Bean public TilesConfigurer configureTilesConfigurer() { TilesConfigurer configurer = new TilesConfigurer(); configurer.setDefinitions(new String[] {"/WEB-INF/tiles/tiles.xml", "/WEB-INF/views/**/views.xml"}); return configurer; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/").addResourceLocations("/recourses/**"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
Fix clicking on a category not working
angular.module('eappApp').controller('CategoryController', ["$scope", "$rootScope", "eapp", function ($scope, $rootScope, eapp) { $rootScope.isMainMenu = true; $scope.loading = false; $scope.Init = function() { var categoriesPromise = eapp.getCategories(); $scope.loading = true; categoriesPromise.then(function(response) { $scope.categories = response.data; $scope.loading = false; }); }; $rootScope.select_category = function($event, category) { $scope.clearSessionItems(); var category_id = parseInt(category.id); eapp.recordHit("eapp_product_category ",category_id); window.sessionStorage.setItem("category_id", category_id); window.sessionStorage.setItem("category_name", category.name); window.location = $scope.site_url.concat("/shop"); }; angular.element(document).ready(function() { $scope.Init(); }); }]);
angular.module('eappApp').controller('CategoryController', ["$scope", "$rootScope", "eapp", function ($scope, $rootScope, eapp) { $rootScope.isMainMenu = true; $scope.loading = false; $scope.Init = function() { var categoriesPromise = eapp.getCategories(); $scope.loading = true; categoriesPromise.then(function(response) { $scope.categories = response.data; $scope.loading = false; }); }; angular.element(document).ready(function() { $scope.Init(); }); }]);
Use border-box style for all elements
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; overscroll-behavior-y: none; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; overscroll-behavior-y: none; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
Clone defaults when creating new project For obvious reasons.
var _ = require('lodash'); var AppDispatcher = require('../dispatcher/AppDispatcher'); var ProjectConstants = require('../constants/ProjectConstants'); var defaults = require('../config').defaults; var ProjectActions = { create: function() { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_CREATED, project: _.cloneDeep(defaults) }); }, updateSource: function(projectKey, language, source) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_SOURCE_EDITED, projectKey: projectKey, language: language, source: source }); }, toggleLibrary: function(projectKey, libraryKey) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_LIBRARY_TOGGLED, projectKey: projectKey, libraryKey: libraryKey }); }, loadFromStorage: function(project) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_LOADED_FROM_STORAGE, projectKey: project.projectKey, project: project }); } }; module.exports = ProjectActions;
var AppDispatcher = require('../dispatcher/AppDispatcher'); var ProjectConstants = require('../constants/ProjectConstants'); var defaults = require('../config').defaults; var ProjectActions = { create: function() { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_CREATED, project: defaults }); }, updateSource: function(projectKey, language, source) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_SOURCE_EDITED, projectKey: projectKey, language: language, source: source }); }, toggleLibrary: function(projectKey, libraryKey) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_LIBRARY_TOGGLED, projectKey: projectKey, libraryKey: libraryKey }); }, loadFromStorage: function(project) { AppDispatcher.dispatch({ actionType: ProjectConstants.PROJECT_LOADED_FROM_STORAGE, projectKey: project.projectKey, project: project }); } }; module.exports = ProjectActions;
Improve selection sort algorithm's documentation
def selection_sort(L): """ (list) -> NoneType Sort list from smallest to largest using selection sort algorithm :param L: unsorted list >>> L = [2, 7, 5, 3] >>> selection_sort(L) >>> L [2, 3, 5, 7] """ end = len(L) # Find the index of the smallest element in L[i:] and swap that item # with the item at index i for i in range(end): index_of_smallest = get_index_of_smallest(L, i) L[index_of_smallest], L[i] = L[i], L[index_of_smallest] def get_index_of_smallest(L, i): """ (list, int) -> int :param L: list we want to analyse :param i: index from where we want to start :return: index of smallest object in the list """ # The index of the smallest item so far index_of_smallest = i end = len(L) for j in range(i + 1, end): if L[j] < L[index_of_smallest]: index_of_smallest = j return index_of_smallest if __name__ == '__main__': import doctest doctest.testmod()
def selection_sort(L): """ :param L: unsorted list :return: this is a method, there is no return function. The method sorts a list using selection sort algorithm >>> L = [2, 7, 5, 3] >>> selection_sort(L) >>> L [2, 3, 5, 7] """ end = len(L) # Find the index of the smallest element in L[i:] and swap that item # with the item at index i for i in range(end): index_of_smallest = get_index_of_smallest(L, i) L[index_of_smallest], L[i] = L[i], L[index_of_smallest] def get_index_of_smallest(L, i): """ (list, int) -> int :param L: list we want to analyse :param i: index from where we want to start :return: index of smallest object in the list """ # The index of the smallest item so far index_of_smallest = i end = len(L) for j in range(i + 1, end): if L[j] < L[index_of_smallest]: index_of_smallest = j return index_of_smallest if __name__ == '__main__': import doctest doctest.testmod()
Stats: Fix bug with MySQL Database.
from cStringIO import StringIO from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure class GraphToolException(Exception): pass def fig_to_data(fig): s = StringIO() fig.print_png(s) r = s.getvalue() s.close() return r class GraphTool(object): def __init__(self): pass def commit_bar(self, _time, amount, _title='Unknown title', _xlabel = 'Unknown time type', _ylabel='Unknown amount type'): """ Generate a bar plot with <time> on X, amount on Y. Specify amount label with _ylabel, time label with _xlabel. """ fig = Figure(edgecolor='#FFFFFF', facecolor='#FFFFFF') canvas = FigureCanvas(fig) h = fig.add_subplot(111) h.bar(_time, amount) h.set_xlabel(_xlabel) h.set_ylabel(_ylabel) h.set_xbound(_time[0], _time[len(_time)-1]) h.set_ybound(0, int(max(amount))) h.set_axis_bgcolor('#FFFFFF') h.set_title(_title) return fig_to_data(canvas)
from cStringIO import StringIO from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure class GraphToolException(Exception): pass def fig_to_data(fig): s = StringIO() fig.print_png(s) r = s.getvalue() s.close() return r class GraphTool(object): def __init__(self): pass def commit_bar(self, _time, amount, _title='Unknown title', _xlabel = 'Unknown time type', _ylabel='Unknown amount type'): """ Generate a bar plot with <time> on X, amount on Y. Specify amount label with _ylabel, time label with _xlabel. """ fig = Figure(edgecolor='#FFFFFF', facecolor='#FFFFFF') canvas = FigureCanvas(fig) h = fig.add_subplot(111) h.bar(_time, amount) h.set_xlabel(_xlabel) h.set_ylabel(_ylabel) h.set_xbound(_time[0], _time[len(_time)-1]) h.set_ybound(0, max(amount)) h.set_axis_bgcolor('#FFFFFF') h.set_title(_title) return fig_to_data(canvas)
Add the about page to url.py
from django.conf.urls import patterns, url from django.views.generic import TemplateView from studentvoice import views urlpatterns = patterns('', url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^create/$', views.create, name='create'), url(r'^search/', views.search, name='search'), url(r'^(?P<voice_id>\d+)/$', views.show, name='show'), url(r'^vote/$', views.vote, name='vote'), url(r'^(?P<voice_id>\d+)/report/$', views.report, name='report'), url(r'^(?P<voice_id>\d+)/create_comment/$', views.create_comment, name='create_comment'), url(r'^delete/(?P<voice_id>\d+)/$', views.delete, name='delete'), url(r'^(?P<voice_id>\d+)/edit/$', views.edit, name='edit'), url(r'^(?P<voice_id>\d+)/respond/$', views.respond, name='respond'), url(r'^(?P<voice_id>\d+)/respond/edit/$', views.edit_response, name='edit_response'), )
from django.conf.urls import patterns, url from django.views.generic import TemplateView from studentvoice import views urlpatterns = patterns('', url(r'^$', views.home, name='home'), url(r'^create/$', views.create, name='create'), url(r'^search/', views.search, name='search'), url(r'^(?P<voice_id>\d+)/$', views.show, name='show'), url(r'^vote/$', views.vote, name='vote'), url(r'^(?P<voice_id>\d+)/report/$', views.report, name='report'), url(r'^(?P<voice_id>\d+)/create_comment/$', views.create_comment, name='create_comment'), url(r'^delete/(?P<voice_id>\d+)/$', views.delete, name='delete'), url(r'^(?P<voice_id>\d+)/edit/$', views.edit, name='edit'), url(r'^(?P<voice_id>\d+)/respond/$', views.respond, name='respond'), url(r'^(?P<voice_id>\d+)/respond/edit/$', views.edit_response, name='edit_response'), )
Change request matching cron to not allow admins to run directly
package com.google.step.coffee.tasks; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.step.coffee.PermissionChecker; import com.google.step.coffee.UserManager; import com.google.step.coffee.data.RequestStore; import com.google.step.coffee.entity.ChatRequest; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet triggered as cron job to match current chat requests together. Triggered periodically by * fetch. */ @WebServlet("/api/tasks/request-matching") public class RequestMatchingTask extends HttpServlet { private RequestMatcher matcher = new RequestMatcher(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cronHeader = req.getHeader("X-Appengine-Cron"); UserService userService = UserServiceFactory.getUserService(); if (cronHeader == null || !Boolean.parseBoolean(cronHeader)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden action."); return; } RequestStore requestStore = new RequestStore(); List<ChatRequest> requestList = requestStore.getUnmatchedRequests(); matcher.matchRequests(requestList, requestStore); resp.setStatus(HttpServletResponse.SC_OK); } }
package com.google.step.coffee.tasks; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.step.coffee.PermissionChecker; import com.google.step.coffee.UserManager; import com.google.step.coffee.data.RequestStore; import com.google.step.coffee.entity.ChatRequest; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet triggered as cron job to match current chat requests together. Triggered periodically by * fetch. */ @WebServlet("/api/tasks/request-matching") public class RequestMatchingTask extends HttpServlet { private RequestMatcher matcher = new RequestMatcher(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cronHeader = req.getHeader("X-Appengine-Cron"); UserService userService = UserServiceFactory.getUserService(); if (cronHeader == null || !Boolean.parseBoolean(cronHeader) || !userService.isUserAdmin()) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden action."); return; } RequestStore requestStore = new RequestStore(); List<ChatRequest> requestList = requestStore.getUnmatchedRequests(); matcher.matchRequests(requestList, requestStore); resp.setStatus(HttpServletResponse.SC_OK); } }
Disable fetching on new props
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { dispatched } from 'react-prepare'; import { fetchAll } from 'app/actions/EventActions'; import EventList from './components/EventList'; import { selectSortedEvents } from 'app/reducers/events'; import moment from 'moment'; const mapStateToProps = (state, ownProps) => { const user = ownProps.currentUser; const icalToken = user ? user.icalToken : null; const actionGrant = state => state.events.actionGrant; return { ...createStructuredSelector({ events: selectSortedEvents, actionGrant })(state, ownProps), icalToken }; }; export default compose( dispatched((props, dispatch) => dispatch(fetchAll({ dateAfter: moment().format('YYYY-MM-DD') })), { componentWillReceiveProps: false } ), connect(mapStateToProps) )(EventList);
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { dispatched } from 'react-prepare'; import { fetchAll } from 'app/actions/EventActions'; import EventList from './components/EventList'; import { selectSortedEvents } from 'app/reducers/events'; import moment from 'moment'; const mapStateToProps = (state, ownProps) => { const user = ownProps.currentUser; const icalToken = user ? user.icalToken : null; const actionGrant = state => state.events.actionGrant; return { ...createStructuredSelector({ events: selectSortedEvents, actionGrant })(state, ownProps), icalToken }; }; export default compose( dispatched((props, dispatch) => dispatch(fetchAll({ dateAfter: moment().format('YYYY-MM-DD') })) ), connect(mapStateToProps) )(EventList);
Use Materialize toasts to show the status
$(document).ready(function() { $("#invite-form").on('submit', function() { var inviteeEmail = $("#email").val(); console.log(inviteeEmail) if (!inviteeEmail || !inviteeEmail.length) { alert('Please enter an email'); return false; } $.ajax({ type: "POST", url: "/", headers: { 'X-CSRFToken': csrfToken, }, data: { email: inviteeEmail}, success: function(data) { handleResponse(data); } }); return false; }); }); function handleResponse(data) { document.data = data if (data.status === 'success') { console.log('success') Materialize.toast('Success!', 4000) } if (data.status === 'fail') { Materialize.toast(data.error, 4000) } }
$(document).ready(function() { $("#invite-form").on('submit', function() { var inviteeEmail = $("#email").val(); console.log(inviteeEmail) if (!inviteeEmail || !inviteeEmail.length) { alert('Please enter an email'); return false; } $.ajax({ type: "POST", url: "/", headers: { 'X-CSRFToken': csrfToken, }, data: { email: inviteeEmail}, success: function(data) { handleResponse(data); } }); return false; }); }); function handleResponse(data) { document.data = data if (data.status === 'success') { console.log('success') } if (data.status === 'fail') { console.log('failed') } }
Use an XQueryCDataSection for the CDataSection PSI.
/* * Copyright (C) 2016 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCDataSection; public class XQueryCDataSectionPsiImpl extends ASTWrapperPsiElement implements XQueryCDataSection { public XQueryCDataSectionPsiImpl(@NotNull ASTNode node) { super(node); } }
/* * Copyright (C) 2016 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; public class XQueryCDataSectionPsiImpl extends ASTWrapperPsiElement { public XQueryCDataSectionPsiImpl(@NotNull ASTNode node) { super(node); } }
Add reference to allowed sources
import dotenv from "dotenv"; import moment from "moment"; dotenv.load(); export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test"; export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test"; export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates"; export const LOG_LEVEL = process.env.LOG_LEVEL || "info"; export const ALLOWED_SOURCES = ["reading", "forecast", "reference"]; export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds(); export const FORMULAS_COLLECTION = "virtual-sensors-formulas"; export const PRODUCER = "iwwa-lambda-virtual-aggregator"; export const EVENT_READING_INSERTED = "element inserted in collection readings";
import dotenv from "dotenv"; import moment from "moment"; dotenv.load(); export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test"; export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test"; export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates"; export const LOG_LEVEL = process.env.LOG_LEVEL || "info"; export const ALLOWED_SOURCES = ["reading", "forecast"]; export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds(); export const FORMULAS_COLLECTION = "virtual-sensors-formulas"; export const PRODUCER = "iwwa-lambda-virtual-aggregator"; export const EVENT_READING_INSERTED = "element inserted in collection readings";
Fix background - abs url for injected code
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } var initContactMPsPymParent = function() { var pymParent = new pym.Parent('contactmps-embed-parent', baseurl + '/campaign/newsmedia/', {}); }; var agent = navigator.userAgent.toLowerCase(); if (agent.includes("mobile") && agent.includes("android")) { // addEventListener only available in later chrome versions window.addEventListener("load",function(){ window.addEventListener('error', function(e) { ga('send', 'event', 'JavaScript Error Parent', e.filename + ': ' + e.lineno, e.message); }); }); // Don't initialise pymParent! we iframe it ourselves! document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(https://noconfidencevote.openup.org.za/static/images/background.svg); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); } else { document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous" async defer onload="initContactMPsPymParent()"></script>'); }
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } var initContactMPsPymParent = function() { var pymParent = new pym.Parent('contactmps-embed-parent', baseurl + '/campaign/newsmedia/', {}); }; var agent = navigator.userAgent.toLowerCase(); if (agent.includes("mobile") && agent.includes("android")) { // addEventListener only available in later chrome versions window.addEventListener("load",function(){ window.addEventListener('error', function(e) { ga('send', 'event', 'JavaScript Error Parent', e.filename + ': ' + e.lineno, e.message); }); }); // Don't initialise pymParent! we iframe it ourselves! document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(\'/static/images/background.svg\'); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); } else { document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous" async defer onload="initContactMPsPymParent()"></script>'); }
Write output to .sty file.
import re # Input file created from http://astronautweb.co/snippet/font-awesome/ INPUT_FILE = 'htmlfontawesome.txt' OUTPUT_FILE = 'fontawesome.sty' with open(INPUT_FILE) as r, open(OUTPUT_FILE, 'w') as w: for line in r: # Expects to find 'fa-NAME' ending with " name = re.findall(r'fa-[^""]*', line)[0] # Expects to find '\fSYMBOL' ending with " symbol = re.findall(r'\\f[^"]*', line)[0][1:].upper() camel_case = [w.capitalize() for w in name.split('-')] camel_case[0] = camel_case[0].lower() camel_name = ''.join(camel_case) name = name.lstrip('fa-') print('\expandafter\def\csname faicon@{name}\endcsname ' '{{\symbol{{"{symbol}}}}} \def\{camel_name} ' '{{{{\FA\csname faicon@{name}\endcsname}}}}'.format(name=name, camel_name=camel_name, symbol=symbol), file=w)
import re # Input file created from http://astronautweb.co/snippet/font-awesome/ INPUT_FILE = 'htmlfontawesome.txt' with open(INPUT_FILE) as r: for line in r: # Expects to find 'fa-NAME' ending with " name = re.findall(r'fa-[^""]*', line)[0] # Expects to find '\fSYMBOL' ending with " symbol = re.findall(r'\\f[^"]*', line)[0][1:].upper() camel_case = [w.capitalize() for w in name.split('-')] camel_case[0] = camel_case[0].lower() camel_name = ''.join(camel_case) name = name.lstrip('fa-') print('\expandafter\def\csname faicon@{name}\endcsname ' '{{\symbol{{"{symbol}}}}} \def\{camel_name} ' '{{{{\FA\csname faicon@{name}\endcsname}}}}'.format(name=name, camel_name=camel_name, symbol=symbol))
Write fusion Reducer as additions to List
package es.tid.cosmos.mobility.activityarea; import java.io.IOException; import java.util.List; import java.util.ArrayList; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Reducer; import es.tid.cosmos.mobility.data.MobProtocol.ActivityArea; import es.tid.cosmos.mobility.data.MobProtocol.ActivityAreaKey; import es.tid.cosmos.mobility.data.MobProtocol.Cell; /** * * @author losa */ public class FusionTotalVarsReducer extends Reducer< ProtobufWritable<ActivityAreaKey>, ProtobufWritable<ActivityArea>, ProtobufWritable<ActivityAreaKey>, List<ProtobufWritable<ActivityArea>>> { private List<ProtobufWritable<ActivityArea>> allAreas; @Override protected void reduce(ProtobufWritable<ActivityAreaKey> key, Iterable<ProtobufWritable<ActivityArea>> values, Context context) throws IOException, InterruptedException { this.allAreas = new ArrayList<ProtobufWritable<ActivityArea>>(); for (ProtobufWritable<ActivityArea> value : values) { allAreas.add(value); } context.write(key, allAreas); } }
package es.tid.cosmos.mobility.activityarea; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Reducer; import es.tid.cosmos.mobility.data.MobProtocol.ActivityArea; import es.tid.cosmos.mobility.data.MobProtocol.ActivityAreaKey; import es.tid.cosmos.mobility.data.MobProtocol.Cell; /** * * @author losa */ public class FusionTotalVarsReducer extends Reducer< ProtobufWritable<ActivityAreaKey>, ProtobufWritable<ActivityArea>, ProtobufWritable<ActivityAreaKey>, ProtobufWritable<Cell>> { @Override protected void reduce(ProtobufWritable<ActivityAreaKey> key, Iterable<ProtobufWritable<ActivityArea>> values, Context context) throws IOException, InterruptedException { } }
Add `@CheckReturnValue` to package info
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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. */ /** * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package. */ @CheckReturnValue @ParametersAreNonnullByDefault package io.spine.server.storage.jdbc.aggregate.given; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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. */ /** * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package. */ @ParametersAreNonnullByDefault package io.spine.server.storage.jdbc.aggregate.given; import javax.annotation.ParametersAreNonnullByDefault;
Remove recently published test for pending events Former-commit-id: c85ae777aea382c08b9d5da5fd519d20d2b6baf6
package au.gov.ga.geodesy.domain.model.event; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; public class EventRepositoryImpl implements EventRepositoryCustom { @PersistenceContext(unitName = "geodesy") private EntityManager entityManager; // TODO: move out of custom public List<Event> getPendingEvents() { String queryString = "select e from Event e " + "where e.timeHandled is null and (e.retries is null or e.retries < " + Event.MAX_RETRIES + ") and (e.timePublished is null)"; TypedQuery<Event> query = entityManager.createQuery(queryString, Event.class); return query.getResultList(); } }
package au.gov.ga.geodesy.domain.model.event; import java.time.Instant; import java.util.Calendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; public class EventRepositoryImpl implements EventRepositoryCustom { @PersistenceContext(unitName = "geodesy") private EntityManager entityManager; public List<Event> getPendingEvents() { // TODO: try to remove oneMinuteAgo String queryString = "select e from Event e " + "where e.timeHandled is null and (e.retries is null or e.retries < " + Event.MAX_RETRIES + ") and (e.timePublished is null or e.timePublished < :oneMinuteAgo)"; TypedQuery<Event> query = entityManager.createQuery(queryString, Event.class); Calendar c = Calendar.getInstance(); c.add(Calendar.MINUTE, -1); query.setParameter("oneMinuteAgo", c.getTime()); return query.getResultList(); } }
Fix test. Everything works ok with CI and reporting. Yikes!
import assert from 'assert'; import fs from 'fs'; import rimraf from 'rimraf'; const tmpProjectName = 'testRjankoProject'; describe('Rjanko', function() { describe('action', function() { before(function(){ if (fs.existsSync(tmpProjectName)) { rimraf.sync(tmpProjectName); } }); it('project directory should exist after creation', function(done){ var createAction = require('../src/actions/create'); createAction({name: tmpProjectName}).then(() => { assert.equal(fs.existsSync(tmpProjectName), true); //assert.equal(fs.existsSync(`${tmpProjectName}/package.json`), true); done() }); }); after(function() { rimraf.sync(tmpProjectName); }) }) });
import assert from 'assert'; import fs from 'fs'; import rimraf from 'rimraf'; const tmpProjectName = 'testRjankoProject'; describe('Rjanko', function() { describe('action', function() { before(function(){ if (fs.existsSync(tmpProjectName)) { rimraf.sync(tmpProjectName); } }); it('project directory should exist after creation', function(done){ var createAction = require('../src/actions/create'); createAction({name: tmpProjectName}).then(() => { assert.equal(fs.existsSync(tmpProjectName), true); assert.equal(fs.existsSync(`${tmpProjectName}/package.json`), true); done() }); }); after(function() { rimraf.sync(tmpProjectName); }) }) });
refactor: Add static template() method to base
class ComponentViewModel { constructor (root, params, attrs, MDCFoundation, MDCComponent) { this.root = root; this.foundation = MDCFoundation; this.attachTo = MDCComponent.attachTo; this.instance = ko.observable({}); ko.utils.objectForEach(this.defaultParams(), (name, defaultValue) => { if (params.hasOwnProperty(name)) { this[name] = params[name]; delete params[name]; } else { this[name] = defaultValue; } }); ko.utils.arrayForEach(this.unwrapParams(), name => this[name] = ko.toJS(this[name])); delete params.$raw; if (params.hasOwnProperty('')) { delete params['']; } this.bindings = params; this.attrs = attrs; } defaultParams () { return {} } unwrapParams () { return [] } initialize (parent) { } static template () { return ''; } } export default ComponentViewModel;
class ComponentViewModel { constructor (root, params, attrs, MDCFoundation, MDCComponent) { this.root = root; this.foundation = MDCFoundation; this.attachTo = MDCComponent.attachTo; this.instance = ko.observable({}); ko.utils.objectForEach(this.defaultParams(), (name, defaultValue) => { if (params.hasOwnProperty(name)) { this[name] = params[name]; delete params[name]; } else { this[name] = defaultValue; } }); ko.utils.arrayForEach(this.unwrapParams(), name => this[name] = ko.toJS(this[name])); delete params.$raw; if (params.hasOwnProperty('')) { delete params['']; } this.bindings = params; this.attrs = attrs; } defaultParams () { return {} } unwrapParams () { return [] } initialize (parent) { } } export default ComponentViewModel;
Use the new README file, which has been renamed in 4ec717c11604
#!/usr/bin/env python # encoding: utf-8 """ setup.py Setup the Keyring Lib for Python. """ import sys from distutils.core import setup, Extension from extensions import get_extensions setup(name = 'keyring', version = "0.5.1", description = "Store and access your passwords safely.", url = "http://home.python-keyring.org/", keywords = "keyring Keychain GnomeKeyring Kwallet password storage", maintainer = "Kang Zhang", maintainer_email = "jobo.zh@gmail.com", license="PSF", long_description = open('README').read() + open('CHANGES.txt').read(), platforms = ["Many"], packages = ['keyring', 'keyring.tests', 'keyring.util', 'keyring.backends'], ext_modules = get_extensions() )
#!/usr/bin/env python # encoding: utf-8 """ setup.py Setup the Keyring Lib for Python. """ import sys from distutils.core import setup, Extension from extensions import get_extensions setup(name = 'keyring', version = "0.5.1", description = "Store and access your passwords safely.", url = "http://home.python-keyring.org/", keywords = "keyring Keychain GnomeKeyring Kwallet password storage", maintainer = "Kang Zhang", maintainer_email = "jobo.zh@gmail.com", license="PSF", long_description = open('README.txt').read() + open('CHANGES.txt').read(), platforms = ["Many"], packages = ['keyring', 'keyring.tests', 'keyring.util', 'keyring.backends'], ext_modules = get_extensions() )
Fix indentation error from conversion to spaces
import re from django.forms.widgets import MultiWidget, Select, NumberInput from . import ureg class QuantityWidget(MultiWidget): def get_choices(self, allowed_types=None): allowed_types = allowed_types or dir(ureg) return [(x, x) for x in allowed_types] def __init__(self, attrs=None, base_units=None, allowed_types=None): choices = self.get_choices(allowed_types) self.base_units = base_units attrs = attrs or {} attrs.setdefault('step', 'any') widgets = ( NumberInput(attrs=attrs), Select(attrs=attrs, choices=choices) ) super(QuantityWidget, self).__init__(widgets, attrs) def decompress(self, value): non_decimal = re.compile(r'[^\d.]+') if value: number_value = non_decimal.sub('', str(value)) return [number_value, self.base_units] return [None, self.base_units]
import re from django.forms.widgets import MultiWidget, Select, NumberInput from . import ureg class QuantityWidget(MultiWidget): def get_choices(self, allowed_types=None): allowed_types = allowed_types or dir(ureg) return [(x, x) for x in allowed_types] def __init__(self, attrs=None, base_units=None, allowed_types=None): choices = self.get_choices(allowed_types) self.base_units = base_units attrs = attrs or {} attrs.setdefault('step', 'any') widgets = ( NumberInput(attrs=attrs), Select(attrs=attrs, choices=choices) ) super(QuantityWidget, self).__init__(widgets, attrs) def decompress(self, value): non_decimal = re.compile(r'[^\d.]+') if value: number_value = non_decimal.sub('', str(value)) return [number_value, self.base_units] return [None, self.base_units]
Use match() in meteor methods to be able to use the "audit-argument-checks" MDG package
/*** * loggerSet - checks to see if the Logger object has been created on server * @returns {boolean} - return true if the Logger object has been created on server */ var loggerSet = function () { if (typeof Logger !== 'undefined' && Logger !== null) { return true; } console.log('Logger object was not created on the Meteor Server'); return false; }; Meteor.methods({ logglyLog: function(param, tag) { check(param,Object); check(tag,Match.Optional([String])); if (loggerSet()){ Logger.log(param, tag); } }, logglyTrace: function(param, tag) { check(param,Object); check(tag,Match.Optional([String])); if (loggerSet()){ Logger.trace(param, tag); } }, logglyInfo: function(param, tag) { check(param,Object); check(tag,Match.Optional([String])); if (loggerSet()){ Logger.info(param, tag); } }, logglyWarn: function(param, tag) { check(param,Object); check(tag,Match.Optional([String])); if (loggerSet()){ Logger.warn(param, tag); } }, logglyError: function(param, tag) { check(param,Object); check(tag,Match.Optional([String])); if (loggerSet()) { Logger.error(param, tag); } } });
/*** * loggerSet - checks to see if the Logger object has been created on server * @returns {boolean} - return true if the Logger object has been created on server */ var loggerSet = function () { if (typeof Logger !== 'undefined' && Logger !== null) { return true; } console.log('Logger object was not created on the Meteor Server'); return false; }; Meteor.methods({ logglyLog: function(param, tag) { if (loggerSet()){ Logger.log(param, tag); } }, logglyTrace: function(param, tag) { if (loggerSet()){ Logger.trace(param, tag); } }, logglyInfo: function(param, tag) { if (loggerSet()){ Logger.info(param, tag); } }, logglyWarn: function(param, tag) { if (loggerSet()){ Logger.warn(param, tag); } }, logglyError: function(param, tag) { if (loggerSet()) { Logger.error(param, tag); } } });
Add Hashtag mention type to comments
package com.creatubbles.api.model.comment; import android.support.annotation.NonNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Created by Janek on 20.12.2017. */ public enum MentionType { USER("user"), GROUP("group"), CREATION("creation"), GALLERY("gallery"), PARTNER_APPLICATION("partner_application"), HASHTAG("hashtag"), UNKNOWN("unknown"); private String typeName; MentionType(String typeName) { this.typeName = typeName; } @JsonValue @NonNull public String getTypeName() { return typeName; } @JsonCreator public static MentionType fromName(String typeName) { for (MentionType mentionType : MentionType.values()) { if (mentionType.getTypeName().equals(typeName)) { return mentionType; } } return UNKNOWN; } }
package com.creatubbles.api.model.comment; import android.support.annotation.NonNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.github.jasminb.jsonapi.annotations.Type; /** * Created by Janek on 20.12.2017. */ public enum MentionType { USER("user"), GROUP("group"), CREATION("creation"), GALLERY("gallery"), PARTNER_APPLICATION("partner_application"), UNKNOWN("unknown"); private String typeName; MentionType(String typeName) { this.typeName = typeName; } @JsonValue @NonNull public String getTypeName() { return typeName; } @JsonCreator public static MentionType fromName(String typeName) { for (MentionType mentionType : MentionType.values()) { if (mentionType.getTypeName().equals(typeName)) { return mentionType; } } return UNKNOWN; } }
Add options -l in deploy command
#!/usr/bin/env node const program = require('commander') const fs = require('fs') const path = require('path') const { deployCommand, modulesCommand } = require('../src/commands') const { ConfigService } = require('../src/services/config') const { FileService } = require('../src/services/file') const packageData = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'))) const optionsFilePath = packageData.config.optionsFilePath.replace('~', process.env.HOME) const configService = new ConfigService(optionsFilePath) const fileService = new FileService(configService) program .version(packageData.version) .description('Configuration modules manager.') program .command('list') .alias('l') .description('list all modules available.') .action(modulesCommand(fileService)) program .command('deploy [modules...]') .alias('d') .description('deploy configuration files.') .option('-l, --local', 'deploy only local files of the module(s) in the current folder') .action(deployCommand(fileService)) program.parse(process.argv)
#!/usr/bin/env node const program = require('commander') const fs = require('fs') const path = require('path') const { deployCommand, modulesCommand } = require('../src/commands') const { ConfigService } = require('../src/services/config') const { FileService } = require('../src/services/file') const packageData = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'))) const optionsFilePath = packageData.config.optionsFilePath.replace('~', process.env.HOME) const configService = new ConfigService(optionsFilePath) const fileService = new FileService(configService) program .version(packageData.version) .description('Configuration modules manager.') program .command('list') .alias('l') .description('list all modules available.') .action(modulesCommand(fileService)) program .command('deploy [modules...]') .alias('d') .description('deploy configuration files.') .action(deployCommand(fileService)) program.parse(process.argv)
Migrate with model from app state - Not from app code
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-10-16 20:22 from __future__ import unicode_literals from django.db import migrations OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(model, from_name, to_name): try: schema = model.objects.get(name=from_name) except model.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, OLD_NAME, NEW_NAME) def undo_aspredicted_rename(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-10-16 20:22 from __future__ import unicode_literals from django.db import migrations from osf.models import RegistrationSchema OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(from_name, to_name): try: schema = RegistrationSchema.objects.get(name=from_name) except RegistrationSchema.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(*args, **kwargs): return rename_schema(OLD_NAME, NEW_NAME) def undo_aspredicted_rename(*args, **kwargs): return rename_schema(NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
Remove custom `order` properties from dependencies
const nest = require('depnest') const { h, Value, when } = require('mutant') exports.gives = nest('app.html.menu') exports.needs = nest({ 'app.html.menuItem': 'map', 'app.sync.goTo': 'first', 'sbot.obs.connection': 'first' }) exports.create = function (api) { var _menu return nest('app.html.menu', function menu () { if (_menu) return _menu const hoverClass = Value('') const connectionClass = when(api.sbot.obs.connection, '', '-disconnected') const menuItems = api.app.html.menuItem(api.app.sync.goTo).map(item => { // Remove custom order from dependencies that give app.html.menuItem item.style.order = null return item }) const sortedMenuItems = Object.values(menuItems).sort((a, b) => a.text.localeCompare(b.text) ) // TODO: move goTo out into each menuItem _menu = h('Menu', { classList: [ hoverClass, connectionClass ], 'ev-mouseover': () => hoverClass.set('-open'), 'ev-mouseout': () => hoverClass.set('') }, [ h('div', sortedMenuItems) ]) return _menu }) }
const nest = require('depnest') const { h, Value, when } = require('mutant') exports.gives = nest('app.html.menu') exports.needs = nest({ 'app.html.menuItem': 'map', 'app.sync.goTo': 'first', 'sbot.obs.connection': 'first' }) exports.create = function (api) { var _menu return nest('app.html.menu', function menu () { if (_menu) return _menu const hoverClass = Value('') const connectionClass = when(api.sbot.obs.connection, '', '-disconnected') const menuItems = api.app.html.menuItem(api.app.sync.goTo) const sortedMenuItems = Object.values(menuItems).sort((a, b) => a.text.localeCompare(b.text) ) // TODO: move goTo out into each menuItem _menu = h('Menu', { classList: [ hoverClass, connectionClass ], 'ev-mouseover': () => hoverClass.set('-open'), 'ev-mouseout': () => hoverClass.set('') }, [ h('div', sortedMenuItems) ]) return _menu }) }
Remove redundant injection in header entry dirctive.
"use strict"; angular.module("hikeio"). directive("headerEntry", function() { return { scope: { align: "@", label: "@", url: "@" }, compile: function(tplElm, tplAttr) { // Include link only if url is included (otherwise, on some browsers it implies /) if (!tplAttr.url) { var link = tplElm.children()[0]; tplElm.empty(); tplElm.append(link.children); } }, template: "<a href='{{url}}'>" + "<div data-ng-style='{float:align}' >" + "<div class='header-separator' data-ng-show='align == \"right\"'></div>" + "<div class='header-entry' data-ng-transclude>" + "<span class='label' data-ng-show='label'>{{label}}</span>" + "</div>" + "<div class='header-separator' data-ng-show='align == \"left\"'></div>" + "</div>" + "</a>", transclude: true }; });
"use strict"; angular.module("hikeio"). directive("headerEntry", ["$document", function($document) { return { scope: { align: "@", label: "@", url: "@" }, compile: function(tplElm, tplAttr) { // Include link only if url is included (otherwise, on some browsers it implies /) if (!tplAttr.url) { var link = tplElm.children()[0]; tplElm.empty(); tplElm.append(link.children); } }, template: "<a href='{{url}}'>" + "<div data-ng-style='{float:align}' >" + "<div class='header-separator' data-ng-show='align == \"right\"'></div>" + "<div class='header-entry' data-ng-transclude>" + "<span class='label' data-ng-show='label'>{{label}}</span>" + "</div>" + "<div class='header-separator' data-ng-show='align == \"left\"'></div>" + "</div>" + "</a>", transclude: true }; }]);
Fix an issue where the port 9999 might be occupied thus the test fails. Now the test finds a garanteed emtpy port.
package com.groupon.seleniumgridextras.utilities; import org.junit.Test; import java.net.ConnectException; import java.net.ServerSocket; import java.net.URL; import java.net.UnknownHostException; import static org.junit.Assert.assertEquals; public class HttpUtilityTest { @Test(expected = ConnectException.class) public void testConnectionRefusedError() throws Exception { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket .close(); //Find a garanteed open port by taking one and closing. Why doesn't Java allow me to get a list of open ports? HttpUtility.getRequest(new URL("http://localhost:" + port)).getResponseCode(); } @Test public void test404Page() throws Exception { assertEquals(404, HttpUtility.getRequest(new URL("http://xkcd.com/404")).getResponseCode()); } @Test public void test200Page() throws Exception { assertEquals(200, HttpUtility.getRequest(new URL("http://google.com")).getResponseCode()); } @Test(expected = UnknownHostException.class) public void testUnknownHost() throws Exception { HttpUtility.getRequest(new URL("http://googasdfasfdkjashfdkjahsfdle.com/")).getResponseCode(); } @Test public void testGetAsString() throws Exception { assertEquals("", HttpUtility.getRequestAsString(new URL("http://xkcd.com/404"))); } }
package com.groupon.seleniumgridextras.utilities; import org.junit.Test; import java.net.ConnectException; import java.net.URL; import java.net.UnknownHostException; import static org.junit.Assert.assertEquals; /** * Created with IntelliJ IDEA. User: dima Date: 7/8/14 Time: 4:09 PM To change this template use * File | Settings | File Templates. */ public class HttpUtilityTest { @Test(expected=ConnectException.class) public void testConnectionRefusedError() throws Exception { HttpUtility.getRequest(new URL("http://localhost:9999")).getResponseCode(); } @Test public void test404Page() throws Exception { assertEquals(404, HttpUtility.getRequest(new URL("http://xkcd.com/404")).getResponseCode()); } @Test public void test200Page() throws Exception { assertEquals(200, HttpUtility.getRequest(new URL("http://google.com")).getResponseCode()); } @Test(expected = UnknownHostException.class) public void testUnknownHost() throws Exception { HttpUtility.getRequest(new URL("http://googasdfasfdkjashfdkjahsfdle.com/")).getResponseCode(); } @Test public void testGetAsString() throws Exception{ assertEquals("", HttpUtility.getRequestAsString(new URL("http://xkcd.com/404"))); } }
Make travis tests work with sites
""" Custom happening database manipulation. """ from django.contrib.sites.managers import CurrentSiteManager as Manager from django.db import models from django.contrib.sites.models import Site from multihost import sites import os class Model(models.Model): """ Custom model for use in happening. Ensures that models are owned by a particular site. """ class Meta: abstract = True site = models.ForeignKey(Site) objects = Manager() def save(self, *args, **kwargs): """ Ensure there is a site for this instance. """ if 'scdtest' in os.environ or 'travis' in os.environ: self.site = Site.objects.first() else: self.site = sites.by_host() return super(Model, self).save(*args, **kwargs)
""" Custom happening database manipulation. """ from django.contrib.sites.managers import CurrentSiteManager as Manager from django.db import models from django.contrib.sites.models import Site from multihost import sites import os class Model(models.Model): """ Custom model for use in happening. Ensures that models are owned by a particular site. """ class Meta: abstract = True site = models.ForeignKey(Site) objects = Manager() def save(self, *args, **kwargs): """ Ensure there is a site for this instance. """ if 'scdtest' in os.environ: self.site = Site.objects.first() else: self.site = sites.by_host() return super(Model, self).save(*args, **kwargs)
Create some shims for py3k
import os import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers': { 'voltron': { 'handlers': ['default'], 'level': 'INFO', 'propogate': True, } } } VOLTRON_DIR = os.path.expanduser('~/.voltron/') VOLTRON_CONFIG = os.path.join(VOLTRON_DIR, 'config') def configure_logging(): logging.config.dictConfig(LOG_CONFIG) log = logging.getLogger('voltron') return log # Python 3 shims if not hasattr(__builtins__, "xrange"): xrange = range
import os import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers': { 'voltron': { 'handlers': ['default'], 'level': 'INFO', 'propogate': True, } } } VOLTRON_DIR = os.path.expanduser('~/.voltron/') VOLTRON_CONFIG = os.path.join(VOLTRON_DIR, 'config') def configure_logging(): logging.config.dictConfig(LOG_CONFIG) log = logging.getLogger('voltron') return log
Validate issuer even if none in payload
<?php namespace Emarref\Jwt\Verification; use Emarref\Jwt\Claim; use Emarref\Jwt\Encoding; use Emarref\Jwt\Exception\VerificationException; use Emarref\Jwt\HeaderParameter; use Emarref\Jwt\Token; class IssuerVerifier implements VerifierInterface { /** * @var string */ private $issuer; /** * @param string $issuer */ public function __construct($issuer = null) { if (null !== $issuer && !is_string($issuer)) { throw new \InvalidArgumentException('Cannot verify invalid issuer value.'); } $this->issuer = $issuer; } /** * @param Token $token * @throws VerificationException */ public function verify(Token $token) { /** @var Claim\Issuer $issuerClaim */ $issuerClaim = $token->getPayload()->findClaimByName(Claim\Issuer::NAME); $issuer = (null === $issuerClaim) ? null : $issuerClaim->getValue(); if ($this->issuer !== $issuer) { throw new VerificationException('Issuer is invalid.'); } } }
<?php namespace Emarref\Jwt\Verification; use Emarref\Jwt\Claim; use Emarref\Jwt\Encoding; use Emarref\Jwt\Exception\VerificationException; use Emarref\Jwt\HeaderParameter; use Emarref\Jwt\Token; class IssuerVerifier implements VerifierInterface { /** * @var string */ private $issuer; /** * @param string $issuer */ public function __construct($issuer = null) { if (null !== $issuer && !is_string($issuer)) { throw new \InvalidArgumentException('Cannot verify invalid issuer value.'); } $this->issuer = $issuer; } /** * @param Token $token * @throws VerificationException */ public function verify(Token $token) { /** @var Claim\Issuer $issuerClaim */ $issuerClaim = $token->getPayload()->findClaimByName(Claim\Issuer::NAME); if (null === $issuerClaim) { return; } $issuer = $issuerClaim->getValue(); if ($this->issuer !== $issuer) { throw new VerificationException('Issuer is invalid.'); } } }
Change category from String to int
package com.xamoom.android.mapping; import com.xamoom.android.APICallback; import java.util.List; /** * Used for mapping menu responses from the xamoom-cloud-api. * Menu will have only a list of MenuItems. * * @author Raphael Seher * * @see MenuItem * @see com.xamoom.android.XamoomEndUserApi#getContentbyId(String, boolean, boolean, String, boolean, boolean, APICallback) * @see com.xamoom.android.XamoomEndUserApi#getContentByLocationIdentifier(String, String, boolean, boolean, String, APICallback) */ public class Menu { private List<MenuItem> items; @Override public String toString() { String output = "items: "; for (MenuItem item : items) { output += item.toString(); } return output; } public List<MenuItem> getItems() { return items; } }
package com.xamoom.android.mapping; import com.google.gson.annotations.SerializedName; import com.xamoom.android.APICallback; import com.xamoom.android.mapping.ContentBlocks.MenuItem; import java.util.List; /** * Used for mapping menu responses from the xamoom-cloud-api. * Menu will have only a list of MenuItems. * * @author Raphael Seher * * @see MenuItem * @see com.xamoom.android.XamoomEndUserApi#getContentbyIdFull(String, boolean, boolean, String, boolean, APICallback) * @see com.xamoom.android.XamoomEndUserApi#getContentByLocationIdentifier(String, String, boolean, boolean, String, APICallback) */ public class Menu { private List<MenuItem> items; @Override public String toString() { String output = "items: "; for (MenuItem item : items) { output += item.toString(); } return output; } public List<MenuItem> getItems() { return items; } }
Allow port to be passed in as argv
var express = require('express'); var RedisStore = require('connect-redis')(express); var routes = require('./routes'); var url = require('url'); var whiskers = require('whiskers'); var port = process.env.PORT || process.argv[2] || 8127; var redisUrl = process.env.REDISTOGO_URL && url.parse(process.env.REDISTOGO_URL); var redisOptions = redisUrl && { host: redisUrl.hostname, port: redisUrl.port, pass: redisUrl.auth.split(':')[1] }; var app = express(); app.engine('.html', whiskers.__express); app.set('views', __dirname + '/templates'); app.use('/api', express.query()); app.use(express.logger()); app.use(express.cookieParser('walrus')); app.use(express.session({ store: new RedisStore(redisOptions), secret: process.env.SECRET || 'walrus' })); app.use(app.router); app.use(express.staticCache()); app.use(express.static(__dirname + '/static', {maxAge: 86400000})); routes(app); app.listen(port); console.log('Running on port '+port);
var express = require('express'); var RedisStore = require('connect-redis')(express); var routes = require('./routes'); var url = require('url'); var whiskers = require('whiskers'); var port = process.env.PORT || 8127; var redisUrl = process.env.REDISTOGO_URL && url.parse(process.env.REDISTOGO_URL); var redisOptions = redisUrl && { host: redisUrl.hostname, port: redisUrl.port, pass: redisUrl.auth.split(':')[1] }; var app = express(); app.engine('.html', whiskers.__express); app.set('views', __dirname + '/templates'); app.use('/api', express.query()); app.use(express.logger()); app.use(express.cookieParser('walrus')); app.use(express.session({ store: new RedisStore(redisOptions), secret: process.env.SECRET || 'walrus' })); app.use(app.router); app.use(express.staticCache()); app.use(express.static(__dirname + '/static', {maxAge: 86400000})); routes(app); app.listen(port); console.log('Running on port '+port);
Move update/build script functionality to Vendor.
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Vendor\ComposerPackageReader; use Jivoo\Vendor\VendorLoader; use Jivoo\Vendor\VendorCommand; /** * Initializes the third-party library loading system. */ class VendorUnit extends UnitBase { /** * {@inheritdoc} */ public function run(App $app, Document $config) { $app->m->vendor = new VendorLoader($app); $vendor = $this->p('app/../vendor'); if (is_dir($vendor)) $app->m->vendor->addPath($vendor, new ComposerPackageReader()); $vendor = $this->p('share/vendor'); if (is_dir($vendor)) $app->m->vendor->addPath($vendor, new ComposerPackageReader()); $app->m->addProperty('vendor', $app->m->vendor); $this->m->lazy('shell')->addCommand('vendor', new VendorCommand($app)); } }
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Vendor\ComposerPackageReader; use Jivoo\Vendor\VendorLoader; /** * Initializes the third-party library loading system. */ class VendorUnit extends UnitBase { /** * {@inheritdoc} */ public function run(App $app, Document $config) { $app->m->vendor = new VendorLoader($app); $vendor = $this->p('app/../vendor'); if (is_dir($vendor)) $app->m->vendor->addPath($vendor, new ComposerPackageReader()); $vendor = $this->p('share/vendor'); if (is_dir($vendor)) $app->m->vendor->addPath($vendor, new ComposerPackageReader()); $app->m->addProperty('vendor', $app->m->vendor); } }
Add `user` parameter to differential.createrevision Summary: arc incorrectly passes a "user" parameter to differential.createrevision (long ago, we respected it, I think). After D4191 this fatals. Provide a stub call until the next version bump. Test Plan: inspection Reviewers: vrana, btrahan Reviewed By: btrahan CC: aran Differential Revision: https://secure.phabricator.com/D4220
<?php /** * @group conduit */ final class ConduitAPI_differential_createrevision_Method extends ConduitAPIMethod { public function getMethodDescription() { return "Create a new Differential revision."; } public function defineParamTypes() { return array( // TODO: Arcanist passes this; prevent fatals after D4191 until Conduit // version 7 or newer. 'user' => 'ignored', 'diffid' => 'required diffid', 'fields' => 'required dict', ); } public function defineReturnType() { return 'nonempty dict'; } public function defineErrorTypes() { return array( 'ERR_BAD_DIFF' => 'Bad diff ID.', ); } protected function execute(ConduitAPIRequest $request) { $fields = $request->getValue('fields'); $diff = id(new DifferentialDiff())->load($request->getValue('diffid')); if (!$diff) { throw new ConduitException('ERR_BAD_DIFF'); } $revision = DifferentialRevisionEditor::newRevisionFromConduitWithDiff( $fields, $diff, $request->getUser()); return array( 'revisionid' => $revision->getID(), 'uri' => PhabricatorEnv::getURI('/D'.$revision->getID()), ); } }
<?php /** * @group conduit */ final class ConduitAPI_differential_createrevision_Method extends ConduitAPIMethod { public function getMethodDescription() { return "Create a new Differential revision."; } public function defineParamTypes() { return array( 'diffid' => 'required diffid', 'fields' => 'required dict', ); } public function defineReturnType() { return 'nonempty dict'; } public function defineErrorTypes() { return array( 'ERR_BAD_DIFF' => 'Bad diff ID.', ); } protected function execute(ConduitAPIRequest $request) { $fields = $request->getValue('fields'); $diff = id(new DifferentialDiff())->load($request->getValue('diffid')); if (!$diff) { throw new ConduitException('ERR_BAD_DIFF'); } $revision = DifferentialRevisionEditor::newRevisionFromConduitWithDiff( $fields, $diff, $request->getUser()); return array( 'revisionid' => $revision->getID(), 'uri' => PhabricatorEnv::getURI('/D'.$revision->getID()), ); } }
Upgrade to JUnit 4.0: Fixing Vector -> List update consequences.
package com.intellij.rt.execution.junit2; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import java.util.Hashtable; public class RunOnce extends TestResult { private Hashtable myPeformedTests = new Hashtable(); private static final String NOT_ALLOWED_IN_ID = ":"; protected void run(TestCase test) { if (test.getClass().getName().startsWith(TestSuite.class.getName())) { super.run(test); } else { String testKey = keyOf(test); if (!myPeformedTests.containsKey(testKey)) { super.run(test); myPeformedTests.put(testKey, test); } else { fireTestSkipped(test, (Test)myPeformedTests.get(testKey)); } } } private void fireTestSkipped(TestCase test, Test peformedTest) { for (int i = 0; i < fListeners.size(); i++) { Object listener = fListeners.get(i); if (listener instanceof TestSkippingListener) { ((TestSkippingListener)listener).onTestSkipped(test, peformedTest); } } } private String keyOf(TestCase test) { return test.getClass().getName() + NOT_ALLOWED_IN_ID + test.getName() + NOT_ALLOWED_IN_ID + test.toString(); } }
package com.intellij.rt.execution.junit2; import junit.framework.TestResult; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.framework.Test; import java.util.Hashtable; import java.util.Enumeration; public class RunOnce extends TestResult { private Hashtable myPeformedTests = new Hashtable(); private static final String NOT_ALLOWED_IN_ID = ":"; protected void run(TestCase test) { if (test.getClass().getName().startsWith(TestSuite.class.getName())) { super.run(test); } else { String testKey = keyOf(test); if (!myPeformedTests.containsKey(testKey)) { super.run(test); myPeformedTests.put(testKey, test); } else { fireTestSkipped(test, (Test)myPeformedTests.get(testKey)); } } } private void fireTestSkipped(TestCase test, Test peformedTest) { for (Enumeration each = fListeners.elements(); each.hasMoreElements();) { Object listener = each.nextElement(); if (listener instanceof TestSkippingListener) ((TestSkippingListener)listener).onTestSkipped(test, peformedTest); } } private String keyOf(TestCase test) { return test.getClass().getName() + NOT_ALLOWED_IN_ID + test.getName() + NOT_ALLOWED_IN_ID + test.toString(); } }
Switch base generator to es6
const Base = require('yeoman-generator').Base; var generators = require('yeoman-generator'); class BaseGenerator extends Base { prompting() { return this.prompt([{ type : 'input', name : 'appName', message : 'Your react native app directory name', default : 'example', }]).then((answers) => { this.answers = answers; }); } install() { this.npmInstall([ 'react-native-router-flux', ], { saveExact: true }); } writing() { this.fs.copyTpl( this.templatePath('**/*.js'), this.destinationPath(''), this.answers ); this.fs.copy( this.templatePath('src/assets/*'), this.destinationPath('src/assets') ); } } module.exports = BaseGenerator;
var generators = require('yeoman-generator'); module.exports = generators.Base.extend({ prompting: function() { return this.prompt([{ type : 'input', name : 'appName', message : 'Your react native app directory name', default : 'example', }]).then(function (answers) { this.answers = answers; }.bind(this)); }, install: function () { this.npmInstall([ 'react-native-router-flux', ], { saveExact: true }); }, writing: function () { this.fs.copyTpl( this.templatePath('**/*.js'), this.destinationPath(''), this.answers ); this.fs.copy( this.templatePath('src/assets/*'), this.destinationPath('src/assets') ); }, });
Change explanation field type to text to allow long explanations.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTriosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('trios', function (Blueprint $table) { $table->increments('id'); $table->string('sentence1'); $table->string('sentence2'); $table->string('sentence3'); $table->text('explanation1'); $table->text('explanation2'); $table->text('explanation3'); $table->string('answer'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('trios'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTriosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('trios', function (Blueprint $table) { $table->increments('id'); $table->string('sentence1'); $table->string('sentence2'); $table->string('sentence3'); $table->string('explanation1'); $table->string('explanation2'); $table->string('explanation3'); $table->string('answer'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('trios'); } }
Raise PluginErrors instead of ValueErrors in versions.
from unleash.exc import PluginError import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for which an assignment should be found. """ ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) if len(ASSIGN_RE.findall(data)) > 1: raise PluginError('Found multiple {}-strings.'.format(varname)) if len(ASSIGN_RE.findall(data)) < 1: raise PluginError('No version assignment ("{}") found.' .format(varname)) return ASSIGN_RE.search(data).group(2) def replace_assign(data, varname, new_value): ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) def repl(m): return m.group(1) + new_value + m.group(3) return ASSIGN_RE.sub(repl, data)
import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for which an assignment should be found. """ ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) if len(ASSIGN_RE.findall(data)) > 1: raise ValueError('Found multiple {}-strings.'.format(varname)) if len(ASSIGN_RE.findall(data)) < 1: raise ValueError('No version assignment ("{}") found.'.format(varname)) return ASSIGN_RE.search(data).group(2) def replace_assign(data, varname, new_value): ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) def repl(m): return m.group(1) + new_value + m.group(3) return ASSIGN_RE.sub(repl, data)
Add organizations link in navbar
import React, { Component } from 'react' import { connect } from 'react-redux' import { Nav, NavItem } from 'react-bootstrap' import { Navbar as NavbarReactBootstrap } from 'react-bootstrap' import LoginButton from './LoginButton' import LogoutButton from './LogoutButton' import { getIsAuthenticated } from '../selectors/user' class Navbar extends Component { render() { return ( <NavbarReactBootstrap> <NavbarReactBootstrap.Header> <NavbarReactBootstrap.Brand> <a href="#">Choir Master</a> </NavbarReactBootstrap.Brand> </NavbarReactBootstrap.Header> <Nav> <NavItem eventKey={1} href="#/dashboard">Organizations</NavItem> </Nav> <NavbarReactBootstrap.Collapse> <NavbarReactBootstrap.Form pullRight> {this.props.isAuthenticated ? <LogoutButton /> : <LoginButton />} </NavbarReactBootstrap.Form> </NavbarReactBootstrap.Collapse> </NavbarReactBootstrap> ); } } export default connect( state => ({ isAuthenticated: getIsAuthenticated(state) }) )(Navbar);
import React, { Component } from 'react' import { connect } from 'react-redux' import LoginButton from './LoginButton' import LogoutButton from './LogoutButton' import { getIsAuthenticated } from '../selectors/user' class Navbar extends Component { render() { return ( <nav className='navbar navbar-default'> <div className='container-fluid'> <a className="navbar-brand" href="#">Choir Master</a> <div className='navbar-form'> {this.props.isAuthenticated ? <LogoutButton /> : <LoginButton />} </div> </div> </nav> ); } } export default connect( state => ({ isAuthenticated: getIsAuthenticated(state) }) )(Navbar);
Make sure to start the timer after you display the GUI. Otherwise you'll get a blocked thread.
package edu.pdx.cs410G.swing; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.*; /** * This program demonstrates a Swing {@link Timer} that periodically * updates a {@link JTextField} with the current time. */ public class TimerExample extends JPanel { private final Timer timer; public TimerExample() { this.setLayout(new BorderLayout()); final JTextField text = new JTextField(20); text.setEditable(false); this.add(BorderLayout.CENTER, text); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { text.setText(new Date().toString()); } }; this.timer = new Timer(1000, listener); this.timer.setInitialDelay(0); } public static void main(String[] args) { JFrame frame = new JFrame("A Timer"); TimerExample example = new TimerExample(); frame.getContentPane().add(example); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); // Start timer after GUI is visible example.timer.start(); } }
package edu.pdx.cs410G.swing; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.*; /** * This program demonstrates a Swing {@link Timer} that periodically * updates a {@link JTextField} with the current time. */ public class TimerExample extends JPanel { public TimerExample() { this.setLayout(new BorderLayout()); final JTextField text = new JTextField(20); text.setEditable(false); this.add(BorderLayout.CENTER, text); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { text.setText(new Date().toString()); } }; Timer timer = new Timer(1000, listener); timer.setInitialDelay(0); timer.start(); } public static void main(String[] args) { JFrame frame = new JFrame("A Timer"); JPanel panel = new TimerExample(); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
PRJ: Increase version 3.1.1 -> 3.1.2
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.1.2' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.1.1' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
Remove all reference to molfiles plugins
# -* coding: utf-8 -* import os from ctypes import cdll from ctypes.util import find_library from chemfiles import ffi ROOT = os.path.dirname(__file__) def load_clib(): '''Load chemfiles C++ library''' libpath = find_library("chemfiles") if not libpath: # Rely on the library built by the setup.py function libpath = os.path.join(ROOT, "_chemfiles.so") try: return cdll.LoadLibrary(libpath) except OSError: raise ImportError( "Could not find chemfiles library. Are you sure it's installed?" ) class ChemfilesLibrary(object): def __init__(self): self._cache = None def __call__(self): if self._cache is None: self._cache = load_clib() ffi.set_interface(self._cache) return self._cache
# -* coding: utf-8 -* import os from ctypes import cdll from ctypes.util import find_library from chemfiles import ffi ROOT = os.path.dirname(__file__) def load_clib(): ''' Load chemfiles C++ library, and set the environment as needed. ''' os.environ['CHEMFILES_PLUGINS'] = os.path.join(ROOT, "molfiles") libpath = find_library("chemfiles") if not libpath: # Rely on the library built by the setup.py function libpath = os.path.join(ROOT, "_chemfiles.so") try: return cdll.LoadLibrary(libpath) except OSError: # We could not find chemfiles ... raise ImportError("Could not find the chemfiles library. " + "Are you sure it is installed?") class ChemfilesLibrary(object): def __init__(self): self._cache = None def __call__(self): if self._cache is None: self._cache = load_clib() ffi.set_interface(self._cache) return self._cache
Add doc comment on ErrNotFound and User
package petfind import ( "errors" "time" ) // ErrNotFound is returned whenever an item does not exist in the Store. var ErrNotFound = errors.New("item not found") // Pet holds information about each pet of the application. type Pet struct { ID int64 Name string Age int Added time.Time } // Store describes the operations the application needs for persisting and // retrieving data. type Store interface { AddPet(*Pet) error GetAllPets() ([]Pet, error) CreateUser(*User) error GetUser(userID int64) (*User, error) GetUserByGithubID(githubID int64) (*User, error) GetUserBySessionID(sessionID string) (*User, error) MakeSchema() error DropSchema() error } // User holds information about a user that is signed in the application. type User struct { ID int64 GithubID int64 Login string Name string Email string Added time.Time } // TODO(psimika): Useful article in case a custom type needs to be stored in // the database: // // https://husobee.github.io/golang/database/2015/06/12/scanner-valuer.html
package petfind import ( "errors" "time" ) var ErrNotFound = errors.New("item not found") // Pet holds information about each pet of the application. type Pet struct { ID int64 Name string Age int Added time.Time } // Store describes the operations the application needs for persisting and // retrieving data. type Store interface { AddPet(*Pet) error GetAllPets() ([]Pet, error) CreateUser(*User) error GetUser(userID int64) (*User, error) GetUserByGithubID(githubID int64) (*User, error) GetUserBySessionID(sessionID string) (*User, error) MakeSchema() error DropSchema() error } type User struct { ID int64 GithubID int64 Login string Name string Email string Added time.Time } // TODO(psimika): Useful article in case a custom type needs to be stored in // the database: // // https://husobee.github.io/golang/database/2015/06/12/scanner-valuer.html
Update for Django version 1.11
""" Contains some common filter as utilities """ from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(c) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
""" Contains some common filter as utilities """ from django.template import Library, loader, Context from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(Context(c)) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
Correct reference to ScrollingBehaviour source files.
//= require_directory ./AbstractDocument //= require_directory ./BrowserWidget //= require_directory ./ComponentStateManager //= require_directory ./Desktop //= require_directory ./DiagramWidget //= require_directory ./DocumentEditor //= require_directory ./EventWidget //= require_directory ./FundamentalTypes //= require_directory ./HierarchicalMenuWidget //= require_directory ./HtmlDocument //= require_directory ./Internationalization //= require_directory ./jStorage //= require_directory ./LanguageSelectorWidget //= require_directory ./NewsReaderWidget //= require_directory ./PhotoGaleryWidget //= require_directory ./ResourceManager //= require_directory ./ScrollingBehaviour //= require_directory ./Singleton //= require_directory ./SkinSelectorWidget //= require_directory ./SmartDocument //= require_directory ./SplashForm //= require_directory ./TabWidget //= require_directory ./TextAreaEditor //= require_directory ./ToolBarWidget //= require_directory ./VideoPlayerWidget //= require_directory ./WebUIConfiguration //= require_directory ./WebUIController //= require_directory ./WebUILogger //= require_directory ./WebUIMessageBus
//= require_directory ./AbstractDocument //= require_directory ./BrowserWidget //= require_directory ./ComponentStateManager //= require_directory ./Desktop //= require_directory ./DiagramWidget //= require_directory ./DocumentEditor //= require_directory ./EventWidget //= require_directory ./FundamentalTypes //= require_directory ./HierarchicalMenuWidget //= require_directory ./HtmlDocument //= require_directory ./Internationalization //= require_directory ./jStorage //= require_directory ./LanguageSelectorWidget //= require_directory ./NewsReaderWidget //= require_directory ./PhotoGaleryWidget //= require_directory ./ResourceManager //= require_directory ./ScrollBar //= require_directory ./Singleton //= require_directory ./SkinSelectorWidget //= require_directory ./SmartDocument //= require_directory ./SplashForm //= require_directory ./TabWidget //= require_directory ./TextAreaEditor //= require_directory ./ToolBarWidget //= require_directory ./VideoPlayerWidget //= require_directory ./WebUIConfiguration //= require_directory ./WebUIController //= require_directory ./WebUILogger //= require_directory ./WebUIMessageBus
Improve the specs for Feature.search()
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length); var doc = docs[0]; assert.equal('add files', doc.name); assert.deepEqual({ Git: 'git add', Mercurial: 'hg add', Subversion: 'svn add' }, doc.examples); done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
Sort parameters and cast to int
<?php /** * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\Route; class CachingRouter extends Router { /** * @var \OCP\ICache */ protected $cache; /** * @param \OCP\ICache $cache */ public function __construct($cache) { $this->cache = $cache; parent::__construct(); } /** * Generate url based on $name and $parameters * * @param string $name Name of the route to use. * @param array $parameters Parameters for the route * @param bool $absolute * @return string */ public function generate($name, $parameters = array(), $absolute = false) { sort($parameters); $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . json_encode($parameters) . intval($absolute); if ($this->cache->hasKey($key)) { return $this->cache->get($key); } else { $url = parent::generate($name, $parameters, $absolute); $this->cache->set($key, $url, 3600); return $url; } } }
<?php /** * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\Route; class CachingRouter extends Router { /** * @var \OCP\ICache */ protected $cache; /** * @param \OCP\ICache $cache */ public function __construct($cache) { $this->cache = $cache; parent::__construct(); } /** * Generate url based on $name and $parameters * * @param string $name Name of the route to use. * @param array $parameters Parameters for the route * @param bool $absolute * @return string */ public function generate($name, $parameters = array(), $absolute = false) { $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . json_encode($parameters) . $absolute; if ($this->cache->hasKey($key)) { return $this->cache->get($key); } else { $url = parent::generate($name, $parameters, $absolute); $this->cache->set($key, $url, 3600); return $url; } } }
Fix calling pathway commons client in biopax api
import sys from processor import BiopaxProcessor from indra.java_vm import autoclass, JavaException from indra.biopax import pathway_commons_client as pcc def process_pc_neighborhood(gene_names, neighbor_limit=1): model = pcc.graph_query('neighborhood', gene_names, neighbor_limit=neighbor_limit) if model is not None: return process_model(model) def process_pc_pathsbetween(gene_names, neighbor_limit=1): model = pcc.graph_query('pathsbetween', gene_names, neighbor_limit=neighbor_limit) if model is not None: return process_model(model) def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1): model = pcc.graph_query('pathsfromto', source_genes, target_genes, neighbor_limit) if model is not None: return process_model(model) def process_owl(owl_filename): model = pcc.owl_to_model(owl_filename) return process_model(model) def process_model(model): bproc = BiopaxProcessor(model) # bproc.get_complexes() # bproc.get_phosphorylation() # bproc.print_statements() return bproc if __name__ == '__main__': pass
import sys from processor import BiopaxProcessor from indra.java_vm import autoclass, JavaException from indra.biopax import pathway_commons_client as pcc def process_pc_neighborhood(gene_names, neighbor_limit=1): model = pcc.graph_query('neighborhood', gene_names, neighbor_limit=neighbor_limit) if model is not None: return process_model(model) def process_pc_pathsbetween(gene_names, neighbor_limit=1): model = pcc.graph_query('pathsbetween', gene_names, neighbor_limit=neighbor_limit) if model is not None: return process_model(model) def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1): model = pcc.run_pc_query('pathsfromto', source_genes, target_genes, neighbor_limit) if model is not None: return process_model(model) def process_owl(owl_filename): model = pcc.owl_to_model(owl_filename) return process_model(model) def process_model(model): bproc = BiopaxProcessor(model) # bproc.get_complexes() # bproc.get_phosphorylation() # bproc.print_statements() return bproc if __name__ == '__main__': pass
USe tox as test package and added python 3.7 to classifiers
# *-* coding:utf-8 *-* from setuptools import setup setup(name='ie', version='1.0.8', description='Validation of brazilian state registration numbers', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='inscrição estadual inscricao estadual inscricoes estaduais inscrições estaduais validacao validação', url='https://github.com/matheuscas/pyIE', author='Matheus Cardoso', author_email='matheus.mcas@gmail.com', license='MIT', packages=['ie'], tests_require=['tox'], zip_safe=False)
# *-* coding:utf-8 *-* from setuptools import setup setup(name='ie', version='1.0.8', description='Validation of brazilian state registration numbers', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='inscrição estadual inscricao estadual inscricoes estaduais inscrições estaduais validacao validação', url='https://github.com/matheuscas/pyIE', author='Matheus Cardoso', author_email='matheus.mcas@gmail.com', license='MIT', packages=['ie'], test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
Fix mock statement for new API
from io import BytesIO from unittest.mock import MagicMock, patch from isort import hooks def test_git_hook(): """Simple smoke level testing of git hooks""" # Ensure correct subprocess command is called with patch("subprocess.run", MagicMock()) as run_mock: hooks.git_hook() assert run_mock.called_with( ["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"] ) # Test with incorrectly sorted file returned from git with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock: class FakeProecssResponse(object): stdout = b"import b\nimport a" with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock: with patch("isort.hooks.api", MagicMock()): hooks.git_hook(modify=True)
from io import BytesIO from unittest.mock import MagicMock, patch from isort import hooks def test_git_hook(): """Simple smoke level testing of git hooks""" # Ensure correct subprocess command is called with patch("subprocess.run", MagicMock()) as run_mock: hooks.git_hook() assert run_mock.called_with( ["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"] ) # Test with incorrectly sorted file returned from git with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock: class FakeProecssResponse(object): stdout = b"import b\nimport a" with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock: with patch("isort.hooks.SortImports", MagicMock()): hooks.git_hook(modify=True)
Use the correct variable for ContainerPreference names
import ContextualIdentities from '../ContextualIdentity'; import PreferenceGroup from './PreferenceGroup'; import ContainerPreference from './ContainerPreference'; /** * Contains a @see{ContainerPreference} for each existing container */ export default class ContainerPreferenceGroup extends PreferenceGroup { constructor({name, label, description}) { super({name, label, description, preferences: [], toggleable: false}); } async fillContainer() { // Get all existing containers and create ContainerPref this._preferences = (await ContextualIdentities.get()) .map((container) => { return new ContainerPreference({ name: `${this.name}.${container.cookieStoreId}`, label: container.name, }); }); return super.fillContainer(); } async updateFromDb() { return Promise.all(this._preferences.map((preference) => preference.updateFromDb())); } } ContainerPreferenceGroup.TYPE = 'containers';
import ContextualIdentities from '../ContextualIdentity'; import PreferenceGroup from './PreferenceGroup'; import ContainerPreference from './ContainerPreference'; /** * Contains a @see{ContainerPreference} for each existing container */ export default class ContainerPreferenceGroup extends PreferenceGroup { constructor({name, label, description}) { super({name, label, description, preferences: [], toggleable: false}); } async fillContainer() { // Get all existing containers and create ContainerPref this._preferences = (await ContextualIdentities.get()) .map((container) => { return new ContainerPreference({ name: container.cookieStoreId, label: container.name, }); }); return super.fillContainer(); } async updateFromDb() { return Promise.all(this._preferences.map((preference) => preference.updateFromDb())); } } ContainerPreferenceGroup.TYPE = 'containers';
Create somewhat questionable sql function
from os.path import abspath, dirname, join import sh import psycopg2 import requests PROJECT_FOLDER=dirname(dirname(abspath(__file__))) DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker') def docker_compose(version, *args): sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args) def test_pg(): def callback(cursor): cursor.execute('select 1 + 1;') return cursor.fetchone()[0] == 2 def error(): return False return sql(callback, error) def test_es(): try: return requests.get('http://localhost:9200').json()['tagline'] == 'You Know, for Search' except Exception: return False def sql(callback, error): try: with psycopg2.connect(host='localhost', port=5432, user='postgres', dbname='postgres') as conn: with conn.cursor() as cursor: return callback(cursor) except Exception: return error()
from os.path import abspath, dirname, join import sh import psycopg2 import requests PROJECT_FOLDER=dirname(dirname(abspath(__file__))) DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker') def docker_compose(version, *args): sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args) def test_pg(): try: with psycopg2.connect(host='localhost', port=5432, user='postgres', dbname='postgres') as conn: with conn.cursor() as cursor: cursor.execute('select 1 + 1;') return cursor.fetchone()[0] == 2 except Exception: return False def test_es(): try: return requests.get('http://localhost:9200').json()['tagline'] == 'You Know, for Search' except Exception: return False
Change graph_type for chart_type and remove it from context
# -*- coding: utf-8 -*- from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' chart_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.chart_type + ".html" return url
# -*- coding: utf-8 -*- from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' graph_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["graph_type"] = self.graph_type context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.graph_type + ".html" return url
Fix url fields when no value is set
from __future__ import unicode_literals from urlparse import urlparse from django.contrib.admin.widgets import AdminURLFieldWidget from django.forms.widgets import CheckboxFieldRenderer, CheckboxSelectMultiple, CheckboxChoiceInput from django.utils.html import format_html class NiceCheckboxChoiceInput(CheckboxChoiceInput): def render(self, name=None, value=None, attrs=None): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs return format_html( '{} <label{}>{}</label>', self.tag(attrs), label_for, self.choice_label ) def is_checked(self): return self.choice_value in self.value class MultiCheckboxRenderer(CheckboxFieldRenderer): choice_input_class = NiceCheckboxChoiceInput class CheckboxSelectMultipleWidget(CheckboxSelectMultiple): renderer = MultiCheckboxRenderer class SecureAdminURLFieldWidget(AdminURLFieldWidget): def render(self, name, value, attrs=None): if value and urlparse(value).scheme not in ('http', 'https', ): return super(AdminURLFieldWidget, self).render(name, value, attrs) else: return super(SecureAdminURLFieldWidget, self).render(name, value, attrs)
from __future__ import unicode_literals from urlparse import urlparse from django.contrib.admin.widgets import AdminURLFieldWidget from django.forms.widgets import CheckboxFieldRenderer, CheckboxSelectMultiple, CheckboxChoiceInput from django.utils.html import format_html class NiceCheckboxChoiceInput(CheckboxChoiceInput): def render(self, name=None, value=None, attrs=None): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs return format_html( '{} <label{}>{}</label>', self.tag(attrs), label_for, self.choice_label ) def is_checked(self): return self.choice_value in self.value class MultiCheckboxRenderer(CheckboxFieldRenderer): choice_input_class = NiceCheckboxChoiceInput class CheckboxSelectMultipleWidget(CheckboxSelectMultiple): renderer = MultiCheckboxRenderer class SecureAdminURLFieldWidget(AdminURLFieldWidget): def render(self, name, value, attrs=None): if urlparse(value).scheme not in ('http', 'https', ): return super(AdminURLFieldWidget, self).render(name, value, attrs) else: return super(SecureAdminURLFieldWidget, self).render(name, value, attrs)
Add more test coverage for Redis Checkpoint
package redis import ( "testing" ) func Test_CheckpointLifecycle(t *testing.T) { // new c, err := New("app") if err != nil { t.Fatalf("new checkpoint error: %v", err) } // set c.Set("streamName", "shardID", "testSeqNum") // get val, err := c.Get("streamName", "shardID") if err != nil { t.Fatalf("get checkpoint error: %v", err) } if val != "testSeqNum" { t.Fatalf("checkpoint exists expected %s, got %s", "testSeqNum", val) } } func Test_SetEmptySeqNum(t *testing.T) { c, err := New("app") if err != nil { t.Fatalf("new checkpoint error: %v", err) } err = c.Set("streamName", "shardID", "") if err == nil { t.Fatalf("should not allow empty sequence number") } } func Test_key(t *testing.T) { c, err := New("app") if err != nil { t.Fatalf("new checkpoint error: %v", err) } want := "app:checkpoint:stream:shard" if got := c.key("stream", "shard"); got != want { t.Fatalf("checkpoint key, want %s, got %s", want, got) } }
package redis import ( "testing" "gopkg.in/redis.v5" ) var defaultAddr = "127.0.0.1:6379" func Test_CheckpointLifecycle(t *testing.T) { client := redis.NewClient(&redis.Options{Addr: defaultAddr}) c := &Checkpoint{ appName: "app", client: client, } // set checkpoint c.Set("streamName", "shardID", "testSeqNum") // get checkpoint val, err := c.Get("streamName", "shardID") if err != nil { t.Fatalf("get checkpoint error: %v", err) } if val != "testSeqNum" { t.Fatalf("checkpoint exists expected %s, got %s", "testSeqNum", val) } client.Del(c.key("streamName", "shardID")) } func Test_key(t *testing.T) { client := redis.NewClient(&redis.Options{Addr: defaultAddr}) c := &Checkpoint{ appName: "app", client: client, } expected := "app:checkpoint:stream:shard" if val := c.key("stream", "shard"); val != expected { t.Fatalf("checkpoint exists expected %s, got %s", expected, val) } }
Fix script for repos with binaries
#!/usr/bin/env python # get-pmstats.py # Henry J Schmale # November 25, 2017 # # Calculates the additions and deletions per day within a git repository # by parsing out the git log. It opens the log itself. # Produces output as a CSV import subprocess from datetime import datetime def chomp_int(val): try: return int(val) except ValueError: return 0 changes_by_date = {} git_log = subprocess.Popen( 'git log --numstat --pretty="%at"', stdout=subprocess.PIPE, shell=True) date = None day_changes = [0, 0] for line in git_log.stdout: args = line.rstrip().split() if len(args) == 1: old_date = date date = datetime.fromtimestamp(int(args[0])) if day_changes != [0, 0] and date.date() != old_date.date(): changes_by_date[str(date.date())] = day_changes day_changes = [0, 0] elif len(args) >= 3: day_changes = [sum(x) for x in zip(day_changes, map(chomp_int, args[0:2]))] print('date,ins,del') for key,vals in changes_by_date.items(): print(','.join(map(str, [key, vals[0], vals[1]])))
#!/usr/bin/env python # get-pmstats.py # Henry J Schmale # November 25, 2017 # # Calculates the additions and deletions per day within a git repository # by parsing out the git log. It opens the log itself. # Produces output as a CSV import subprocess from datetime import datetime changes_by_date = {} git_log = subprocess.Popen( 'git log --numstat --pretty="%at"', stdout=subprocess.PIPE, shell=True) date = None day_changes = [0, 0] for line in git_log.stdout: args = line.rstrip().split() if len(args) == 1: old_date = date date = datetime.fromtimestamp(int(args[0])) if day_changes != [0, 0] and date.date() != old_date.date(): changes_by_date[str(date.date())] = day_changes day_changes = [0, 0] elif len(args) >= 3: day_changes = [sum(x) for x in zip(day_changes, map(int, args[0:2]))] print('date,ins,del') for key,vals in changes_by_date.items(): print(','.join(map(str, [key, vals[0], vals[1]])))
Fix some grunt / linting issues
'use strict'; angular.module('core').controller('HeaderController', ['$scope', '$state', 'Authentication', 'Menus', function ($scope, $state, Authentication, Menus) { // Expose view variables $scope.$state = $state; $scope.authentication = Authentication; // Get the topbar menu $scope.menu = document.getElementById('side-menu'); // Toggle the menu items $scope.isCollapsed = false; $scope.toggleCollapsibleMenu = function () { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function () { $scope.isCollapsed = false; }); $scope.toggleMenu = function() { if ($scope.menu.style.left === '-200px') { $scope.menu.style.left = '0px'; } else { $scope.menu.style.left = '-200px'; } }; $scope.closeMenu = function() { $scope.menu.style.left = '-200px'; }; } ]);
'use strict'; angular.module('core').controller('HeaderController', ['$scope', '$state', 'Authentication', 'Menus', function ($scope, $state, Authentication, Menus) { // Expose view variables $scope.$state = $state; $scope.authentication = Authentication; // Get the topbar menu $scope.menu = document.getElementById("side-menu"); // Toggle the menu items $scope.isCollapsed = false; $scope.toggleCollapsibleMenu = function () { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function () { $scope.isCollapsed = false; }); $scope.toggleMenu = function() { if ($scope.menu.style.left === "-200px") { $scope.menu.style.left = "0px"; } else { $scope.menu.style.left = "-200px"; } }; $scope.closeMenu = function() { $scope.menu.style.left = "-200px"; } } ]);
Fix bug with moving up and down
import React, {Component, PropTypes} from 'react'; import t from 'tcomb-form'; function renderInput(locals) { const onChange = function (event) { locals.onChange(event.target.value); }; const triggerRealInputChange = function (event) { locals.onChange(document.getElementById('virtual-keyboard-helper-' + locals.attrs.name).value); }; return <div> <input type="text" label={locals.label} name={locals.attrs.name} value={locals.value} onChange={onChange} style={{display: 'none'}} /> <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} value={locals.value} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> </div>; } const textboxTemplate = t.form.Form.templates.textbox.clone({ renderInput }) export default class VirtualKeyboardFactory extends t.form.Textbox { getTemplate() { return textboxTemplate } }
import React, {Component, PropTypes} from 'react'; import t from 'tcomb-form'; function renderInput(locals) { const onChange = function (event) { locals.onChange(event.target.value); }; const triggerRealInputChange = function (event) { locals.onChange(document.getElementById('virtual-keyboard-helper-' + locals.attrs.name).value); }; return <div> <input type="text" label={locals.label} name={locals.attrs.name} value={locals.value} onChange={onChange} style={{display: 'none'}} /> <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> </div>; } const textboxTemplate = t.form.Form.templates.textbox.clone({ renderInput }) export default class VirtualKeyboardFactory extends t.form.Textbox { getTemplate() { return textboxTemplate } }
Remove redirect to avoid Chrome privacy error
from flask import Flask, render_template, request, redirect import requests import pandas as pd from datetime import datetime from bokeh.plotting import figure, output_notebook, output_file, save app = Flask(__name__) # @app.route('/') # def main(): # return redirect('/index') @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': return render_template('index.html') else: pitcher = request.form['pitcher'] image_file = pitcher.lower() image_file = image_file.split() image_file = '_'.join(image_file) + '.png' return render_template('results.html', image_file = image_file) if __name__ == '__main__': app.run(port=33508)
from flask import Flask, render_template, request, redirect import requests import pandas as pd from datetime import datetime from bokeh.plotting import figure, output_notebook, output_file, save app = Flask(__name__) @app.route('/') def main(): return redirect('/index') @app.route('/index', methods=['GET', 'POST']) def index(): if request.method == 'GET': return render_template('index.html') else: pitcher = request.form['pitcher'] image_file = pitcher.lower() image_file = image_file.split() image_file = '_'.join(image_file) + '.png' return render_template('results.html', image_file = image_file) if __name__ == '__main__': app.run(port=33508)
Increase iteration time a bit
package forager.client; import java.io.IOException; public class StatusMonitor implements Runnable { int maxActive = 4; boolean online; private Forager forager; public StatusMonitor(Forager forager) { this.forager = forager; } public void run() { online = true; while (online) { int active = forager.getActiveCount(); if (active < maxActive) { int numTasks = maxActive - active; try { forager.submitTaskRequest(numTasks); } catch (IOException e) { System.out.println("Failed to submit task request!"); e.printStackTrace(); } } try { Thread.sleep(10000); } catch (InterruptedException e) { } } } }
package forager.client; import java.io.IOException; public class StatusMonitor implements Runnable { int maxActive = 4; boolean online; private Forager forager; public StatusMonitor(Forager forager) { this.forager = forager; } public void run() { online = true; while (online) { int active = forager.getActiveCount(); if (active < maxActive) { int numTasks = maxActive - active; try { forager.submitTaskRequest(numTasks); } catch (IOException e) { System.out.println("Failed to submit task request!"); e.printStackTrace(); } } try { Thread.sleep(5000); } catch (InterruptedException e) { } } } }
Change use br to asynchronous testing
'use strict'; var fs = require('fs'); var utility = require('../utility'); describe('use br', function() { before(function(done) { var filename = utility.buildPath('expect', 'useBr.txt'), testHTML = document.querySelectorAll('#use-br .hljs'); fs.readFile(filename, 'utf-8', utility.handleSetup(this, testHTML, done)); }); it('should respect <br> tags', function() { var actual = this.blocks[0]; actual.should.equal(this.expected); }); it('should ignore literal new lines', function() { var actual = this.blocks[1]; actual.should.equal(this.expected); }); it('should recognize xml-style <br/>', function() { var actual = this.blocks[2]; actual.should.equal(this.expected); }); });
'use strict'; var _ = require('lodash'); var fs = require('fs'); var utility = require('../utility'); describe('use br', function() { before(function() { var filename = utility.buildPath('expect', 'useBr.txt'), testHTML = document.querySelectorAll('#use-br .hljs'); this.expected = fs.readFileSync(filename, 'utf-8').trim(); this.blocks = _.map(testHTML, 'innerHTML'); }); it('should respect <br> tags', function() { var actual = this.blocks[0]; actual.should.equal(this.expected); }); it('should ignore literal new lines', function() { var actual = this.blocks[1]; actual.should.equal(this.expected); }); it('should recognize xml-style <br/>', function() { var actual = this.blocks[2]; actual.should.equal(this.expected); }); });
Add /api/ in front of API-URLs
/** * Created by Stein-Otto Svorstøl on 26.08.15. */ 'use strict'; var bookController = require('./controllers/bookController'); function setup(app){ var bodyParser = require('body-parser'); // Some setup for encoding of requests app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use(function(req, res, next) { // Headers to allow CORS and different requests res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.put('/api/book', bookController.createNew); app.get('/api/book/:isbn', bookController.getWithISBN); app.get('/api/book/:isbn/:owner', bookController.getWithISBNAndOwner); } exports.setup = setup;
/** * Created by Stein-Otto Svorstøl on 26.08.15. */ 'use strict'; var bookController = require('./controllers/bookController'); function setup(app){ var bodyParser = require('body-parser'); // Some setup for encoding of requests app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use(function(req, res, next) { // Headers to allow CORS and different requests res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.put('/book', bookController.createNew); app.get('/book/:isbn', bookController.getWithISBN); app.get('/book/:isbn/:owner', bookController.getWithISBNAndOwner); } exports.setup = setup;
Fix issue where value might be null in which case it's safe to just set directly on the property.
import data from '../util/data'; export default function (opts) { const { attribute } = opts; return function (name, oldValue, newValue) { const propertyName = data(this, 'attributeLinks')[name]; if (propertyName) { const propertyData = data(this, `api/property/${propertyName}`); if (!propertyData.settingProperty) { const propOpts = this.constructor.properties[propertyName]; this[propertyName] = newValue !== null && propOpts.deserialize ? propOpts.deserialize(newValue) : newValue; } } if (attribute) { attribute(this, { name: name, newValue: newValue === null ? undefined : newValue, oldValue: oldValue === null ? undefined : oldValue }); } }; }
import data from '../util/data'; export default function (opts) { const { attribute } = opts; return function (name, oldValue, newValue) { const propertyName = data(this, 'attributeLinks')[name]; if (propertyName) { const propertyData = data(this, `api/property/${propertyName}`); if (!propertyData.settingProperty) { const propOpts = this.constructor.properties[propertyName]; this[propertyName] = propOpts.deserialize ? propOpts.deserialize(newValue) : newValue; } } if (attribute) { attribute(this, { name: name, newValue: newValue === null ? undefined : newValue, oldValue: oldValue === null ? undefined : oldValue }); } }; }
Split test function in 2 functions
package envh import ( "regexp" "testing" "github.com/stretchr/testify/assert" ) func TestCreateTreeFromDelimiterFilteringByRegexp(t *testing.T) { setTestingEnvsForTree() n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_") for key, expected := range map[string]string{"TEST3": "test1", "TEST4": "test2", "TEST6": "test3", "TEST1": "test5", "TEST2": "test4"} { nodes := n.findAllChildsByKey(key, true) assert.Len(t, *nodes, 1, "Must contains 1 element") assert.Equal(t, expected, (*nodes)[0].value, "Must have correct value") } } func TestCreateTreeFromDelimiterFilteringByRegexpAndFindAllKeysWithAKey(t *testing.T) { setTestingEnvsForTree() n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_") nodes := n.findAllChildsByKey("TEST2", false) assert.Len(t, *nodes, 2, "Must contains 2 elements") }
package envh import ( "regexp" "testing" "github.com/stretchr/testify/assert" ) func TestCreateTreeFromDelimiterFilteringByRegexp(t *testing.T) { setTestingEnvsForTree() n := createTreeFromDelimiterFilteringByRegexp(regexp.MustCompile("ENVH"), "_") for key, expected := range map[string]string{"TEST3": "test1", "TEST4": "test2", "TEST6": "test3", "TEST1": "test5", "TEST2": "test4"} { nodes := n.findAllChildsByKey(key, true) assert.Len(t, *nodes, 1, "Must contains 1 element") assert.Equal(t, expected, (*nodes)[0].value, "Must have correct value") } nodes := n.findAllChildsByKey("TEST2", false) assert.Len(t, *nodes, 2, "Must contains 2 elements") }
Add "-i" flag to ignore module not found errors https://github.com/steveicarus/iverilog/pull/151 Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog -i -t null ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog", "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog -t null ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog", "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
Move cache into common location
<?php namespace App\Phansible\Provider; use App\Phansible\Model\GithubAdapter; use Cache\Adapter\Filesystem\FilesystemCachePool; use Github\Client; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; class GithubProviderStaticFactory { /** * {@inheritdoc} */ public static function create(): GithubAdapter { $filesystemAdapter = new Local(__DIR__ . '/../../../var/cache/github-api-cache'); $filesystem = new Filesystem($filesystemAdapter); $cache = new FilesystemCachePool($filesystem); $client = new Client(); $client->addCache($cache); return new GithubAdapter($client); } }
<?php namespace App\Phansible\Provider; use App\Phansible\Model\GithubAdapter; use Cache\Adapter\Filesystem\FilesystemCachePool; use Github\Client; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; class GithubProviderStaticFactory { /** * {@inheritdoc} */ public static function create(): GithubAdapter { $filesystemAdapter = new Local(__DIR__ . '/../../../app/cache/github-api-cache'); $filesystem = new Filesystem($filesystemAdapter); $cache = new FilesystemCachePool($filesystem); $client = new Client(); $client->addCache($cache); return new GithubAdapter($client); } }
Fix update model priority on api call
"use strict"; //Load dependencies var async = require("async"); var applicationStorage = require("core/application-storage"); /** * Insert an update into list * @param type * @param region * @param realm * @param name * @param priority * @param callback */ module.exports.insert = function (type, region, realm, name, priority, callback) { var redis = applicationStorage.redis; //Concat priority with timestamp priority = priority + '' + new Date().getTime(); //Create object to insert var value = JSON.stringify({region: region, realm: realm, name: name, priority: priority}); //Create or update auctionUpdate redis.zadd(type, priority, value, function (error) { callback(error); }); }; /** * Return the number of updates in list * @param type * @param callback */ module.exports.getCount = function (type, callback) { var redis = applicationStorage.redis; redis.zcount(type, "-inf", "+inf", function (error, value) { callback(error, value); }); };
"use strict"; //Load dependencies var async = require("async"); var applicationStorage = require("core/application-storage"); /** * Insert an update into list * @param type * @param region * @param realm * @param name * @param priority * @param callback */ module.exports.insert = function (type, region, realm, name, priority, callback) { var redis = applicationStorage.redis; //Create object to insert var value = JSON.stringify({region: region, realm: realm, name: name, priority: priority}); //Create or update auctionUpdate redis.zadd(type, priority + '' + new Date().getTime(), value, function (error) { callback(error); }); }; /** * Return the number of updates in list * @param type * @param callback */ module.exports.getCount = function (type, callback) { var redis = applicationStorage.redis; redis.zcount(type, "-inf", "+inf", function (error, value) { callback(error, value); }); };
Change javadoc similarityThreshold -> Predicate.
package uk.ac.ebi.quickgo.ontology.common.coterm; import java.util.List; import java.util.function.Predicate; import org.springframework.data.repository.Repository; /** * Represents the store of co-occurring GO Term information. * * @author Tony Wardell * Date: 29/09/2016 * Time: 11:39 * Created with IntelliJ IDEA. */ public interface CoTermRepository extends Repository<List<CoTerm>, String> { /** * For a single GO Term, retrieve a list of co-occurring terms and related statistics, in order of the * co-occurring terms similarity probablity (descending). * @param id is the target GO term, for which the method will retrieve co-occurring terms (GO terms that are used * to annotation the same gene products as this GO Term is used to annotate). * @param source is the method from which the annotation that uses the GO term was generated. * @param limit Limit the number of co-occurring terms return to the limit specified. * @param filter apply the predicate to filter the results. * @return a list of objects, each one of which represent a GO Term that is used to annotate the same gene * product as the id. Each object holds statistics related to that co-occurrence. */ List<CoTerm> findCoTerms(String id, CoTermSource source, int limit, Predicate<CoTerm> filter); }
package uk.ac.ebi.quickgo.ontology.common.coterm; import java.util.List; import java.util.function.Predicate; import org.springframework.data.repository.Repository; /** * Represents the store of co-occurring GO Term information. * * @author Tony Wardell * Date: 29/09/2016 * Time: 11:39 * Created with IntelliJ IDEA. */ public interface CoTermRepository extends Repository<List<CoTerm>, String> { /** * For a single GO Term, retrieve a list of co-occurring terms and related statistics, in order of the * co-occurring terms similarity probablity (descending). * @param id is the target GO term, for which the method will retrieve co-occurring terms (GO terms that are used * to annotation the same gene products as this GO Term is used to annotate). * @param source is the method from which the annotation that uses the GO term was generated. * @param limit Limit the number of co-occurring terms return to the limit specified. * @param similarityThreshold if specified (greater than zero), only return co-occurring GO terms with a * similarity ratio above this figure. * @return a list of objects, each one of which represent a GO Term that is used to annotate the same gene * product as the id. Each object holds statistics related to that co-occurrence. */ List<CoTerm> findCoTerms(String id, CoTermSource source, int limit, Predicate filter); }
Clean up return value for API
import urlparse import os, sys import json tools_dir = os.environ.get('TOOLSDIR') lib_path = os.path.abspath(tools_dir) sys.path.append(lib_path) from msc_apps import * data_dir_root = os.environ.get('DATADIR') def sync_wallet_response(request_dict): if not request_dict.has_key('type'): return (None, 'No field type in response dict '+str(request_dict)) req_type = request_dict['type'][0].upper() if req_type == "SYNCWALLET": syncWallets(request_dict['masterWallets'][0]) else: return (None, req_type + ' is not supported') response = { 'status': 'OK' } return (json.dumps(response), None) def syncWallets(master_wallets_json): master_wallets = json.loads(master_wallets_json) for wallet in master_wallets: uuid = wallet['uuid'] filename = data_dir_root + '/wallets/' + uuid + '.json' with open(filename, 'w') as f: json.dump(wallet, f) return "OK" def sync_wallet_handler(environ, start_response): return general_handler(environ, start_response, sync_wallet_response)
import urlparse import os, sys import json tools_dir = os.environ.get('TOOLSDIR') lib_path = os.path.abspath(tools_dir) sys.path.append(lib_path) from msc_apps import * data_dir_root = os.environ.get('DATADIR') def sync_wallet_response(request_dict): if not request_dict.has_key('type'): return (None, 'No field type in response dict '+str(request_dict)) req_type = request_dict['type'][0].upper() if req_type == "SYNCWALLET": response_data = syncWallets(request_dict['masterWallets'][0]) else: return (None, req_type + ' is not supported') response = { 'status': 'OK', 'data': response_data } return (json.dumps(response), None) def syncWallets(master_wallets_json): master_wallets = json.loads(master_wallets_json) for wallet in master_wallets: uuid = wallet['uuid'] filename = data_dir_root + '/wallets/' + uuid + '.json' with open(filename, 'w') as f: json.dump(wallet, f) return "OK" def sync_wallet_handler(environ, start_response): return general_handler(environ, start_response, sync_wallet_response)
Use staticCache if option is set
require('./dotenv')(); exports.config = null; exports.run = null; exports.start = function start(options){ options = options || {}; options.port = options.port || process.env.PORT || 80; options.serve = options.serve || 'public'; options.bodyParser = options.bodyParser || true; options.staticCache = options.staticCache || false; console.log('Node ' + process.version + ', port ' + options.port); var http = require('http'); var koa = require('koa'); var logger = require('koa-logger'); var serve = require('koa-static'); var serveCache = require('koa-static-cache'); var bodyParser = require('koa-bodyparser'); var app = koa(); app.use(logger()); if(options.staticCache){ app.use(serveCache(options.serve, { buffer: true })); }else{ app.use(serve(options.serve)); } if(options.bodyParser){ app.use(bodyParser()); } if(exports.config){ exports.config(app); } var server = http.createServer(app.callback()); if(exports.run){ exports.run(server); } server.listen(options.port); };
require('./dotenv')(); exports.config = null; exports.run = null; exports.start = function start(options){ options = options || {}; options.port = options.port || process.env.PORT || 80; options.serve = options.serve || 'public'; options.bodyParser = options.bodyParser || true; console.log('Node ' + process.version + ', port ' + options.port); var http = require('http'); var koa = require('koa'); var logger = require('koa-logger'); var serve = require('koa-static'); var bodyParser = require('koa-bodyparser'); var app = koa(); app.use(logger()); app.use(serve(options.serve)); if(options.bodyParser){ app.use(bodyParser()); } if(exports.config){ exports.config(app); } var server = http.createServer(app.callback()); if(exports.run){ exports.run(server); } server.listen(options.port); };
[SW-1610][FollowUp] Fix running python tests by changing the env directly (cherry picked from commit 0d808a100cd14fce9d4fba4f9cde6ad5315fbc12)
# # 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. # import os import sys import pytest dist = sys.argv[2] path = os.getenv("PYTHONPATH") if path is None: path = dist else: path = "{}:{}".format(dist, path) os.putenv("PYTHONPATH", path) os.putenv('PYSPARK_DRIVER_PYTHON', sys.executable) os.putenv('PYSPARK_PYTHON', sys.executable) os.environ["PYTHONPATH"] = path os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable os.environ['PYSPARK_PYTHON'] = sys.executable sys.path.insert(0, dist) pytestConfigArgs = sys.argv[1].replace("'", "").split(" ") args = pytestConfigArgs + ["--dist", dist, "--spark_conf", ' '.join(sys.argv[3:])] code = pytest.main(args) sys.exit(code)
# # 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. # import os import sys import pytest dist = sys.argv[2] path = os.getenv("PYTHONPATH") if path is None: path = dist else: path = "{}:{}".format(dist, path) os.environ["PYTHONPATH"] = path os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable os.environ['PYSPARK_PYTHON'] = sys.executable sys.path.insert(0, dist) pytestConfigArgs = sys.argv[1].replace("'", "").split(" ") args = pytestConfigArgs + ["--dist", dist, "--spark_conf", ' '.join(sys.argv[3:])] code = pytest.main(args) sys.exit(code)
Add a test for __sub__ between a DateWith and a vanilla date.
import unittest from datetime import date, timedelta from calexicon.dates import DateWithCalendar class TestDateWithCalendar(unittest.TestCase): def setUp(self): date_dt = date(2010, 8, 1) self.date_wc = DateWithCalendar(None, date_dt) def test_comparisons(self): self.assertTrue(self.date_wc < date(2010, 8, 2)) self.assertFalse(self.date_wc < date(2010, 7, 31)) self.assertTrue(self.date_wc > date(2010, 7, 2)) self.assertFalse(self.date_wc > date(2010, 8, 31)) def test_nonstrict_comparisons(self): self.assertTrue(self.date_wc <= date(2010, 8, 2)) self.assertFalse(self.date_wc <= date(2010, 7, 31)) self.assertTrue(self.date_wc >= date(2010, 7, 2)) self.assertFalse(self.date_wc >= date(2010, 8, 31)) self.assertTrue(self.date_wc <= date(2010, 8, 1)) self.assertTrue(self.date_wc >= date(2010, 8, 1)) def test_subtraction(self): self.assertEqual(self.date_wc - date(2012, 10, 30), timedelta(days=-821))
import unittest from datetime import date from calexicon.dates import DateWithCalendar class TestDateWithCalendar(unittest.TestCase): def setUp(self): date_dt = date(2010, 8, 1) self.date_wc = DateWithCalendar(None, date_dt) def test_comparisons(self): self.assertTrue(self.date_wc < date(2010, 8, 2)) self.assertFalse(self.date_wc < date(2010, 7, 31)) self.assertTrue(self.date_wc > date(2010, 7, 2)) self.assertFalse(self.date_wc > date(2010, 8, 31)) def test_nonstrict_comparisons(self): self.assertTrue(self.date_wc <= date(2010, 8, 2)) self.assertFalse(self.date_wc <= date(2010, 7, 31)) self.assertTrue(self.date_wc >= date(2010, 7, 2)) self.assertFalse(self.date_wc >= date(2010, 8, 31)) self.assertTrue(self.date_wc <= date(2010, 8, 1)) self.assertTrue(self.date_wc >= date(2010, 8, 1))
Fix bug on generate tag group command
<?php namespace Conner\Tagging\Console\Commands; use Conner\Tagging\TaggingUtility; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputArgument; class GenerateTagGroup extends Command { protected $name = 'tagging:create-group'; protected $signature = 'tagging:create-group {group}'; protected $description = 'Create a laravel tag group'; public function handle() { $groupName = $this->argument('group'); $tagGroupModel = TaggingUtility::tagGroupModelString(); $tagGroup = new $tagGroupModel(); $tagGroup->name = $groupName; $tagGroup->slug = TaggingUtility::normalize($groupName); $tagGroup->save(); $this->info('Created tag group: '.$groupName); } protected function getArguments() { return [ ['group', InputArgument::REQUIRED, 'Name of the group to create.'], ]; } }
<?php namespace Conner\Tagging\Console\Commands; use Conner\Tagging\TaggingUtility; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputArgument; class GenerateTagGroup extends Command { protected $name = 'tagging:create-group'; protected $signature = 'tagging:create-group {group}'; protected $description = 'Create a laravel tag group'; public function handle() { $groupName = $this->argument('group'); $tagGroup = new ${TaggingUtility::tagGroupModelString()}; $tagGroup->name = $groupName; $tagGroup->slug = TaggingUtility::normalize($groupName); $tagGroup->save(); $this->info('Created tag group: '.$groupName); } protected function getArguments() { return [ ['group', InputArgument::REQUIRED, 'Name of the group to create.'], ]; } }
Make the readers tests a bit more verbose.
# coding: utf-8 try: import unittest2 as unittest except ImportError, e: import unittest import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } for key, value in expected.items(): self.assertEquals(value, metadata[key], key)
# coding: utf-8 try: import unittest2 except ImportError, e: import unittest as unittest2 import datetime import os from pelican import readers CUR_DIR = os.path.dirname(__file__) CONTENT_PATH = os.path.join(CUR_DIR, 'content') def _filename(*args): return os.path.join(CONTENT_PATH, *args) class RstReaderTest(unittest2.TestCase): def test_article_with_metadata(self): reader = readers.RstReader({}) content, metadata = reader.read(_filename('article_with_metadata.rst')) expected = { 'category': 'yeah', 'author': u'Alexis Métaireau', 'title': 'This is a super article !', 'summary': 'Multi-line metadata should be supported\nas well as <strong>inline markup</strong>.', 'date': datetime.datetime(2010, 12, 2, 10, 14), 'tags': ['foo', 'bar', 'foobar'], } self.assertDictEqual(metadata, expected)
Revert "cancel sorting trend tags in the UI side" This reverts commit d72abcf351161b068496b38675fda1306d21de74.
import { TREND_TAGS_SUCCESS, TREND_TAGS_HISTORY_SUCCESS, TOGGLE_TREND_TAGS } from '../actions/trend_tags'; import Immutable from 'immutable'; const initialState = Immutable.Map({ tags: Immutable.Map({ updated_at: '', score: Immutable.Map(), }), history: Immutable.List(), visible: true, }); export default function trend_tags(state = initialState, action) { switch(action.type) { case TREND_TAGS_SUCCESS: const tmp = Immutable.fromJS(action.tags); return state.set('tags', tmp.set('score', tmp.get('score').sort((a, b) => { return b - a; }))); case TREND_TAGS_HISTORY_SUCCESS: return state.set('history', Immutable.fromJS(action.tags)); case TOGGLE_TREND_TAGS: return state.set('visible', !state.get('visible')); default: return state; } }
import { TREND_TAGS_SUCCESS, TREND_TAGS_HISTORY_SUCCESS, TOGGLE_TREND_TAGS } from '../actions/trend_tags'; import Immutable from 'immutable'; const initialState = Immutable.Map({ tags: Immutable.Map({ updated_at: '', score: Immutable.Map(), }), history: Immutable.List(), visible: true, }); export default function trend_tags(state = initialState, action) { switch(action.type) { case TREND_TAGS_SUCCESS: return state.set('tags', Immutable.fromJS(action.tags)); case TREND_TAGS_HISTORY_SUCCESS: return state.set('history', Immutable.fromJS(action.tags)); case TOGGLE_TREND_TAGS: return state.set('visible', !state.get('visible')); default: return state; } }
Remove old tests, fix import
package main import ( "flag" "os" "github.com/ian-kent/Go-MailHog/MailHog-Server/config" "github.com/ian-kent/Go-MailHog/MailHog-UI/assets" "github.com/ian-kent/Go-MailHog/MailHog-UI/web" "github.com/ian-kent/Go-MailHog/http" "github.com/ian-kent/go-log/log" gotcha "github.com/ian-kent/gotcha/app" ) var conf *config.Config var exitCh chan int func configure() { config.RegisterFlags() flag.Parse() conf = config.Configure() } func main() { configure() // FIXME need to make API URL configurable exitCh = make(chan int) cb := func(app *gotcha.App) { web.CreateWeb(conf, app) } go http.Listen(conf, assets.Asset, exitCh, cb) for { select { case <-exitCh: log.Printf("Received exit signal") os.Exit(0) } } }
package main import ( "flag" "os" "github.com/ian-kent/Go-MailHog/MailHog-Server/config" "github.com/ian-kent/Go-MailHog/MailHog-UI/assets" "github.com/ian-kent/Go-MailHog/MailHog-UI/http/web" "github.com/ian-kent/Go-MailHog/http" "github.com/ian-kent/go-log/log" gotcha "github.com/ian-kent/gotcha/app" ) var conf *config.Config var exitCh chan int func configure() { config.RegisterFlags() flag.Parse() conf = config.Configure() } func main() { configure() // FIXME need to make API URL configurable exitCh = make(chan int) cb := func(app *gotcha.App) { web.CreateWeb(conf, app) } go http.Listen(conf, assets.Asset, exitCh, cb) for { select { case <-exitCh: log.Printf("Received exit signal") os.Exit(0) } } }
Make seeds runnable on CLI
require('dotenv').load() // LEJ: ES6 import not working for a commandline run of knex, // replacing with require // (e.g. knex seed:run) // // import { merge } from 'lodash' const _ = require('lodash') const merge = _.merge if (!process.env.DATABASE_URL) { throw new Error('process.env.DATABASE_URL must be set') } const url = require('url').parse(process.env.DATABASE_URL) var user, password if (url.auth) { const i = url.auth.indexOf(':') user = url.auth.slice(0, i) password = url.auth.slice(i + 1) } const defaults = { client: 'pg', connection: { host: url.hostname, port: url.port, user: user, password: password, database: url.pathname.substring(1) }, migrations: { tableName: 'knex_migrations' } } module.exports = { test: defaults, development: defaults, staging: defaults, production: merge({connection: {ssl: true}}, defaults) }
import { merge } from 'lodash' require('dotenv').load() if (!process.env.DATABASE_URL) { throw new Error('process.env.DATABASE_URL must be set') } const url = require('url').parse(process.env.DATABASE_URL) var user, password if (url.auth) { const i = url.auth.indexOf(':') user = url.auth.slice(0, i) password = url.auth.slice(i + 1) } const defaults = { client: 'pg', connection: { host: url.hostname, port: url.port, user: user, password: password, database: url.pathname.substring(1) }, migrations: { tableName: 'knex_migrations' } } module.exports = { test: defaults, development: defaults, staging: defaults, production: merge({connection: {ssl: true}}, defaults) }
Set $NBGALLERY_URL to override gallery location
import json import os import sys sys.path.append('/root/.jupyter/extensions/') c.JupyterApp.ip = '*' c.JupyterApp.port = 80 c.JupyterApp.open_browser = False c.JupyterApp.allow_credentials = True c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post'] c.JupyterApp.reraise_server_extension_failures = True c.JupyterApp.extra_static_paths = ['/root/.jupyter/static'] c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/'] c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'} c.JupyterApp.allow_origin = 'https://nb.gallery' # needed to receive notebooks from the gallery c.JupyterApp.disable_check_xsrf = True # Override gallery location nbgallery_url = os.getenv('NBGALLERY_URL') if nbgallery_url: print('Setting nbgallery url to %s' % nbgallery_url) c.JupyterApp.allow_origin = nbgallery_url config = json.loads(open('/root/.jupyter/nbconfig/common.json').read()) config['nbgallery']['url'] = nbgallery_url with open('/root/.jupyter/nbconfig/common.json', 'w') as output: output.write(json.dumps(config, indent=2))
import sys sys.path.append('/root/.jupyter/extensions/') c.JupyterApp.ip = '*' c.JupyterApp.port = 80 c.JupyterApp.open_browser = False c.JupyterApp.allow_credentials = True c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post'] c.JupyterApp.reraise_server_extension_failures = True c.JupyterApp.extra_static_paths = ['/root/.jupyter/static'] c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/'] c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'} c.JupyterApp.allow_origin = 'https://nb.gallery' # needed to receive notebooks from the gallery c.JupyterApp.disable_check_xsrf = True
Use css instead of scss as output format
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ // Create the webfont files: webfont: { icons: { src: '../icons/actions/22@2x/*.svg', dest: './dist', options: { stylesheet: 'css', types: 'eot,woff2,ttf,svg', optimize: false } } } }); grunt.loadNpmTasks('grunt-webfont'); // Run the default task by executing "grunt" in the CLI: grunt.registerTask('default', ['webfont']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ // Create the webfont files: webfont: { icons: { src: '../icons/actions/22@2x/*.svg', dest: './dist', options: { stylesheet: 'scss', types: 'eot,woff2,ttf,svg', optimize: false } } } }); grunt.loadNpmTasks('grunt-webfont'); // Run the default task by executing "grunt" in the CLI: grunt.registerTask('default', ['webfont']); };
Fix string resolution for filesystem
import angr import logging l = logging.getLogger(name=__name__) class getcwd(angr.SimProcedure): def run(self, buf, size): cwd = self.state.fs.cwd size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1) try: self.state.memory.store(buf, cwd, size=size) self.state.memory.store(buf + size, b'\0') except angr.errors.SimSegfaultException: return 0 else: return buf class chdir(angr.SimProcedure): def run(self, buf): cwd = self.state.mem[buf].string.concrete l.info('chdir(%r)', cwd) self.state.fs.cwd = cwd return 0
import angr import logging l = logging.getLogger(name=__name__) class getcwd(angr.SimProcedure): def run(self, buf, size): cwd = self.state.fs.cwd size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1) try: self.state.memory.store(buf, cwd, size=size) self.state.memory.store(buf + size, b'\0') except angr.errors.SimSegfaultException: return 0 else: return buf class chdir(angr.SimProcedure): def run(self, buf): cwd = self.state.mem[buf].string l.info('chdir(%r)', cwd) self.state.fs.cwd = cwd return 0
Make sure conditional_punctuation can handle all value type (using force_text).
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Erik Stein <code@classlibrary.net>, 2015 import re from django import template from django.template.defaultfilters import stringfilter from django.utils.encoding import force_text from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from .. import text as text_utils register = template.Library() @register.filter() def conditional_punctuation(value, punctuation=",", space=" "): """ Appends punctuation if the (stripped) value is not empty and the value does not already end in a punctuation mark (.,:;!?). """ value = force_text(value or "").strip() if value: if value[-1] not in ".,:;!?": value += conditional_escape(punctuation) value += conditional_escape(space) # Append previously stripped space return value conditional_punctuation.is_safe = True WHITESPACE = re.compile('\s+') @register.filter(needs_autoescape=True) @stringfilter def nbsp(text, autoescape=True): if autoescape: esc = conditional_escape else: esc = lambda x: x return mark_safe(WHITESPACE.sub('&nbsp;', esc(text.strip()))) @register.filter(needs_autoescape=False) @stringfilter def html_entities_to_unicode(text): return mark_safe(text_utils.html_entities_to_unicode(text))
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Erik Stein <code@classlibrary.net>, 2015 import re from django import template from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from .. import text as text_utils register = template.Library() @register.filter() def conditional_punctuation(value, punctuation=",", space=" "): """ Appends punctuation if the (stripped) value is not empty and the value does not already end in a punctuation mark (.,:;!?). """ value = value.strip() if value: if value[-1] not in ".,:;!?": value += conditional_escape(punctuation) value += conditional_escape(space) # Append previously stripped space return value conditional_punctuation.is_safe = True WHITESPACE = re.compile('\s+') @register.filter(needs_autoescape=True) @stringfilter def nbsp(text, autoescape=True): if autoescape: esc = conditional_escape else: esc = lambda x: x return mark_safe(WHITESPACE.sub('&nbsp;', esc(text.strip()))) @register.filter(needs_autoescape=False) @stringfilter def html_entities_to_unicode(text): return mark_safe(text_utils.html_entities_to_unicode(text))
Use correct parameter for HOST and PORT
from .config import current_config from flask import Flask from flask import redirect from flask import url_for from flask.ext.babel import Babel from kqueen_ui.blueprints.registration.views import registration from kqueen_ui.blueprints.ui.views import ui from werkzeug.contrib.cache import SimpleCache import logging import os logger = logging.getLogger(__name__) cache = SimpleCache() def create_app(config_file=None): app = Flask(__name__, static_folder='./asset/static') app.register_blueprint(ui, url_prefix='/ui') app.register_blueprint(registration, url_prefix='/registration') # load configuration config = current_config(config_file) app.config.from_mapping(config.to_dict()) app.logger.setLevel(getattr(logging, app.config.get('LOG_LEVEL'))) app.logger.info('Loading configuration from {}'.format(config.source_file)) Babel(app) return app app = create_app() @app.route('/') def root(): return redirect(url_for('ui.index'), code=302) def run(): logger.debug('kqueen_ui starting') app.run( host=app.config.get('HOST'), port=int(app.config.get('PORT')) )
from .config import current_config from flask import Flask from flask import redirect from flask import url_for from flask.ext.babel import Babel from kqueen_ui.blueprints.registration.views import registration from kqueen_ui.blueprints.ui.views import ui from werkzeug.contrib.cache import SimpleCache import logging import os logger = logging.getLogger(__name__) cache = SimpleCache() def create_app(config_file=None): app = Flask(__name__, static_folder='./asset/static') app.register_blueprint(ui, url_prefix='/ui') app.register_blueprint(registration, url_prefix='/registration') # load configuration config = current_config(config_file) app.config.from_mapping(config.to_dict()) app.logger.setLevel(getattr(logging, app.config.get('LOG_LEVEL'))) app.logger.info('Loading configuration from {}'.format(config.source_file)) Babel(app) return app app = create_app() @app.route('/') def root(): return redirect(url_for('ui.index'), code=302) def run(): logger.debug('kqueen_ui starting') app.run( host=app.config.get('KQUEEN_UI_HOST'), port=int(app.config.get('KQUEEN_UI_PORT')) )
Add missing "require" after refactor
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui/effect //= require jquery.cookies //= require bootstrap //= require underscore //= require socket.io //= require select2 //= require sweet-alert.min //= require dashboard/modernizr.min //= require dashboard/pace.min //= require dashboard/wow.min //= require dashboard/jquery.scrollTo.min.js //= require dashboard/jquery.nicescroll.js //= require dashboard/jquery.app //= require handlebars.runtime //= require ansi_up.js //= require react //= require react_ujs //= require react_bootstrap //= require components //= require codemirror //= require formatting //= require shell //= require yaml //= require custom.codemirror // //= require init //= require_tree ./dashboard //= require autoload
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui/effect //= require jquery.cookies //= require bootstrap //= require underscore //= require socket.io //= require select2 //= require sweet-alert.min //= require dashboard/modernizr.min //= require dashboard/pace.min //= require dashboard/wow.min //= require dashboard/jquery.scrollTo.min.js //= require dashboard/jquery.nicescroll.js //= require dashboard/jquery.app //= require handlebars.runtime //= require ansi_up.js //= require react //= require react_ujs //= require react_bootstrap //= require components //= require codemirror //= require formatting //= require shell //= require yaml // //= require init //= require_tree ./dashboard //= require autoload
Correct pypi package; file naming was wrong.
'''setup script for this module''' from setuptools import setup def readme(): '''pull iin the readme file for the long description''' with open('README.md') as rfile: return rfile.read() setup( name='chamberconnectlibrary', version='2.1.3', description='A library for interfacing with Espec North America chambers', long_description=readme(), url='https://github.com/EspecNorthAmerica/ChamberConnectLibrary', author='Espec North America', author_email='mmetzler@espec.com', license='MIT', packages=['chamberconnectlibrary'], install_requires=['pyserial'], zip_safe=False, keywords='Espec P300 SCP220 F4T F4', include_package_data=True, scripts=['bin/chamberconnectlibrary-test.py'] )
'''setup script for this module''' from setuptools import setup def readme(): '''pull iin the readme file for the long description''' with open('README.md') as rfile: return rfile.read() setup( name='chamberconnectlibrary', version='2.1.2', description='A library for interfacing with Espec North America chambers', long_description=readme(), url='https://github.com/EspecNorthAmerica/ChamberConnectLibrary', author='Espec North America', author_email='mmetzler@espec.com', license='MIT', packages=['chamberconnectlibrary'], install_requires=['pyserial'], zip_safe=False, keywords='Espec P300 SCP220 F4T F4', include_package_data=True, scripts=['bin/chamberconnectlibrary-test.py'] )
feat: Append modified_field to the user_feilds of energy point rule
// Copyright (c) 2018, Frappe Technologies and contributors // For license information, please see license.txt frappe.ui.form.on('Energy Point Rule', { refresh: function(frm) { frm.events.set_user_and_multiplier_field_options(frm); }, reference_doctype(frm) { frm.events.set_user_and_multiplier_field_options(frm); }, set_user_and_multiplier_field_options(frm) { const reference_doctype = frm.doc.reference_doctype; if (!reference_doctype) return; frappe.model.with_doctype(reference_doctype, () => { const map_for_options = df => ({ label: df.label, value: df.fieldname }); const fields = frappe.meta.get_docfields(frm.doc.reference_doctype); const user_fields = fields.filter(df => (df.fieldtype === 'Link' && df.options === 'User') || df.fieldtype === 'Data') .map(map_for_options) .concat([ { label: __('Owner'), value: 'owner' }, { label: __('Modified By'), value: 'modified_by' } ]); const multiplier_fields = fields.filter(df => ['Int', 'Float'].includes(df.fieldtype)) .map(map_for_options); frm.set_df_property('user_field', 'options', user_fields); frm.set_df_property('multiplier_field', 'options', multiplier_fields); }); } });
// Copyright (c) 2018, Frappe Technologies and contributors // For license information, please see license.txt frappe.ui.form.on('Energy Point Rule', { refresh: function(frm) { frm.events.set_user_and_multiplier_field_options(frm); }, reference_doctype(frm) { frm.events.set_user_and_multiplier_field_options(frm); }, set_user_and_multiplier_field_options(frm) { const reference_doctype = frm.doc.reference_doctype; if (!reference_doctype) return; frappe.model.with_doctype(reference_doctype, () => { const map_for_options = df => ({ label: df.label, value: df.fieldname }); const fields = frappe.meta.get_docfields(frm.doc.reference_doctype); const user_fields = fields.filter(df => (df.fieldtype === 'Link' && df.options === 'User') || df.fieldtype === 'Data') .map(map_for_options) .concat([{label: __('Owner'), value: 'owner'}]); const multiplier_fields = fields.filter(df => ['Int', 'Float'].includes(df.fieldtype)) .map(map_for_options); frm.set_df_property('user_field', 'options', user_fields); frm.set_df_property('multiplier_field', 'options', multiplier_fields); }); } });
Change Movie parameter from production_company to production_companies
# media.py class Movie(object): def __init__(self, title, storyline, poster_image_url, trailer_youtube_url, lead_actors, release_date, mpaa_rating, language, runtime, production_companies, trivia ): self.title = title self.storyline = storyline self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url self.lead_actors = lead_actors self.release_date = release_date self.mpaa_rating = mpaa_rating self.language = language self.runtime = runtime self.production_companies = production_companies self.trivia = trivia
# media.py class Movie(object): def __init__(self, title, storyline, poster_image_url, trailer_youtube_url, lead_actors, release_date, mpaa_rating, language, runtime, production_company, trivia ): self.title = title self.storyline = storyline self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url self.lead_actors = lead_actors self.release_date = release_date self.mpaa_rating = mpaa_rating self.language = language self.runtime = runtime self.production_company = production_company self.trivia = trivia
Use the long version of recipient
package se.soy.gpg; import java.util.List; import java.util.ArrayList; public class GPG { // FIXME Remove when done static<T> void println(T arg) { System.out.println(arg); } public static void main(String[] args) { println("main"); GPG.encrypt().armor().sign().recipient("0xrecipient").output(); /* GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file"); GPG.sign().armor().(); */ } private List<String> command = new ArrayList<String>(); private static GPG gpg = null; public void output() { println("OPTIONS:"); println("Command:"); println(command); } public static GPG encrypt() { gpg = (null == gpg) ? new GPG() : gpg; gpg.command.add("--encrypt"); return gpg; } public static GPG sign() { gpg = (null == gpg) ? new GPG() : gpg; gpg.command.add("--sign"); return gpg; } public GPG armor() { command.add("--armor"); return this; } // TODO: Add recipients(List<String> recipients) public GPG recipient(String recipient) { command.add("--recipient " + recipient); return this; } }
package se.soy.gpg; import java.util.List; import java.util.ArrayList; public class GPG { // FIXME Remove when done static<T> void println(T arg) { System.out.println(arg); } public static void main(String[] args) { println("main"); GPG.encrypt().armor().sign().recipient("0xrecipient").output(); /* GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file"); GPG.sign().armor().(); */ } private List<String> command = new ArrayList<String>(); private static GPG gpg = null; public void output() { println("OPTIONS:"); println("Command:"); println(command); } public static GPG encrypt() { gpg = (null == gpg) ? new GPG() : gpg; gpg.command.add("--encrypt"); return gpg; } public static GPG sign() { gpg = (null == gpg) ? new GPG() : gpg; gpg.command.add("--sign"); return gpg; } public GPG armor() { command.add("--armor"); return this; } // TODO: Add recipients(List<String> recipients) public GPG recipient(String recipient) { command.add("-r " + recipient); return this; } }
Fix error when tick history is empty
import React, { PropTypes } from 'react'; import EChart from './EChart'; import SizeProvider from '../_common/SizeProvider'; import createOptions from './options/MobileChartOptions'; const theme = { background: 'white', line: 'rgba(42, 48, 82, 0.8)', fill: 'rgba(42, 48, 82, 0.2)', text: '#999', grid: '#eee', axisText: 'rgba(64, 68, 72, .5)', }; export default class TradeChart extends React.Component { static propTypes = { history: PropTypes.array.isRequired, spot: PropTypes.number, }; static defaultProps = { spot: 0, }; render() { const { history, spot } = this.props; if (history.length === 0) return null; const options = createOptions({ history, spot: +spot, theme }); return ( <SizeProvider style={{ width: '100%', height: '120px' }}> <EChart options={options} {...this.props} /> </SizeProvider> ); } }
import React, { PropTypes } from 'react'; import EChart from './EChart'; import SizeProvider from '../_common/SizeProvider'; import createOptions from './options/MobileChartOptions'; const theme = { background: 'white', line: 'rgba(42, 48, 82, 0.8)', fill: 'rgba(42, 48, 82, 0.2)', text: '#999', grid: '#eee', axisText: 'rgba(64, 68, 72, .5)', }; export default class TradeChart extends React.Component { static propTypes = { history: PropTypes.array.isRequired, spot: PropTypes.number, }; static defaultProps = { history: [], spot: 0, }; render() { const { history, spot } = this.props; const options = createOptions({ history, spot: +spot, theme }); return ( <SizeProvider style={{ width: '100%', height: '120px' }}> <EChart options={options} {...this.props} /> </SizeProvider> ); } }
Make fall back to ~/.eslintrc
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" from SublimeLinter.lint import Linter class ESLint(Linter): """Provides an interface to the eslint executable.""" syntax = ('javascript', 'html') cmd = 'eslint --format=compact' version_args = '--version' version_re = r'v(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.3.0' regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) line_col_base = (1, 0) selectors = { 'html': 'source.js.embedded.html' } tempfile_suffix = 'js' config_file = ('--config', '.eslintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" from SublimeLinter.lint import Linter class ESLint(Linter): """Provides an interface to the eslint executable.""" syntax = ('javascript', 'html') cmd = 'eslint --format=compact' version_args = '--version' version_re = r'v(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.3.0' regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) line_col_base = (1, 0) selectors = { 'html': 'source.js.embedded.html' } tempfile_suffix = 'js' config_file = ('--config', '.eslintrc')
Print C++ code during parsing
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def run(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('C++ Transpilation', ast.transpile_children()) utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def run(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
Change API for name to be string
'use strict'; /* rule.js * Expresses CSS rules. */ const create = require('./create'); let Rule = create(function(name, list1, list2){ this.name = name; if (this.name[0] !== '@') { this.type = 'selector'; this.selector = this.name || []; this.items = list1 || []; } else if (this.name[0] === '@') { this.type = 'at-rule'; if (arguments.length === 3) { this.type += ' expressive'; this.name = this.name[0]; this.expression = list1 || []; this.items = list2 || []; } else if (arguments.length === 2) this.input = list1; } else { this.type = 'unknown'; this.items = [].concat(...(Array.prototype.slice.call(arguments, 1))) || []; } }, { add: function(){ this.items.push(...arguments); return this; }, remove: function(loc){ this.items.splice(loc, 1); return this; }, set: function(loc, value){ this.items[loc] = value; return this; }, }); module.exports = exports = Rule;
'use strict'; /* rule.js * Expresses CSS rules. */ const create = require('./create'); let Rule = create(function(names, list1, list2){ this.names = names; if (typeof names === 'string') this.names = [names]; if (this.names.length > 1 || arguments.length === 2) { this.type = 'selector'; this.selectors = this.names || []; this.items = list1 || []; } else if (this.names.length === 1 && this.names[0][0] === '@') { this.type = 'at-rule'; if (arguments.length === 3) { this.type += ' expressive'; this.name = this.names[0]; this.expression = list1 || []; this.items = list2 || []; } else if (arguments.length === 2) this.input = list1; } else { this.type = 'unknown'; this.items = [].concat(...(Array.prototype.slice.call(arguments, 1))) || []; } }, { add: function(){ this.items.push(...arguments); return this; }, remove: function(loc){ this.items.splice(loc, 1); return this; }, set: function(loc, value){ this.items[loc] = value; return this; }, }); module.exports = exports = Rule;
Remove unnecessary state init in reducer test
import posts from '../reducers'; import { addPost, requestPosts, requestPostsError, receivePosts, } from '../actions'; const post = { title: 'A first post' }; it('returns initial state', () => { const state = posts(undefined, {}); expect(state).toEqual({ isFetching: false, lastUpdated: 0, items: [], }); }); it('handles adding post', () => { const state = posts(undefined, addPost(post)); expect(state.items).toContain(post); }); it('handles receiving posts', () => { const state = posts( undefined, receivePosts({ posts: [post] }), ); expect(state.items.length).not.toBe(0); expect(state.isFetching).toBe(false); expect(state.lastUpdated).not.toBe(0); }); it('handles requesting posts', () => { const state = posts({ items: [] }, requestPosts()); expect(state.isFetching).toBe(true); }); it('handles request errors', () => { const state = posts( { items: [], isFetching: true }, requestPostsError(), ); expect(state.isFetching).toBe(false); });
import posts from '../reducers'; import { addPost, requestPosts, requestPostsError, receivePosts, } from '../actions'; const post = { title: 'A first post' }; it('returns initial state', () => { const state = posts(undefined, {}); expect(state).toEqual({ isFetching: false, lastUpdated: 0, items: [], }); }); it('handles adding post', () => { const state = posts({ items: [] }, addPost(post)); expect(state.items).toContain(post); }); it('handles receiving posts', () => { const state = posts( undefined, receivePosts({ posts: [post] }), ); expect(state.items.length).not.toBe(0); expect(state.isFetching).toBe(false); expect(state.lastUpdated).not.toBe(0); }); it('handles requesting posts', () => { const state = posts({ items: [] }, requestPosts()); expect(state.isFetching).toBe(true); }); it('handles request errors', () => { const state = posts( { items: [], isFetching: true }, requestPostsError(), ); expect(state.isFetching).toBe(false); });