text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add fabric task for Quora example
# coding: utf-8 from __future__ import unicode_literals, print_function from fabric.api import task, local, run, lcd, cd, env, shell_env from fabtools.python import virtualenv from _util import PWD, VENV_DIR @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def quora(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('pip install spacy') local('python -m spacy.en.download') local('python examples/quora_similarity.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
# coding: utf-8 from __future__ import unicode_literals, print_function from fabric.api import task, local, run, lcd, cd, env, shell_env from fabtools.python import virtualenv from _util import PWD, VENV_DIR @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
Fix user name addition to props
from flask import render_template from flask_login import current_user from goodtablesio import settings # Module API def render_component(component, props=None): """Render frontend component within html layout. Args: component (str): component name props (dict): component props Returns: str: rendered component """ filename = 'index.min.html' if settings.DEBUG: filename = 'index.html' if not props: props = {} # Common props if props == {} or (props and 'userName' not in props): user_name = getattr(current_user, 'display_name') if not user_name: user_name = getattr(current_user, 'name') props['userName'] = user_name return render_template( filename, component=component, props=props.copy(), google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
from flask import render_template from flask_login import current_user from goodtablesio import settings # Module API def render_component(component, props=None): """Render frontend component within html layout. Args: component (str): component name props (dict): component props Returns: str: rendered component """ filename = 'index.min.html' if settings.DEBUG: filename = 'index.html' if not props: props = {} # Common props if props == {} or (props and 'userName' not in props): user_name = getattr(current_user, 'display_name', getattr(current_user, 'name', None)) props['userName'] = user_name return render_template( filename, component=component, props=props.copy(), google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
Fix problem with system asking if you want to send empty answer This happens even tough you've written an answer. The problem was that we've made a change to how the text-value state is set. Previously it was set with the setState() function. However since text-value is the component's default state the updateVisual() function is called. This means that the element's value is reset. This caused in some browsers the caret to be reset to first position. Since the text-value is updated on keyup it caret was reset on every keyboard click. The idea was to solve this by setting the text-value directory in the state list. This then makes sure updateVisual() is not called. However the first commit did not make the proper change instead the change that was made caused the system to ask if the user wants to send an empty answer when the send button was clicked because it thought nothing had been entered in the text box.
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('keyup', function() { self._states['text-value'] = self.node().value; }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('keyup', function() { self.setState('text-value', self._states['text-value'] = self.node().value); }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
Return inverse boolean of contains for ExecutableExists.
package codeutilsShared import ( "os" "os/exec" "strings" ) // ExecCommand executes a utility with args and returning the stringified output func ExecCommand(utility string, args []string, liveOutput bool) string { var output []byte runner := exec.Command(utility, args...) if liveOutput { // If we should immediately output the results of the command runner.Stdout = os.Stdout runner.Stderr = os.Stderr runner.Start() } else { // If we should redirect output to var output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout } return string(output[:]) } // ExecutableExists checks if an executable exists func ExecutableExists(executableName string) bool { var emptyFlags []string executableCommandMessage := ExecCommand("which "+executableName, emptyFlags, false) // Generate an empty call to the executable return !strings.Contains(executableCommandMessage, executableName+" not found") // If executable does not exist }
package codeutilsShared import ( "os" "os/exec" "strings" ) // ExecCommand executes a utility with args and returning the stringified output func ExecCommand(utility string, args []string, liveOutput bool) string { var output []byte runner := exec.Command(utility, args...) if liveOutput { // If we should immediately output the results of the command runner.Stdout = os.Stdout runner.Stderr = os.Stderr runner.Start() } else { // If we should redirect output to var output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout } return string(output[:]) } // ExecutableExists checks if an executable exists func ExecutableExists(executableName string) bool { var emptyFlags []string executableCommandMessage := ExecCommand("which " + executableName, emptyFlags, false) // Generate an empty call to the executable return strings.Contains(executableCommandMessage, executableName + " not found") // If executable does not exist }
Remove `keys` from the TBot struct. The keys struct is not needed after we have initialized the bot.
package twitterbot import ( "fmt" "time" "github.com/ChimeraCoder/anaconda" ) type TBot struct { api *anaconda.TwitterApi } func New(config string) (*TBot, error) { keys, err := ReadConfig(config) if err != nil { return nil, err } anaconda.SetConsumerKey(keys.consumerPublic) anaconda.SetConsumerSecret(keys.consumerSecret) api := anaconda.NewTwitterApi(keys.accessPublic, keys.accessSecret) return &TBot{api}, nil } type TweetCreator interface { NextTweet() string } func (t *TBot) Run(creator TweetCreator) { var previousTweet string for { tweet := creator.NextTweet() if previousTweet == "" || previousTweet != tweet { fmt.Println("[" + time.Now().Format(time.RFC850) + "] Posting " + tweet) t.api.PostTweet(tweet, nil) previousTweet = tweet } fmt.Println("[" + time.Now().Format(time.RFC850) + "] Sleeping...") time.Sleep(10 * time.Minute) } }
package twitterbot import ( "fmt" "time" "github.com/ChimeraCoder/anaconda" ) type TBot struct { api *anaconda.TwitterApi keys *Keys } func New(config string) (*TBot, error) { keys, err := ReadConfig(config) if err != nil { return nil, err } anaconda.SetConsumerKey(keys.consumerPublic) anaconda.SetConsumerSecret(keys.consumerSecret) api := anaconda.NewTwitterApi(keys.accessPublic, keys.accessSecret) return &TBot{api, keys}, nil } type TweetCreator interface { NextTweet() string } func (t *TBot) Run(creator TweetCreator) { var previousTweet string for { tweet := creator.NextTweet() if previousTweet == "" || previousTweet != tweet { fmt.Println("[" + time.Now().Format(time.RFC850) + "] Posting " + tweet) t.api.PostTweet(tweet, nil) previousTweet = tweet } fmt.Println("[" + time.Now().Format(time.RFC850) + "] Sleeping...") time.Sleep(10 * time.Minute) } }
Fix duplicate users during tests
from builtins import object import factory from django.contrib.auth.models import Group from bluebottle.members.models import Member class BlueBottleUserFactory(factory.DjangoModelFactory): class Meta(object): model = Member username = factory.Sequence(lambda n: u'user_{0}'.format(n)) email = factory.Sequence(lambda o: u'user_{0}@onepercentclub.com'.format(o)) first_name = factory.Sequence(lambda f: u'user_{0}'.format(f)) last_name = factory.Sequence(lambda l: u'user_{0}'.format(l)) is_active = True is_staff = False is_superuser = False @classmethod def _create(cls, model_class, *args, **kwargs): user = super(BlueBottleUserFactory, cls)._create(model_class, *args, **kwargs) # ensure the raw password gets set after the initial save password = kwargs.pop("password", None) if password: user.set_password(password) user.save() return user class GroupFactory(factory.DjangoModelFactory): class Meta(object): model = Group name = factory.Sequence(lambda n: u'group_{0}'.format(n))
from builtins import object import factory from django.contrib.auth.models import Group from bluebottle.members.models import Member class BlueBottleUserFactory(factory.DjangoModelFactory): class Meta(object): model = Member username = factory.Faker('email') email = factory.Faker('email') first_name = factory.Sequence(lambda f: u'user_{0}'.format(f)) last_name = factory.Sequence(lambda l: u'user_{0}'.format(l)) is_active = True is_staff = False is_superuser = False @classmethod def _create(cls, model_class, *args, **kwargs): user = super(BlueBottleUserFactory, cls)._create(model_class, *args, **kwargs) # ensure the raw password gets set after the initial save password = kwargs.pop("password", None) if password: user.set_password(password) user.save() return user class GroupFactory(factory.DjangoModelFactory): class Meta(object): model = Group name = factory.Sequence(lambda n: u'group_{0}'.format(n))
Add CWD to config search path
<?php use Symfony\Component\DependencyInjection\ContainerBuilder; use Inanimatt\SiteBuilder\TransformerCompilerPass; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\DelegatingLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; (@include_once __DIR__ . '/../vendor/autoload.php') || @include_once __DIR__ . '/../../../autoload.php'; // Set up the service container $sc = new ContainerBuilder; $sc->addCompilerPass(new TransformerCompilerPass); $searchPath = array(getcwd(), __DIR__, __DIR__.'/..'); if (defined('SITEBUILDER_ROOT')) { array_unshift($searchPath, SITEBUILDER_ROOT); } $locator = new FileLocator($searchPath); $resolver = new LoaderResolver(array( new YamlFileLoader($sc, $locator), new IniFileLoader($sc, $locator), )); $loader = new DelegatingLoader($resolver); $loader->load('services.yml'); $sc->compile(); return $sc;
<?php use Symfony\Component\DependencyInjection\ContainerBuilder; use Inanimatt\SiteBuilder\TransformerCompilerPass; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\DelegatingLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\IniFileLoader; (@include_once __DIR__ . '/../vendor/autoload.php') || @include_once __DIR__ . '/../../../autoload.php'; // Set up the service container $sc = new ContainerBuilder; $sc->addCompilerPass(new TransformerCompilerPass); $searchPath = array(__DIR__, __DIR__.'/..'); if (defined('SITEBUILDER_ROOT')) { array_unshift($searchPath, SITEBUILDER_ROOT); } $locator = new FileLocator($searchPath); $resolver = new LoaderResolver(array( new YamlFileLoader($sc, $locator), new IniFileLoader($sc, $locator), )); $loader = new DelegatingLoader($resolver); $loader->load('services.yml'); $sc->compile(); return $sc;
Set static property visibility to public
<?php namespace Ams\Composer\GitHooks; class GitHooks { const SAMPLE = '.sample'; public static $hookFilename = [ 'applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-commit', 'prepare-commit-msg', 'commit-msg', 'post-commit', 'pre-rebase', 'post-checkout', 'post-merge', 'pre-push', 'pre-receive', 'update', 'post-receive', 'post-update', 'pre-auto-gc', 'post-rewrite', ]; }
<?php namespace Ams\Composer\GitHooks; class GitHooks { const SAMPLE = '.sample'; static $hookFilename = [ 'applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-commit', 'prepare-commit-msg', 'commit-msg', 'post-commit', 'pre-rebase', 'post-checkout', 'post-merge', 'pre-push', 'pre-receive', 'update', 'post-receive', 'post-update', 'pre-auto-gc', 'post-rewrite', ]; }
Fix body size limiter middleware.
var log = require('util/log'); function attachMiddleware(maxSize) { return function bodyDecoder(req, res, next) { var cl, bodyLen = 0; cl = req.headers['content-length']; if (cl) { cl = parseInt(cl, 10); if (cl >= maxSize) { log.info('Denying client for too large content length'); res.writeHead(413, {Connection: 'close'}); res.end(); req.socket.destroy(); } } req.setEncoding('utf8'); req.on('data', function(chunk) { bodyLen += chunk.length; if (bodyLen >= maxSize) { log.info('Denying client for body too large'); res.writeHead(413, {Connection: 'close'}); res.end(); req.socket.destroy(); } }); next(); }; } exports.attachMiddleware = attachMiddleware;
var log = require('util/log'); function attachMiddleware(maxSize) { return function bodyDecoder(req, res, next) { var cl, bodyLen = 0; cl = req.headers['content-length']; if (cl) { cl = parseInt(cl, 10); if (cl >= maxSize) { log.msg('Denying client for too large content length', {content_length: cl, max: maxSize}); res.writeHead(413, {Connection: 'close'}); res.end(); req.transport.close(); } } req.setEncoding('utf8'); req.on('data', function(chunk) { bodyLen += chunk.length; if (bodyLen >= maxSize) { log.msg('Denying client for body too large', {content_length: bodyLen, max: maxSize}); res.writeHead(413, {Connection: 'close'}); res.end(); req.transport.close(); } }); next(); }; } exports.attachMiddleware = attachMiddleware;
Update for 1.11.0 and 1.12.0-beta.1.
var path = require('path'); var fs = require('fs'); function config(options){ var configFile = path.join(options.project.root, 'config', 'ember-try.js'); if(fs.existsSync(configFile)){ return require(configFile); } else { return defaultConfig(); } } module.exports = config; function defaultConfig(){ return { scenarios: [ { name: 'ember-1.10', dependencies: { "ember": "1.10.0" } }, { name: 'ember-1.11.0', dependencies: { "ember": "1.11.0" } }, { name: 'ember-1.12.0-beta.1', dependencies: { "ember": "1.12.0-beta.1" } } ] } }
var path = require('path'); var fs = require('fs'); function config(options){ var configFile = path.join(options.project.root, 'config', 'ember-try.js'); if(fs.existsSync(configFile)){ return require(configFile); } else { return defaultConfig(); } } module.exports = config; function defaultConfig(){ return { scenarios: [ { name: 'ember-1.10', dependencies: { "ember": "1.10.0" } }, { name: 'ember-1.11.0-beta.5', dependencies: { "ember": "1.11.0-beta.5" } } ] } }
Enable embedding/saving to basket "info" components in BackendUtils
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), INFO("info"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(BUBBLE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(TREE.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(INFO.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(BUBBLE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(TREE.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
Move matplotlib import into function I think importing it at the top-level causes a conflict with our global matplotlib backend settings
# Color palette returns an array of colors (rainbow) import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) :param num: int :return colors: list """ from matplotlib import pyplot as plt # If a previous palette is saved, return it if params.saved_color_scale is not None: return params.saved_color_scale else: # Retrieve the matplotlib colormap cmap = plt.get_cmap(params.color_scale) # Get num evenly spaced colors colors = cmap(np.linspace(0, 1, num), bytes=True) colors = colors[:, 0:3].tolist() # colors are sequential, if params.color_sequence is random then shuffle the colors if params.color_sequence == "random": np.random.shuffle(colors) # Save the color scale for further use params.saved_color_scale = colors return colors
# Color palette returns an array of colors (rainbow) from matplotlib import pyplot as plt import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) :param num: int :return colors: list """ # If a previous palette is saved, return it if params.saved_color_scale is not None: return params.saved_color_scale else: # Retrieve the matplotlib colormap cmap = plt.get_cmap(params.color_scale) # Get num evenly spaced colors colors = cmap(np.linspace(0, 1, num), bytes=True) colors = colors[:, 0:3].tolist() # colors are sequential, if params.color_sequence is random then shuffle the colors if params.color_sequence == "random": np.random.shuffle(colors) # Save the color scale for further use params.saved_color_scale = colors return colors
Add uv.mail validation with email and notempty
package org.synyx.urlaubsverwaltung.mail.config; import org.hibernate.validator.constraints.URL; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; @Validated @ConfigurationProperties(prefix = "uv.mail") public class UrlaubsverwaltungMailConfigurationProperties { @Email @NotEmpty private String sender; @Email @NotEmpty private String administrator; @URL private String applicationUrl; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getAdministrator() { return administrator; } public void setAdministrator(String administrator) { this.administrator = administrator; } public String getApplicationUrl() { return applicationUrl; } public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } }
package org.synyx.urlaubsverwaltung.mail.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotEmpty; @Validated @ConfigurationProperties(prefix = "uv.mail") public class UrlaubsverwaltungMailConfigurationProperties { @NotEmpty private String sender; @NotEmpty private String administrator; @NotEmpty private String applicationUrl; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getAdministrator() { return administrator; } public void setAdministrator(String administrator) { this.administrator = administrator; } public String getApplicationUrl() { return applicationUrl; } public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } }
Correct URL for user stories collection
define([ 'backbone', 'moment', 'connect/models/Story' ], function(Backbone, moment, Story) { 'use strict'; var Stories = Backbone.Collection.extend({ model: Story, url: window.gfw.config.GFW_API_HOST_NEW_API + '/user/stories', comparator: function(subscription) { return -moment(subscription.get('created')).unix(); }, sync: function(method, model, options) { options || (options = {}); if (!options.crossDomain) { options.crossDomain = true; } if (!options.xhrFields) { options.xhrFields = {withCredentials:true}; } return Backbone.sync.call(this, method, model, options); }, parse: function(response) { return response.data; } }); return Stories; });
define([ 'backbone', 'moment', 'connect/models/Story' ], function(Backbone, moment, Story) { 'use strict'; var Stories = Backbone.Collection.extend({ model: Story, //url: window.gfw.config.GFW_API_HOST_V2 + '/user/stories', url: 'http://api-gateway.globalforestwatch.dev:8000/story/user/57736ba451b9ca1300e39430', comparator: function(subscription) { return -moment(subscription.get('created')).unix(); }, sync: function(method, model, options) { options || (options = {}); if (!options.crossDomain) { options.crossDomain = true; } if (!options.xhrFields) { options.xhrFields = {withCredentials:true}; } return Backbone.sync.call(this, method, model, options); }, parse: function(response) { return response.data; } }); return Stories; });
Remove duplicated JSON encoding for error messages
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES', None) if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if ok and not details: details = 'There were no checks.' if not ok: return JsonResponseServerError(details) return JsonResponse(details)
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES', None) if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if ok and not details: details = 'There were no checks.' if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
Fix KaTeX breaking stuff sometimes
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { try { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; } catch (e) { return `<blockquote class="katex-block">${e.message}</blockquote>`; } }; renderer.codespan = function(code) { try { return katex.renderToString(code, katexOpts); } catch (e) { return e.message; } }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.getSession().setUseWrapMode(true); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); event.preventDefault(); return false; } };
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; }; renderer.codespan = function(code) { return katex.renderToString(code, katexOpts); }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.getSession().setUseWrapMode(true); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); event.preventDefault(); return false; } };
Increase the number of map/reduce tasks.
package org.slc.sli.stamper.jobs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slc.sli.stamper.mapreduce.map.ConfigurableMapReduceJob; public class Stamper extends Configured implements Tool { public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new Stamper(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { Configuration conf = new Configuration(); JobConf jobConf = ConfigurableMapReduceJob.parseMapper(conf, "stamper.json"); jobConf.setNumMapTasks(30); jobConf.setNumReduceTasks(6); jobConf.setMemoryForMapTask(4096); jobConf.setMemoryForReduceTask(8192); Job job = new Job(jobConf); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } }
package org.slc.sli.stamper.jobs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slc.sli.stamper.mapreduce.map.ConfigurableMapReduceJob; public class Stamper extends Configured implements Tool { public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new Stamper(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { Configuration conf = new Configuration(); JobConf jobConf = ConfigurableMapReduceJob.parseMapper(conf, "stamper.json"); Job job = new Job(jobConf); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } }
Add Comment to RepoExistanceValidator test and correct test name
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms # ############################################################################### ''' from ..forms import InvestmentModelForm class InvestmentModelFormTestCase(TestCase): """ Tests for InvestmentModelForm """ def test_initial_value_of_investor_type(self): """ Verify initial value of investor_type field of InvestmentModelForm. """ investor_type_initial = InvestmentModelForm().fields["investor_type"].initial self.assertEqual(investor_type_initial, "PERSON") ''' ############################################################################### # Validators # ############################################################################### # Test takes longer than average test because of requests call #@unittest.skip("") class RepoExistanceValidatorTestCase(django.test.TestCase): def test_repo_existance_validator(self): user_rob = RobrechtSocialUserFactory() self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms # ############################################################################### ''' from ..forms import InvestmentModelForm class InvestmentModelFormTestCase(TestCase): """ Tests for InvestmentModelForm """ def test_initial_value_of_investor_type(self): """ Verify initial value of investor_type field of InvestmentModelForm. """ investor_type_initial = InvestmentModelForm().fields["investor_type"].initial self.assertEqual(investor_type_initial, "PERSON") ''' ############################################################################### # Validators # ############################################################################### class RepoExistanceValidatorTestCase(django.test.TestCase): def test_name(self): user_rob = RobrechtSocialUserFactory() self.assertRaises(ValidationError, RepoExistanceValidator(user_rob), "asiakas/non_existing_branch")
Update dropbox module api to take file, fileNAme & user consider taking oauth_token rather than user?
'use strict'; var cp = require('child_process'); var child = cp.fork(__dirname + '/child.js'); var passport = require('passport'); var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy; var active = false; module.exports = function (options) { child.send({ options: options.dropbox }); return { initialize: function () { active = true; passport.use(new DropboxOAuth2Strategy({ clientID: options.dropbox.id, clientSecret: options.dropbox.secret, callbackURL: 'https://jsbin.dev/auth/dropbox/callback' }, function (accessToken, refreshToken, profile, done) { done(null, profile); } )); } }; }; module.exports.saveBin = function (file, fileName, user) { if (!active) { return; } child.send({ file: file, fileName: fileName, user: user }); };
'use strict'; var cp = require('child_process'); var child = cp.fork(__dirname + '/child.js'); var passport = require('passport'); var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy; var active = false; module.exports = function (options) { child.send({ options: options.dropbox }); return { initialize: function () { active = true; passport.use(new DropboxOAuth2Strategy({ clientID: options.dropbox.id, clientSecret: options.dropbox.secret, callbackURL: 'https://jsbin.dev/auth/dropbox/callback' }, function (accessToken, refreshToken, profile, done) { done(null, profile); } )); } }; }; module.exports.saveBin = function (bin, user) { if (!active) { return; } child.send({ bin: bin, user: user }); };
Fix another path case inconsistency
import _ from 'lodash' import axios from 'axios' import moment from 'moment' import Vue from 'vue' import {assert, expect} from 'chai' import moxios from 'moxios' // Emulate browser globals global._ = _; global.axios = axios; global.moment = moment; global.Vue = Vue; // Fail if there's an unhandled promise rejection warning. process.on('unhandledRejection', (error, promise) => { console.error('Unhandled promise rejection', {error, promise}) process.exit(1); }); // Structures require('./Structures/Model.spec.js'); require('./Structures/Collection.spec.js') // Validation require('./Validation/Rule.spec.js') require('./Validation/Rules.spec.js') require('./Validation/Messages.spec.js') // HTTP require('./HTTP/ProxyResponse.spec.js') // Errors require('./Errors/RequestError.spec.js') require('./Errors/ResponseError.spec.js') require('./Errors/ValidationError.spec.js')
import _ from 'lodash' import axios from 'axios' import moment from 'moment' import Vue from 'vue' import {assert, expect} from 'chai' import moxios from 'moxios' // Emulate browser globals global._ = _; global.axios = axios; global.moment = moment; global.Vue = Vue; // Fail if there's an unhandled promise rejection warning. process.on('unhandledRejection', (error, promise) => { console.error('Unhandled promise rejection', {error, promise}) process.exit(1); }); // require('./Structures/Model.spec.js'); require('./Structures/Collection.spec.js') // require('./Validation/rule.spec.js') require('./Validation/rules.spec.js') require('./Validation/messages.spec.js') // require('./HTTP/ProxyResponse.spec.js') // require('./Errors/RequestError.spec.js') require('./Errors/ResponseError.spec.js') require('./Errors/ValidationError.spec.js')
Include loader tests in test suite
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from couchdb.tests import client, couch_tests, design, couchhttp, \ multipart, mapping, view, package, tools, \ loader def suite(): suite = unittest.TestSuite() suite.addTest(client.suite()) suite.addTest(design.suite()) suite.addTest(couchhttp.suite()) suite.addTest(multipart.suite()) suite.addTest(mapping.suite()) suite.addTest(view.suite()) suite.addTest(couch_tests.suite()) suite.addTest(package.suite()) suite.addTest(tools.suite()) suite.addTest(loader.suite()) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from couchdb.tests import client, couch_tests, design, couchhttp, \ multipart, mapping, view, package, tools def suite(): suite = unittest.TestSuite() suite.addTest(client.suite()) suite.addTest(design.suite()) suite.addTest(couchhttp.suite()) suite.addTest(multipart.suite()) suite.addTest(mapping.suite()) suite.addTest(view.suite()) suite.addTest(couch_tests.suite()) suite.addTest(package.suite()) suite.addTest(tools.suite()) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
Ch05: Use attribute for template in Post List.
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()})
Include SUIR JS on logs page This is not pretty, as we don't even use SUIR there, but indico/utils/redux imports a module that imports SUIR and thus breaks the logs page if SUIR is not included.
# This file is part of Indico. # Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from indico.modules.events.management.views import WPEventManagement class WPEventLogs(WPEventManagement): bundles = ('react.js', 'semantic-ui.js', 'module_events.logs.js', 'module_events.logs.css') template_prefix = 'events/logs/' sidemenu_option = 'logs'
# This file is part of Indico. # Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from indico.modules.events.management.views import WPEventManagement class WPEventLogs(WPEventManagement): bundles = ('react.js', 'module_events.logs.js', 'module_events.logs.css') template_prefix = 'events/logs/' sidemenu_option = 'logs'
Use buffer pointer instead of buffer in azure blob storage
package acr import ( "bufio" "bytes" "fmt" "github.com/pkg/errors" "io" "net/http" "time" ) const VERSION = "2018-03-28" type AzureBlobStorage struct { UploadUrl string Bytes *bytes.Buffer } func NewBlobStorage(url string) AzureBlobStorage { return AzureBlobStorage{ UploadUrl: url, Bytes: new(bytes.Buffer), } } func (s *AzureBlobStorage) Writer() io.Writer { return bufio.NewWriter(s.Bytes) } func (s AzureBlobStorage) UploadFileToBlob() error { req, err := http.NewRequest("PUT", s.UploadUrl, s.Bytes) if err != nil { return err } req.Header.Add("x-ms-blob-type", "BlockBlob") req.Header.Add("x-ms-version", VERSION) req.Header.Add("x-ms-date", time.Now().String()) req.Header.Add("Content-Length", fmt.Sprint(s.Bytes.Len())) client := http.Client{} response, err := client.Do(req) if err != nil { return err } if response.StatusCode != http.StatusCreated { return errors.New("couldn't file to blob.") } return nil }
package acr import ( "bufio" "bytes" "github.com/pkg/errors" "io" "net/http" "time" ) const VERSION = "2018-03-28" type AzureBlobStorage struct { UploadUrl string Bytes bytes.Buffer } func NewBlobStorage(url string) AzureBlobStorage { return AzureBlobStorage{ UploadUrl: url, } } func (s AzureBlobStorage) Writer() io.Writer { return bufio.NewWriter(&s.Bytes) } func (s AzureBlobStorage) UploadFileToBlob() error { req, err := http.NewRequest("PUT", s.UploadUrl, bytes.NewBuffer(s.Bytes.Bytes())) if err != nil { return err } req.Header.Add("x-ms-blob-type", "BlockBlob") req.Header.Add("x-ms-version", VERSION) req.Header.Add("x-ms-date", time.Now().String()) req.Header.Add("Content-Length", string(s.Bytes.Len())) client := http.Client{} response, err := client.Do(req) if err != nil { return err } if response.StatusCode != http.StatusCreated { return errors.New("couldn't file to blob.") } return nil }
Fix templateUrl: use a relative path instead of absolute path
angular.module('myApp.games', []) .directive('buttonClickGame', function() { return { restrict: 'E', templateUrl: 'partials/buttonClick.html', controller: function($scope) { $scope.maxTaps = 20; $scope.progress = [ { name: 'Sarah', taps: 5 }, { name: 'Laurent', taps: 10 } ]; $scope.range = function(min, max) { var input = []; for (var i = min; i <= max; i++) { input.push(i); } return input; }; } }; });
angular.module('myApp.games', []) .directive('buttonClickGame', function() { return { restrict: 'E', templateUrl: '/app/partials/buttonClick.html', controller: function($scope) { $scope.maxTaps = 20; $scope.progress = [ { name: 'Sarah', taps: 5 }, { name: 'Laurent', taps: 10 } ]; $scope.range = function(min, max) { var input = []; for (var i = min; i <= max; i++) { input.push(i); } return input; }; } }; });
Add a few functions to Socket class
import socket class Socket: TCP = 0 UDP = 1 def __init__(self, type): if type == self.TCP: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) else: self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.s.setblocking(False) def connect(self, host, port): self.s.connect((host, port)) def close(self): self.s.close() def send(self, data): self.s.sendall(data) def recv(self, num): try: return self.s.recv(num) except BlockingIOError: pass def bind(self, addr=("", 0)): self.s.bind(addr) def sendto(self, data, addr): self.s.sendto(data, addr) def recvfrom(self, num): try: return self.s.recvfrom(num) except BlockingIOError: return None, None def get_address(self): return self.s.getsockname()[0] def get_port(self): return self.s.getsockname()[1]
import socket class Socket: TCP = 0 UDP = 1 def __init__(self, type): if type == self.TCP: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) else: self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.s.setblocking(False) def connect(self, host, port): self.s.connect((host, port)) def close(self): self.s.close() def send(self, data): self.s.sendall(data) def recv(self, num): try: return self.s.recv(num) except BlockingIOError: pass def get_address(self): return self.s.getsockname()[0] def get_port(self): return self.s.getsockname()[1]
download: Tweak URL-with-key logic to be a bit more defensive. It's not entirely obvious whether it's possible for the `src` URL to already have a query part, in which case we should be using `&` rather than `?` as the delimiter. Rather than make and justify an assumption that that can't happen, borrow the logic we have for handling this in `appendAuthToImages` in js.js. There isn't currently an easy way to share the actual code between these places (one inside the webview, one in the main RN environment), so that means copying. Fortunately this is a tiny amount of code and its logic isn't likely to need to change, so that isn't so bad.
/* @flow */ import { CameraRoll, Platform } from 'react-native'; import RNFetchBlob from 'rn-fetch-blob'; import type { Auth } from './apiTypes'; import { getAuthHeader, getFullUrl } from '../utils/url'; import userAgent from '../utils/userAgent'; export default (src: string, auth: Auth) => { const absoluteUrl = getFullUrl(src, auth.realm); if (Platform.OS === 'ios') { const delimiter = absoluteUrl.includes('?') ? '&' : '?'; const urlWithApiKey = `${absoluteUrl}${delimiter}api_key=${auth.apiKey}`; return CameraRoll.saveToCameraRoll(urlWithApiKey); } return RNFetchBlob.config({ addAndroidDownloads: { path: `${RNFetchBlob.fs.dirs.DownloadDir}/${src.split('/').pop()}`, useDownloadManager: true, mime: 'text/plain', // Android DownloadManager fails if the url is missing a file extension title: src.split('/').pop(), notification: true, }, }).fetch('GET', absoluteUrl, { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': userAgent, Authorization: getAuthHeader(auth.email, auth.apiKey), }); };
/* @flow */ import { CameraRoll, Platform } from 'react-native'; import RNFetchBlob from 'rn-fetch-blob'; import type { Auth } from './apiTypes'; import { getAuthHeader, getFullUrl } from '../utils/url'; import userAgent from '../utils/userAgent'; export default (src: string, auth: Auth) => { const fullUrlWithAPIKey = `${getFullUrl(src, auth.realm)}?api_key=${auth.apiKey}`; if (Platform.OS === 'ios') { return CameraRoll.saveToCameraRoll(fullUrlWithAPIKey); } return RNFetchBlob.config({ addAndroidDownloads: { path: `${RNFetchBlob.fs.dirs.DownloadDir}/${src.split('/').pop()}`, useDownloadManager: true, mime: 'text/plain', // Android DownloadManager fails if the url is missing a file extension title: src.split('/').pop(), notification: true, }, }).fetch('GET', getFullUrl(src, auth.realm), { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': userAgent, Authorization: getAuthHeader(auth.email, auth.apiKey), }); };
Add assert to prevent regression
'use strict'; const assertJump = require('./helpers/assertJump'); var Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); contract('Ownable', function(accounts) { let ownable; beforeEach(async function() { ownable = await Ownable.new(); }); it('should have an owner', async function() { let owner = await ownable.owner(); assert.isTrue(owner !== 0); }); it('changes owner after transfer', async function() { let other = accounts[1]; await ownable.transferOwnership(other); let owner = await ownable.owner(); assert.isTrue(owner === other); }); it('should prevent non-owners from transfering', async function() { const other = accounts[2]; const owner = await ownable.owner.call(); assert.isTrue(owner !== other); try { await ownable.transferOwnership(other, {from: other}); } catch(error) { assertJump(error); } }); it('should guard ownership against stuck state', async function() { let originalOwner = await ownable.owner(); try { await ownable.transferOwnership(null, {from: originalOwner}); assert.fail() } catch(error) { assertJump(error); } }); });
'use strict'; const assertJump = require('./helpers/assertJump'); var Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); contract('Ownable', function(accounts) { let ownable; beforeEach(async function() { ownable = await Ownable.new(); }); it('should have an owner', async function() { let owner = await ownable.owner(); assert.isTrue(owner !== 0); }); it('changes owner after transfer', async function() { let other = accounts[1]; await ownable.transferOwnership(other); let owner = await ownable.owner(); assert.isTrue(owner === other); }); it('should prevent non-owners from transfering', async function() { const other = accounts[2]; const owner = await ownable.owner.call(); assert.isTrue(owner !== other); try { await ownable.transferOwnership(other, {from: other}); } catch(error) { assertJump(error); } }); it('should guard ownership against stuck state', async function() { let originalOwner = await ownable.owner(); try { await ownable.transferOwnership(null, {from: originalOwner}); } catch(error) { assertJump(error); } }); });
Test app now creates dummy id if none is specified.
package com.albin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.albin.mqtt.NettyClient; public class NettyMain { private static NettyClient client; private static String topic; public static void main(String[] args) throws InterruptedException, IOException { String id = args.length == 0 ? "Dummy_"+System.currentTimeMillis() : args[0]; client = new NettyClient(id); client.connect(); beInteractive(); client.disconnect(); } private static void beInteractive() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; do { line = in.readLine(); if (line.startsWith("pub")) publish(line.substring(4)); if (line.startsWith("sub")) subscribe(line.substring(4)); if (line.startsWith("unsub")) unsubscribe(line.substring(6)); if (line.startsWith("topic")) { topic = line.substring(6); } } while(!"bye".equals(line)); } private static void unsubscribe(String topic) { client.unsubscribe(topic); } private static void subscribe(String topic) { client.subscribe(topic); } private static void publish(String msg) { client.publish(topic, msg); } }
package com.albin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.albin.mqtt.NettyClient; public class NettyMain { private static NettyClient client; private static String topic; public static void main(String[] args) throws InterruptedException, IOException { client = new NettyClient(args[0]); client.connect(); beInteractive(); client.disconnect(); } private static void beInteractive() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; do { line = in.readLine(); if (line.startsWith("pub")) publish(line.substring(4)); if (line.startsWith("sub")) subscribe(line.substring(4)); if (line.startsWith("unsub")) unsubscribe(line.substring(6)); if (line.startsWith("topic")) { topic = line.substring(6); } } while(!"bye".equals(line)); } private static void unsubscribe(String topic) { client.unsubscribe(topic); } private static void subscribe(String topic) { client.subscribe(topic); } private static void publish(String msg) { client.publish(topic, msg); } }
Add a comment explaining -kb.
#! -*- coding: koi8-r -*- # This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest from test import test_support class PEP263Test(unittest.TestCase): def test_pep263(self): self.assertEqual( u"".encode("utf-8"), '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( u"\".encode("utf-8"), '\\\xd0\x9f' ) def test_main(): test_support.run_unittest(PEP263Test) if __name__=="__main__": test_main()
#! -*- coding: koi8-r -*- import unittest from test import test_support class PEP263Test(unittest.TestCase): def test_pep263(self): self.assertEqual( u"".encode("utf-8"), '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( u"\".encode("utf-8"), '\\\xd0\x9f' ) def test_main(): test_support.run_unittest(PEP263Test) if __name__=="__main__": test_main()
Replace Edge interface with basic struct, add Size and Order methods.
// gogl provides a framework for representing and working with graphs. package gogl // Constants defining graph capabilities and behaviors. const ( E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1 E_UNDIRECTED, EM_UNDIRECTED E_WEIGHTED, EM_WEIGHTED E_TYPED, EM_TYPED E_SIGNED, EM_SIGNED E_LOOPS, EM_LOOPS E_MULTIGRAPH, EM_MULTIGRAPH ) type Vertex interface{} type Edge struct { Tail, Head Vertex } type Graph interface { EachVertex(f func(vertex Vertex)) EachEdge(f func(edge Edge)) EachAdjacent(vertex Vertex, f func(adjacent Vertex)) HasVertex(vertex Vertex) bool Order() uint Size() uint GetSubgraph([]Vertex) Graph } type MutableGraph interface { Graph AddVertex(v interface{}) bool RemoveVertex(v interface{}) bool } type DirectedGraph interface { Graph Transpose() DirectedGraph IsAcyclic() bool GetCycles() [][]interface{} } type MutableDirectedGraph interface { MutableGraph DirectedGraph addDirectedEdge(source interface{}, target interface{}) bool removeDirectedEdge(source interface{}, target interface{}) bool }
// gogl provides a framework for representing and working with graphs. package gogl // Constants defining graph capabilities and behaviors. const ( E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1 E_UNDIRECTED, EM_UNDIRECTED E_WEIGHTED, EM_WEIGHTED E_TYPED, EM_TYPED E_SIGNED, EM_SIGNED E_LOOPS, EM_LOOPS E_MULTIGRAPH, EM_MULTIGRAPH ) type Vertex interface{} type Graph interface { EachVertex(f func(vertex Vertex)) EachEdge(f func(source Vertex, target Vertex)) EachAdjacent(vertex Vertex, f func(adjacent Vertex)) HasVertex(vertex Vertex) bool GetSubgraph([]Vertex) Graph } type MutableGraph interface { Graph AddVertex(v interface{}) bool RemoveVertex(v interface{}) bool } type DirectedGraph interface { Graph Transpose() DirectedGraph IsAcyclic() bool GetCycles() [][]interface{} } type MutableDirectedGraph interface { MutableGraph DirectedGraph addDirectedEdge(source interface{}, target interface{}) bool removeDirectedEdge(source interface{}, target interface{}) bool } type Edge interface { Tail() Vertex Head() Vertex }
Add i3pystatus.weather to packages list
#!/usr/bin/env python from setuptools import setup setup(name="i3pystatus", version="3.34", description="A complete replacement for i3status", url="http://github.com/enkore/i3pystatus", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", "Topic :: Desktop Environment :: Window Managers", ], packages=[ "i3pystatus", "i3pystatus.core", "i3pystatus.tools", "i3pystatus.mail", "i3pystatus.pulseaudio", "i3pystatus.updates", "i3pystatus.weather", ], entry_points={ "console_scripts": [ "i3pystatus = i3pystatus:main", "i3pystatus-setting-util = i3pystatus.tools.setting_util:main" ] }, zip_safe=True, )
#!/usr/bin/env python from setuptools import setup setup(name="i3pystatus", version="3.34", description="A complete replacement for i3status", url="http://github.com/enkore/i3pystatus", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", "Topic :: Desktop Environment :: Window Managers", ], packages=[ "i3pystatus", "i3pystatus.core", "i3pystatus.tools", "i3pystatus.mail", "i3pystatus.pulseaudio", "i3pystatus.updates", ], entry_points={ "console_scripts": [ "i3pystatus = i3pystatus:main", "i3pystatus-setting-util = i3pystatus.tools.setting_util:main" ] }, zip_safe=True, )
Fix fieldname could be path so validation not working
var Select = require('./../index'); Select.prototype._select = function(option, index) { this.model.set('value', option[this.key]); this.model.set('selected', option); this.model.set('selectedIndex', index); this._closeOptions(); }; Select.prototype._willSelect = function() { this.model.set('selectOptionsVisible', true); }; Select.prototype._adjustDropdown = function() { var index = this.model.get('selectedIndex'); var ul = this.optionListDropdown; if (index > 2) { index = index - 2; ul.scrollTop = (index * 40); } else { ul.scrollTop = 0; } }; Select.prototype._addCloseListener = function () { var self = this; this.listener = function (e) { if (!self.optionListDropdown.contains(e.target)) self._closeOptions(); } document.body.addEventListener('mouseup', this.listener); }; Select.prototype._removeCloseListener = function() { document.body.removeEventListener('mouseup', this.listener); }; Select.prototype._validate = function () { if(this.validator) { var field = this.model.get('validator.' + this.fieldName); if (typeof field.validate === 'function') field.validate(); } }; Select.prototype._closeOptions = function () { this.model.set('selectOptionsVisible', false); };
var Select = require('./../index'); Select.prototype._select = function(option, index) { this.model.set('value', option[this.key]); this.model.set('selected', option); this.model.set('selectedIndex', index); this._closeOptions(); }; Select.prototype._willSelect = function() { this.model.set('selectOptionsVisible', true); }; Select.prototype._adjustDropdown = function() { var index = this.model.get('selectedIndex'); var ul = this.optionListDropdown; if (index > 2) { index = index - 2; ul.scrollTop = (index * 40); } else { ul.scrollTop = 0; } }; Select.prototype._addCloseListener = function () { var self = this; this.listener = function (e) { if (!self.optionListDropdown.contains(e.target)) self._closeOptions(); } document.body.addEventListener('mouseup', this.listener); }; Select.prototype._removeCloseListener = function() { document.body.removeEventListener('mouseup', this.listener); }; Select.prototype._validate = function () { if(this.validator && typeof this.validator[this.fieldName].validate === 'function') { this.validator[this.fieldName].validate(); } }; Select.prototype._closeOptions = function () { this.model.set('selectOptionsVisible', false); };
Add separate left and right eye data generation
#!/usr/bin/env python import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
#!/usr/bin/env python import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): data = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) data[stimulus[1] * numx + stimulus[0]] = '1' return data, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): data, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(data, data) # duplicate for two eyes scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
Fix missed safe provider calling impl method
package password import ( "github.com/sirupsen/logrus" "github.com/skygeario/skygear-server/pkg/core/db" ) type safeProviderImpl struct { impl *providerImpl txContext db.SafeTxContext } func NewSafeProvider( builder db.SQLBuilder, executor db.SQLExecutor, logger *logrus.Entry, txContext db.SafeTxContext, ) Provider { return &safeProviderImpl{ impl: newProvider(builder, executor, logger), txContext: txContext, } } func (p *safeProviderImpl) CreatePrincipal(principal Principal) error { p.txContext.EnsureTx() return p.impl.CreatePrincipal(principal) } func (p *safeProviderImpl) GetPrincipalByAuthData(authData map[string]interface{}, principal *Principal) error { p.txContext.EnsureTx() return p.impl.GetPrincipalByAuthData(authData, principal) } func (p *safeProviderImpl) GetPrincipalByUserID(userID string, principal *Principal) error { p.txContext.EnsureTx() return p.impl.GetPrincipalByUserID(userID, principal) } func (p *safeProviderImpl) UpdatePrincipal(principal Principal) error { p.txContext.EnsureTx() return p.impl.UpdatePrincipal(principal) }
package password import ( "github.com/sirupsen/logrus" "github.com/skygeario/skygear-server/pkg/core/db" ) type safeProviderImpl struct { impl *providerImpl txContext db.SafeTxContext } func NewSafeProvider( builder db.SQLBuilder, executor db.SQLExecutor, logger *logrus.Entry, txContext db.SafeTxContext, ) Provider { return &safeProviderImpl{ impl: newProvider(builder, executor, logger), txContext: txContext, } } func (p *safeProviderImpl) CreatePrincipal(principal Principal) error { p.txContext.EnsureTx() return p.CreatePrincipal(principal) } func (p *safeProviderImpl) GetPrincipalByAuthData(authData map[string]interface{}, principal *Principal) error { p.txContext.EnsureTx() return p.impl.GetPrincipalByAuthData(authData, principal) } func (p *safeProviderImpl) GetPrincipalByUserID(userID string, principal *Principal) error { p.txContext.EnsureTx() return p.impl.GetPrincipalByUserID(userID, principal) } func (p *safeProviderImpl) UpdatePrincipal(principal Principal) error { p.txContext.EnsureTx() return p.impl.UpdatePrincipal(principal) }
Make strftime filter safe for non-date types It should probably also support datetime.datetime, but since I only have datetime.date right now, that's not a pressing concern.
from jinja2._compat import text_type import datetime import re def do_right(value, width=80): """Right-justifies the value in a field of a given width.""" return text_type(value).rjust(width) _LATEX_SUBS = ( (re.compile(r'\\'), r'\\textbackslash'), (re.compile(r'([{}_#%&$])'), r'\\\1'), (re.compile(r'~'), r'\~{}'), (re.compile(r'\^'), r'\^{}'), (re.compile(r'"'), r"''"), (re.compile(r'\.\.\.+'), r'\\ldots'), (re.compile(r'&'), r'&'), (re.compile(r'LaTeX'), r'\\textrm{\\LaTeX}') ) def escape_tex(value): """ Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers. Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/ """ newval = value for pattern, replacement in _LATEX_SUBS: newval = pattern.sub(replacement, newval) return newval def strftime(value, _format="%b %Y"): """ Formats a datetime object into a string. Just a simple facade around datetime.strftime. """ if isinstance(value, datetime.date): return value.strftime(_format) else: return value
from jinja2._compat import text_type from datetime import datetime import re def do_right(value, width=80): """Right-justifies the value in a field of a given width.""" return text_type(value).rjust(width) _LATEX_SUBS = ( (re.compile(r'\\'), r'\\textbackslash'), (re.compile(r'([{}_#%&$])'), r'\\\1'), (re.compile(r'~'), r'\~{}'), (re.compile(r'\^'), r'\^{}'), (re.compile(r'"'), r"''"), (re.compile(r'\.\.\.+'), r'\\ldots'), (re.compile(r'&'), r'&'), (re.compile(r'LaTeX'), r'\\textrm{\\LaTeX}') ) def escape_tex(value): """ Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers. Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/ """ newval = value for pattern, replacement in _LATEX_SUBS: newval = pattern.sub(replacement, newval) return newval def strftime(value, _format="%b %Y"): """ Formats a datetime object into a string. Just a simple facade around datetime.strftime. """ return value.strftime(_format)
Fix encoding apostrophes in page names Former-commit-id: 764b2e7462b7fa0883f2e538611ee10957a7113a
<?php /** * Helper class for sanitizing input and escaping output. * @package Helpers * @category Concrete * @subpackage Security * @author Chris Rosser <chris@bluefuton.com> * @copyright Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org) * @license http://www.concrete5.org/license/ MIT License */ namespace Concrete\Core\Validation; class SanitizeService { public function sanitizeString($string) { return filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); } public function sanitizeInt($int) { return filter_var($int, FILTER_SANITIZE_NUMBER_INT); } public function sanitizeURL($url) { return filter_var($url, FILTER_SANITIZE_URL); } public function sanitizeEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } }
<?php /** * Helper class for sanitizing input and escaping output. * @package Helpers * @category Concrete * @subpackage Security * @author Chris Rosser <chris@bluefuton.com> * @copyright Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org) * @license http://www.concrete5.org/license/ MIT License */ namespace Concrete\Core\Validation; class SanitizeService { public function sanitizeString($string) { return filter_var($string, FILTER_SANITIZE_STRING); } public function sanitizeInt($int) { return filter_var($int, FILTER_SANITIZE_NUMBER_INT); } public function sanitizeURL($url) { return filter_var($url, FILTER_SANITIZE_URL); } public function sanitizeEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } }
Add missing lower() in create_container()
import logging import os from plumbum.commands.base import BaseCommand from benchbuild.settings import CFG from benchbuild.utils.cmd import podman LOG = logging.getLogger(__name__) PODMAN_DEFAULT_OPTS = [ '--root', os.path.abspath(str(CFG['container']['root'])), '--runroot', os.path.abspath(str(CFG['container']['runroot'])) ] def bb_podman() -> BaseCommand: return podman[PODMAN_DEFAULT_OPTS] BB_PODMAN_CONTAINER_START: BaseCommand = bb_podman()['container', 'start'] BB_PODMAN_CREATE: BaseCommand = bb_podman()['create'] BB_PODMAN_RM: BaseCommand = bb_podman()['rm'] def create_container(image_id: str, container_name: str) -> str: container_id = str( BB_PODMAN_CREATE( '--replace', '--name', container_name.lower(), image_id.lower() ) ).strip() LOG.debug('created container: %s', container_id) return container_id def run_container(name: str) -> None: LOG.debug('running container: %s', name) BB_PODMAN_CONTAINER_START['-ai', name].run_tee() def remove_container(container_id: str) -> None: BB_PODMAN_RM(container_id)
import logging import os from plumbum.commands.base import BaseCommand from benchbuild.settings import CFG from benchbuild.utils.cmd import podman LOG = logging.getLogger(__name__) PODMAN_DEFAULT_OPTS = [ '--root', os.path.abspath(str(CFG['container']['root'])), '--runroot', os.path.abspath(str(CFG['container']['runroot'])) ] def bb_podman() -> BaseCommand: return podman[PODMAN_DEFAULT_OPTS] BB_PODMAN_CONTAINER_START: BaseCommand = bb_podman()['container', 'start'] BB_PODMAN_CREATE: BaseCommand = bb_podman()['create'] BB_PODMAN_RM: BaseCommand = bb_podman()['rm'] def create_container(image_id: str, container_name: str) -> str: container_id = str( BB_PODMAN_CREATE( '--replace', '--name', container_name.lower(), image_id ) ).strip() LOG.debug('created container: %s', container_id) return container_id def run_container(name: str) -> None: LOG.debug('running container: %s', name) BB_PODMAN_CONTAINER_START['-ai', name].run_tee() def remove_container(container_id: str) -> None: BB_PODMAN_RM(container_id)
Add affected users to userhasoperpermission call in USERHOST
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class UserhostCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "UserhostCommand" core = True def userCommands(self): return [ ("USERHOST", 1, self) ] def parseParams(self, user, params, prefix, tags): if not params: user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters") return None return { "nicks": params[:5] } def execute(self, user, data): userHosts = [] for nick in data["nicks"]: if nick not in self.ircd.userNicks: continue targetUser = self.ircd.users[self.ircd.userNicks[nick]] output = targetUser.nick if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]): output += "*" output += "=" if user.metadataKeyExists("away"): output += "-" else: output += "+" output += "{}@{}".format(targetUser.ident, targetUser.host()) userHosts.append(output) user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts)) return True userhostCmd = UserhostCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class UserhostCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "UserhostCommand" core = True def userCommands(self): return [ ("USERHOST", 1, self) ] def parseParams(self, user, params, prefix, tags): if not params: user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters") return None return { "nicks": params[:5] } def execute(self, user, data): userHosts = [] for nick in data["nicks"]: if nick not in self.ircd.userNicks: continue targetUser = self.ircd.users[self.ircd.userNicks[nick]] output = targetUser.nick if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, ""): output += "*" output += "=" if user.metadataKeyExists("away"): output += "-" else: output += "+" output += "{}@{}".format(targetUser.ident, targetUser.host()) userHosts.append(output) user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts)) return True userhostCmd = UserhostCommand()
Use more Pythonic name for test.
""" Test the top-level Kafka Streams class """ import pytest from winton_kafka_streams import kafka_config from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError from winton_kafka_streams.kafka_streams import KafkaStreams from winton_kafka_streams.processor.processor import BaseProcessor from winton_kafka_streams.processor.topology import TopologyBuilder class MyTestProcessor(BaseProcessor): pass def test__given__stream_already_started__when__call_start_again__then__raise_error(): kafka_config.NUM_STREAM_THREADS = 0 topology_builder = TopologyBuilder() topology_builder.source('my-source', ['my-input-topic-1']) topology_builder.processor('my-processor', MyTestProcessor, 'my-source') topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor') topology = topology_builder.build() kafka_streams = KafkaStreams(topology, kafka_config) kafka_streams.start() with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'): kafka_streams.start()
""" Test the top-level Kafka Streams class """ import pytest from winton_kafka_streams import kafka_config from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError from winton_kafka_streams.kafka_streams import KafkaStreams from winton_kafka_streams.processor.processor import BaseProcessor from winton_kafka_streams.processor.topology import TopologyBuilder class MyTestProcessor(BaseProcessor): pass def test_Given_StreamAlreadyStarted_When_CallStartAgain_Then_RaiseError(): kafka_config.NUM_STREAM_THREADS = 0 topology_builder = TopologyBuilder() topology_builder.source('my-source', ['my-input-topic-1']) topology_builder.processor('my-processor', MyTestProcessor, 'my-source') topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor') topology = topology_builder.build() kafka_streams = KafkaStreams(topology, kafka_config) kafka_streams.start() with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'): kafka_streams.start()
Move sensitive data to env variables
var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); // create reusable transporter object using the default SMTP transport var smtp = process.env.SMTPCREDENTIALS || ''; var transporter = nodemailer.createTransport(smtp); var SECRET = process.env.SPASECRET || ''; var SENDTO = process.env.EMAILS || ''; router.post('/deliverforme', function(req, res, next) { var data = req.body; console.log("##\n\n", data, "\n\n##"); if (data.key !== SECRET) { res.status(400).send(); } var sended_at = new Date(parseFloat(data.timestamp)); var received_at = new Date(Date.now()); var message = [data['form[content]'], "\n\nEnviado em ", sended_at.toString(), ". Processado em ", received_at.toString() ].join(' '); var mailOptions = { to: SENDTO, from: [data['form[name]'],"<",data['form[email]'],">"].join(' '), subject: data['form[subject]'], text: message }; transporter.sendMail(mailOptions, function(error, info){ if(error) { res.status(403).send(); } }); res.status(201).send(); }); module.exports = router;
var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); // create reusable transporter object using the default SMTP transport var smtp = process.env.SMTPCREDENTIALS || ''; var transporter = nodemailer.createTransport(smtp); var SECRET = process.env.SPASECRET || ''; router.post('/deliverforme', function(req, res, next) { var data = req.body; console.log("##\n\n", data, "\n\n##"); if (data.key !== SECRET) { res.status(400).send(); } var sended_at = new Date(parseFloat(data.timestamp)); var received_at = new Date(Date.now()); var message = [data['form[content]'], "\n\nEnviado em ", sended_at.toString(), ". Processado em ", received_at.toString() ].join(' '); var mailOptions = { to: 'kenner.hp@gmail.com', from: [data['form[name]'],"<",data['form[email]'],">"].join(' '), subject: data['form[subject]'], text: message }; transporter.sendMail(mailOptions, function(error, info){ if(error) { res.status(403).send(); } }); res.status(201).send(); }); module.exports = router;
Fix API documentation for IsLargeCallback. Fixes #497.
package invtweaks.api.container; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A marker for containers that have a chest-like persistent storage component. Enables the Inventory Tweaks sorting * buttons for this container. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ChestContainer { // Set to true if the Inventory Tweaks sorting buttons should be shown for this container. boolean showButtons() default true; // Size of a chest row int rowSize() default 9; // Uses 'large chest' mode for sorting buttons // (Renders buttons vertically down the right side of the GUI) boolean isLargeChest() default false; // Annotation for method to get size of a chest row if it is not a fixed size for this container class // Signature int func() @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface RowSizeCallback { } // Annotation for method to get size of a chest row if it is not a fixed size for this container class // Signature boolean func() @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface IsLargeCallback { } }
package invtweaks.api.container; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A marker for containers that have a chest-like persistent storage component. Enables the Inventory Tweaks sorting * buttons for this container. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ChestContainer { // Set to true if the Inventory Tweaks sorting buttons should be shown for this container. boolean showButtons() default true; // Size of a chest row int rowSize() default 9; // Uses 'large chest' mode for sorting buttons // (Renders buttons vertically down the right side of the GUI) boolean isLargeChest() default false; // Annotation for method to get size of a chest row if it is not a fixed size for this container class // Signature int func() @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface RowSizeCallback { } // Annotation for method to get size of a chest row if it is not a fixed size for this container class // Signature int func() @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface IsLargeCallback { } }
Change port to work with heroku
import fs from 'fs'; import express from 'express'; import path from 'path'; import bodyParser from 'body-parser'; import { initRoutes } from './api/routes'; // Start express const server = express(); //Load in HTML file const index = fs.readFileSync(__dirname + '/client/client.html'); const port = process.env.PORT || process.env.NODE_PORT || 3000; // Serve Assets server.use('**/js', express.static(path.resolve(`${__dirname}/build/js`))); server.use('**/css', express.static(path.resolve(`${__dirname}/client/stylesheets`))); server.use('**/media', express.static(path.resolve(`${__dirname}/client/media`))); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: true })); // Initialize server route and run initRoutes(server, index); server.listen(port); console.log('_________________________________________________________________________ \n'); console.log('Server running at http://127.0.0.1:1337/');
import fs from 'fs'; import express from 'express'; import path from 'path'; import bodyParser from 'body-parser'; import { initRoutes } from './api/routes'; // Start express const server = express(); //Load in HTML file const index = fs.readFileSync(__dirname + '/client/client.html'); // Serve Assets server.use('**/js', express.static(path.resolve(`${__dirname}/build/js`))); server.use('**/css', express.static(path.resolve(`${__dirname}/client/stylesheets`))); server.use('**/media', express.static(path.resolve(`${__dirname}/client/media`))); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: true })); // Initialize server route and run initRoutes(server, index); server.listen(1337); console.log('_________________________________________________________________________ \n'); console.log('Server running at http://127.0.0.1:1337/');
Add detail log on LKS
/** * PDP-11 Emulation for JavaScript */ /** * DeviceKw prototype * * This prototype provides KW device emulation. * @author Takashi Toyoshima <toyoshim@gmail.com> */ function DeviceKw (bus) { this.bus = bus; } /** * Public constants. */ DeviceKw.ADDRESS_LKS = 0777546; /** * Write 16-bit data to addressed memory. * @param address memory address to write * @param data data to write * @return success */ DeviceKw.prototype.write = function (address, data) { var result = true; switch (address) { case DeviceKw.ADDRESS_LKS: Log.getLog().warn("KW LKS <= 0x" + Log.toHex(data, 4) + " (Not implemented.)"); break; default: result = false; } return result; }; /** * Read 16-bit data from addressed memory. * @param address memory address to read * @return read data (-1: failure) */ DeviceKw.prototype.read = function (address) { var result = -1; switch (address) { case DeviceKw.ADDRESS_LKS: // Clock Status Register result = 0x0000; Log.getLog().warn("KW LKS => 0x0000 (Not implemented.)"); default: break; } return result; };
/** * PDP-11 Emulation for JavaScript */ /** * DeviceKw prototype * * This prototype provides KW device emulation. * @author Takashi Toyoshima <toyoshim@gmail.com> */ function DeviceKw (bus) { this.bus = bus; } /** * Public constants. */ DeviceKw.ADDRESS_LKS = 0777546; /** * Write 16-bit data to addressed memory. * @param address memory address to write * @param data data to write * @return success */ DeviceKw.prototype.write = function (address, data) { var result = true; switch (address) { case DeviceKw.ADDRESS_LKS: default: result = false; } return result; }; /** * Read 16-bit data from addressed memory. * @param address memory address to read * @return read data (-1: failure) */ DeviceKw.prototype.read = function (address) { var result = -1; switch (address) { case DeviceKw.ADDRESS_LKS: // Clock Status Register result = 0x0000; Log.getLog().warn("KW LKS => 0x0000 (Not implemented.)"); default: break; } return result; };
Add support of custom data
<?php /** * This custom class must be placed in the folder /AlloPass/Hipay/Helper * You have to personalize the method getCustomData and return an json of your choice. * */ class Allopass_Hipay_Helper_CustomData extends Mage_Core_Helper_Abstract { /** * Return yours customs datas in a json for gateway transaction request * * @param array $payment * @param float $amount * */ public function getCustomData($payment,$amount) { $customData = array(); // An example of adding custom data if ($payment) { $customData['my_field_custom_1'] = $payment->getOrder()->getBaseCurrencyCode(); } return $customData; } }
<?php /** * This custom class must be placed in the folder /AlloPass/Hipay/Helper * You have to personalize the method getCustomData and return an json of your choice. * */ class Allopass_Hipay_Helper_CustomData extends Mage_Core_Helper_Abstract { /** * Return yours customs datas in a json for gateway transaction request * * @param array $payment * @param float $amount * */ public function getCustomData($payment,$amount) { $customData = array(); // An example of adding custom data if ($payment) { $customData['my_field_custom_1'] = $payment->getOrder()->getBaseCurrencyCode(); } return json_encode($customData); } }
Fix filename of bundled file
import { uglify } from "rollup-plugin-uglify"; import typescript from "rollup-plugin-typescript2"; import resolve from "rollup-plugin-node-resolve"; import license from "rollup-plugin-license"; const base = { input: "src/skinview3d.ts", output: [ { format: "umd", name: "skinview3d", file: "dist/skinview3d.js", indent: "\t", globals: { "three": "THREE" } }, { format: "es", file: "dist/skinview3d.module.js", indent: "\t" } ], external: [ "three" ], plugins: [ resolve(), typescript(), license({ banner: ` skinview3d (https://github.com/bs-community/skinview3d) MIT License ` }) ] }; export default [ base, Object.assign({}, base, { output: Object.assign({}, base.output[0], { file: "dist/skinview3d.min.js" }), plugins: (() => { const plugin = base.plugins.slice(); plugin.splice(1, 0, uglify()); return plugin; })() }) ];
import { uglify } from "rollup-plugin-uglify"; import typescript from "rollup-plugin-typescript2"; import resolve from "rollup-plugin-node-resolve"; import license from "rollup-plugin-license"; const base = { input: "src/skinview3d.ts", output: [ { format: "umd", name: "skinview3d", file: "dist/skinview3d.browser.js", indent: "\t", globals: { "three": "THREE" } }, { format: "es", file: "dist/skinview3d.module.js", indent: "\t" } ], external: [ "three" ], plugins: [ resolve(), typescript(), license({ banner: ` skinview3d (https://github.com/bs-community/skinview3d) MIT License ` }) ] }; export default [ base, Object.assign({}, base, { output: Object.assign({}, base.output[0], { file: "dist/skinview3d.browser.min.js" }), plugins: (() => { const plugin = base.plugins.slice(); plugin.splice(1, 0, uglify()); return plugin; })() }) ];
Make it a map in MultipleProcess
// MulitpleProcess model // An abstract class that allows us to group some atomic process related entities // Like: registrations, requirements or processingSteps 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs'); module.exports = memoize(function (db/*, options*/) { var MultipleProcess = ensureDb(db).Object.extend('MultipleProcess', { map: { type: db.Object, nested: true }, applicable: { type: db.Object, multiple: true, value: function (_observe) { var result = []; this.map.forEach(function (entity) { var isApplicable = entity._get ? _observe(entity._isApplicable) : entity.isApplicable; if (isApplicable) result.push(entity); }); return result; } } }); MultipleProcess.prototype.map._descriptorPrototype_.type = db.Object; return MultipleProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
// MulitpleProcess model // An abstract class that allows us to group some atomic process related entities // Like: registrations, requirements or processingSteps 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs'); module.exports = memoize(function (db/*, options*/) { return ensureDb(db).Object.extend('MultipleProcess', { map: { type: db.Object, nested: true }, applicable: { type: db.Object, multiple: true, value: function (_observe) { var result = []; this.map.forEach(function (entity) { var isApplicable = entity._get ? _observe(entity._isApplicable) : entity.isApplicable; if (isApplicable) result.push(entity); }); return result; } } }); }, { normalizer: require('memoizee/normalizers/get-1')() });
Raise exception when we fail to grab a redis lock. Summary: I might be missing something but it seems odd that we don't raise an error when we fail to grab a lock and consequently not run the wrapped function. We wrap all our tracked tasks with this lock function so failing to grab the lock will appear as if the task finished successfully. Reviewers: nate, josiah Reviewed By: nate, josiah Subscribers: changesbot, kylec Differential Revision: https://tails.corp.dropbox.com/D192147
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) raise return wrapped
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
Add Pages title and code clean
<div class="entry-content"> <?php /* translators: %s: Name of current post */ echo apply_filters('the_content', $post->post_content); // the_content(sprintf( // __('Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentyseventeen'), get_the_title() // )); wp_link_pages(array( 'before' => '<div class="page-links">' . sprintf('<h3>%s</h3>', __('Page', 'twentyseventeen')), 'after' => '</div>', 'link_before' => '<span class="page-number">', 'link_after' => '</span>', )); ?> </div><!-- .entry-content -->
<div class="entry-content"> <?php /* translators: %s: Name of current post */ printf(apply_filters('the_content', $post->post_content)); // the_content(sprintf( // __('Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentyseventeen'), get_the_title() // )); wp_link_pages(array( 'before' => '<div class="page-links">' . __('Pages:', 'twentyseventeen'), 'after' => '</div>', 'link_before' => '<span class="page-number">', 'link_after' => '</span>', )); ?> </div><!-- .entry-content -->
Fix issue with FORWARD_ONLY resultSets
package jp.ne.opt.redshiftfake.views; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by ffarrell on 14/06/2018. * * Some system tables that exist in redshift do not necessarily exist in postgres * * This creates pg_tableef as a view on each connection if it does not exist */ public class SystemViews { private static final String createPgTableDefView = "CREATE VIEW pg_table_def (schemaname, tablename, \"column\", \"type\", \"encoding\", distkey, sortkey, \"notnull\") " + "AS SELECT table_schema, table_name, column_name, data_type, 'none', false, 0, CASE is_nullable WHEN 'yes' THEN false ELSE true END " + "FROM information_schema.columns;"; public static void create(final Connection connection) throws SQLException { final ResultSet resultSet = connection.createStatement().executeQuery("SELECT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'pg_tab_def')"); if(resultSet.next() && !resultSet.getBoolean(1)){ connection.createStatement().execute(createPgTableDefView); } } }
package jp.ne.opt.redshiftfake.views; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by ffarrell on 14/06/2018. * * Some system tables that exist in redshift do not necessarily exist in postgres * * This creates pg_tableef as a view on each connection if it does not exist */ public class SystemViews { private static final String createPgTableDefView = "CREATE VIEW pg_table_def (schemaname, tablename, \"column\", \"type\", \"encoding\", distkey, sortkey, \"notnull\") " + "AS SELECT table_schema, table_name, column_name, data_type, 'none', false, 0, CASE is_nullable WHEN 'yes' THEN false ELSE true END " + "FROM information_schema.columns;"; public static void create(final Connection connection) throws SQLException { final ResultSet resultSet = connection.createStatement().executeQuery("SELECT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'pg_tab_def')"); resultSet.first(); if(!resultSet.getBoolean(1)){ connection.createStatement().execute(createPgTableDefView); } } }
Update to new v1 endpoint We're moving to a versioned API endpoint. Thanks!
'use strict'; var request = require('request'); var symbols = require('log-symbols'); module.exports = function(domain, callback){ var path = 'https://api.domainr.com/v1/api/json/search?q='+domain+'&client_id=avail'; request(path, function (error, response, body) { var results = JSON.parse(body); results = results.results; results = results.map(function (domain) { var available; switch (domain.availability) { case 'tld': available = symbols.info; break; case 'unavailable': available = symbols.error; break; case 'taken': available = symbols.error; break; case 'available': available = symbols.success; break; } return domain.domain + domain.path + ' ' + available; }); callback(results); }); }
'use strict'; var request = require('request'); var symbols = require('log-symbols'); module.exports = function(domain, callback){ var path = 'https://domainr.com/api/json/search?q='+domain+'&client_id=avail'; request(path, function (error, response, body) { var results = JSON.parse(body); results = results.results; results = results.map(function (domain) { var available; switch (domain.availability) { case 'tld': available = symbols.info; break; case 'unavailable': available = symbols.error; break; case 'taken': available = symbols.error; break; case 'available': available = symbols.success; break; } return domain.domain + domain.path + ' ' + available; }); callback(results); }); }
Add toggle mutation for adding achievement
import Relay from 'react-relay'; export default class extends Relay.Mutation { getMutation() { return Relay.QL`mutation{ ToggleAchievement }`; } getFatQuery() { return Relay.QL` fragment on ToggleAchievementPayload { developer { id, achievements, }, connection { id, imports, }, } `; } getConfigs() { return [ { type: 'FIELDS_CHANGE', fieldIDs: { developer: this.props.developerId, }, }, { type: 'FIELDS_CHANGE', fieldIDs: { connection: this.props.connectionId, }, }, ]; } getVariables() { return { id: this.props.id, }; } }
import Relay from 'react-relay'; export default class extends Relay.Mutation { getMutation() { return Relay.QL`mutation{ ToggleAchievement }`; } getFatQuery() { return Relay.QL` fragment on ToggleAchievementPayload { developer { id, connections, achievements, } } `; } getConfigs() { return [ { type: 'RANGE_ADD', parentName: 'developer', parentID: this.props.developerId, connectionName: 'achievements', edgeName: 'achievementEdge', rangeBehaviors: { '': 'append', 'order(-id)': 'prepend', }, }, ]; } getVariables() { return { id: this.props.id, selection: this.props.selection, }; } }
Use proper value center (not middle) for `<FlexParent horizontalAlignment>` attribute
/* eslint-disable import/no-unresolved */ import React from 'react'; import ReactDOM from 'react-dom'; // Styling import { FlexParent, FlexChild } from 'react-foundation-components/lib/flex'; import './splash.css'; import './logo.png'; import './splashFilters.jpg'; import 'react-foundation-components/lib/_typography.scss'; const App = () => { return ( <FlexParent id="splashContainer" horizontalAlignment="center" verticalAlignment="middle"> <FlexChild> <a href="http://localhost:3000/#mapSummer"> <img id="map" role="presentation" src="http://localhost:3000/splashFilters.jpg" /> </a> </FlexChild> </FlexParent> ); }; ReactDOM.render(<App />, document.getElementById('app'));
/* eslint-disable import/no-unresolved */ import React from 'react'; import ReactDOM from 'react-dom'; // Styling import { FlexParent, FlexChild } from 'react-foundation-components/lib/flex'; import './splash.css'; import './logo.png'; import './splashFilters.jpg'; import 'react-foundation-components/lib/_typography.scss'; const App = () => { return ( <FlexParent id="splashContainer" horizontalAlignment="middle" verticalAlignment="middle"> <FlexChild> <a href="http://localhost:3000/#mapSummer"> <img id="map" role="presentation" src="http://localhost:3000/splashFilters.jpg" /> </a> </FlexChild> </FlexParent> ); }; ReactDOM.render(<App />, document.getElementById('app'));
Set cookie only after video is actually displayed
(function($) { $(document).ready(function(){ var pageLinkMap = { 'table': 'table_view', 'map': 'map_view', 'distribution': 'distribution_view', } var displayRatio = 0.5625, w = $(window).width() * 0.95, h = w * displayRatio, wMax = 960, hMax = wMax * displayRatio, page = window.location.pathname.split('/')[2], videoLink = VIDEO_LINKS[pageLinkMap[page]]; if (document.cookie.indexOf('video-upsell=true') === -1) { var showVideo = setTimeout(function () { $.featherlight({ iframe: videoLink, iframeMaxWidth: wMax, iframeMaxHeight: hMax, iframeWidth: w, iframeHeight: h, background: $('.wazi-lightbox'), variant: 'wazi-lightbox' }); var expires = new Date(); expires.setDate(expires.getDate() + 30); document.cookie = "video-upsell=true; expires=" + expires.toUTCString(); }, 15000); } }); }(jQuery));
(function($) { $(document).ready(function(){ var pageLinkMap = { 'table': 'table_view', 'map': 'map_view', 'distribution': 'distribution_view', } var displayRatio = 0.5625, w = $(window).width() * 0.95, h = w * displayRatio, wMax = 960, hMax = wMax * displayRatio, page = window.location.pathname.split('/')[2], videoLink = VIDEO_LINKS[pageLinkMap[page]]; if (document.cookie.indexOf('video-upsell=true') === -1) { var expires = new Date(); expires.setDate(expires.getDate() + 30); document.cookie = "video-upsell=true; expires=" + expires.toUTCString(); var showVideo = setTimeout(function () { $.featherlight({ iframe: videoLink, iframeMaxWidth: wMax, iframeMaxHeight: hMax, iframeWidth: w, iframeHeight: h, background: $('.wazi-lightbox'), variant: 'wazi-lightbox' }); }, 15000); } }); }(jQuery));
Make ESLint allow _id identifier for mongodb id field
module.exports = { extends: "airbnb", env: { browser: true, jest: true, }, rules: { "react/jsx-filename-extension": [ 1, { extensions: [ ".js", ".jsx", ], }, ], // Doesn't allow nested input inside label "jsx-a11y/label-has-for": [0], // Disabled until eslint-plugin-import gets proper support for webpack externals // https://github.com/benmosher/eslint-plugin-import/issues/479 // https://github.com/benmosher/eslint-plugin-import/issues/605 "import/no-extraneous-dependencies": 0, "import/extensions": 0, // Allows us to reference mongodb '_id' field without whitelisting each line. "no-underscore-dangle": [2, { allow: ['_id'] }], }, settings: { "import/resolver": { webpack: { config: "webpack.config.js", }, }, }, };
module.exports = { extends: "airbnb", env: { browser: true, jest: true, }, rules: { "react/jsx-filename-extension": [ 1, { extensions: [ ".js", ".jsx", ], }, ], // Doesn't allow nested input inside label "jsx-a11y/label-has-for": [0], // Disabled until eslint-plugin-import gets proper support for webpack externals // https://github.com/benmosher/eslint-plugin-import/issues/479 // https://github.com/benmosher/eslint-plugin-import/issues/605 "import/no-extraneous-dependencies": 0, "import/extensions": 0, }, settings: { "import/resolver": { webpack: { config: "webpack.config.js", }, }, }, };
Revert "Fallback to other things when keyCode is not available" This reverts commit 016d44a851fd3bcc4f5ffeef79431ac53add5e88.
Elm.Native.Keyboard = {}; Elm.Native.Keyboard.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Keyboard = localRuntime.Native.Keyboard || {}; if (localRuntime.Native.Keyboard.values) { return localRuntime.Native.Keyboard.values; } var NS = Elm.Native.Signal.make(localRuntime); function keyEvent(event) { return { alt: event.altKey, meta: event.metaKey, keyCode: event.keyCode }; } function keyStream(node, eventName, handler) { var stream = NS.input(eventName, { alt: false, meta: false, keyCode: 0 }); localRuntime.addListener([stream.id], node, eventName, function(e) { localRuntime.notify(stream.id, handler(e)); }); return stream; } var downs = keyStream(document, 'keydown', keyEvent); var ups = keyStream(document, 'keyup', keyEvent); var presses = keyStream(document, 'keypress', keyEvent); var blurs = keyStream(window, 'blur', function() { return null; }); return localRuntime.Native.Keyboard.values = { downs: downs, ups: ups, blurs: blurs, presses: presses }; };
Elm.Native.Keyboard = {}; Elm.Native.Keyboard.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Keyboard = localRuntime.Native.Keyboard || {}; if (localRuntime.Native.Keyboard.values) { return localRuntime.Native.Keyboard.values; } var NS = Elm.Native.Signal.make(localRuntime); function keyEvent(event) { return { alt: event.altKey, meta: event.metaKey, keyCode: event.keyCode || event.which || event.charCode || 0 }; } function keyStream(node, eventName, handler) { var stream = NS.input(eventName, { alt: false, meta: false, keyCode: 0 }); localRuntime.addListener([stream.id], node, eventName, function(e) { localRuntime.notify(stream.id, handler(e)); }); return stream; } var downs = keyStream(document, 'keydown', keyEvent); var ups = keyStream(document, 'keyup', keyEvent); var presses = keyStream(document, 'keypress', keyEvent); var blurs = keyStream(window, 'blur', function() { return null; }); return localRuntime.Native.Keyboard.values = { downs: downs, ups: ups, blurs: blurs, presses: presses }; };
Check whether the user entered a name
const express = require('express'); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server); app.use('/public', express.static(__dirname + '/public')); let users = {}; app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); io.on('connection', (socket) => { console.log(`A user with id ${socket.id} connected`); socket.on('send a message', (message) => { if(!socket.id in users) { throw 'You should first enter your name'; } // notify all users a meessage is sent io.sockets.emit('message sent', { message, user: {id: socket.id, name: users[socket.id]} }); }); socket.on('enter', (user) => { users[socket.id] = user.name; socket.emit('entered', users); // notify all users but current that a user has entered socket.broadcast.emit('user entered', users); }); socket.on('disconnect', () => { console.log(`A user with id ${socket.id} disconnected`); delete users[socket.id]; socket.broadcast.emit('user left', users); }); }); server.listen(3000, () => { console.log('Listening on port 3000...'); });
const express = require('express'); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server); app.use('/public', express.static(__dirname + '/public')); let users = {}; app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); io.on('connection', (socket) => { console.log(`A user with id ${socket.id} connected`); socket.on('send a message', (message) => { // emit to all users a meessage is sent io.sockets.emit('message sent', { message, user: {id: socket.id, name: users[socket.id]} }); }); socket.on('enter', (user) => { users[socket.id] = user.name; socket.emit('entered', users); // emit to all users but current a user has entered socket.broadcast.emit('user entered', users); }); socket.on('disconnect', () => { console.log(`A user with id ${socket.id} disconnected`); delete users[socket.id]; socket.broadcast.emit('user left', users); }); }); server.listen(3000, () => { console.log('Listening on port 3000...'); });
Add (failing) tests for URL reversal
var Route = require('../Route'); describe('Route', function() { describe('#url()', function() { it('generates a URL', function() { var route = new Route('/users/'); var url = route.url(); expect(url).toBe('/users/'); }); it('generates a URL with a named param', function() { var route = new Route('/users/:username/pets'); var url = route.url({username: 'matthewwithanm'}); expect(url).toBe('/users/matthewwithanm/pets'); }); it("errors if you don't provide all the params", function() { var route = new Route('/users/:username/pets'); expect(route.url).toThrowError(/Could not reverse URL/); }); it("properly builds URLs with special RegExp chars", function() { var route = new Route('/weird+,^url/:username'); var url = route.url({username: 'matthewwithanm'}); expect(url).toBe('/weird+,^url/matthewwithanm/pets'); }); it("properly builds URLs with optional params", function() { var route = new Route('/users/(:username)'); var url = route.url({username: 'matthewwithanm'}); expect(url).toBe('/users/'); }); }); });
var Route = require('../Route'); describe('Route', function() { describe('#url()', function() { it('generates a URL', function() { var route = new Route('/users/'); var url = route.url(); expect(url).toBe('/users/'); }); it('generates a URL with a named param', function() { var route = new Route('/users/:username/pets'); var url = route.url({username: 'matthewwithanm'}); expect(url).toBe('/users/matthewwithanm/pets'); }); it("errors if you don't provide all the params", function() { var route = new Route('/users/:username/pets'); expect(route.url).toThrowError(/Could not reverse URL/); }); }); });
Remove starting and trailing slashes
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route, browserHistory, IndexRoute} from 'react-router' import App from './components/app'; import Login from './components/login' import Signup from './components/signup' import Classes from './components/teacher/classes/Classes' import Lessons from './components/teacher/classes/ClassData/ClassData' import LessonsData from './components/teacher/classes/ClassData/LessonData' import Students from './components/teacher/classes/students/StudentData' import Settings from './components/Settings' ReactDOM.render(( <Router history={browserHistory}> <Route path='/' component = {App}> <IndexRoute component = {Classes} /> <Route path='class/:classId/lessons' component={Lessons} /> <Route path='class/:classId/lessons/:lessonId' component={LessonsData}/> <Route path='class/:classId/students/:studentId' component={Students}/> </Route> </Router> ), document.getElementById("app"));
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route, browserHistory, IndexRoute} from 'react-router' import App from './components/app'; import Login from './components/login' import Signup from './components/signup' import Classes from './components/teacher/classes/Classes' import Lessons from './components/teacher/classes/ClassData/ClassData' import LessonsData from './components/teacher/classes/ClassData/LessonData' import Students from './components/teacher/classes/students/StudentData' import Settings from './components/Settings' ReactDOM.render(( <Router history={browserHistory}> <Route path='/' component = {App}> <IndexRoute component = {Classes} /> <Route path='/class/:classId/lessons/' component={Lessons} /> <Route path='/class/:classId/lessons/:lessonId' component={LessonsData}/> <Route path='/class/:classId/students/:studentId' component={Students}/> </Route> </Route> </Router> ), document.getElementById("app"));
Fix typo in uploader tests Change-Id: Ife7685d6113309d20bf90a24d73f793be2837314
# Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from solum.tests import base from solum.tests import utils from solum.uploaders import common as uploader class CommonTest(base.BaseTestCase): def setUp(self): super(CommonTest, self).setUp() def test_upload(self): ctxt = utils.dummy_context() orig_path = "original path" assembly_id = "1234" build_id = "5678" baseuploader = uploader.UploaderBase(ctxt, orig_path, assembly_id, build_id, "fakestage") self.assertEqual(0, baseuploader.write_userlog_row.call_count)
# Copyright 2014 - Rackspace Hosting # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from solum.tests import base from solum.tests import utils from solum.uploader import common as uploader class CommonTest(base.BaseTestCase): def setUp(self): super(CommonTest, self).setUp() def test_upload(self): ctxt = utils.dummy_context() orig_path = "original path" assembly_id = "1234" build_id = "5678" baseuploader = uploader.UploaderBase(ctxt, orig_path, assembly_id, build_id, "fakestage") self.assertEqual(0, baseuploader.write_userlog_row.call_count)
Increase max concurrency by 10x
package pool import ( "runtime" "sync" ) type Pool struct { wg *sync.WaitGroup completion chan bool m sync.Mutex } const ( MaxConcurrencyLimit = -1 ) func New(concurrencyLimit int) *Pool { if concurrencyLimit == MaxConcurrencyLimit { // Completely arbitrary. Most of the time we could probably have unbounded concurrency, but the situations where we use // this pool is basically just S3 uploading and downloading, so this number is kind of a proxy for "What won't rate limit us" // TODO: Make artifact uploads and downloads gracefully handle rate limiting, remove this pool entirely, and use unbounded concurrency via a WaitGroup concurrencyLimit = runtime.NumCPU() * 10 } wg := sync.WaitGroup{} completionChan := make(chan bool, concurrencyLimit) for i := 0; i < concurrencyLimit; i++ { completionChan <- true } return &Pool{&wg, completionChan, sync.Mutex{}} } func (pool *Pool) Spawn(job func()) { <-pool.completion pool.wg.Add(1) go func() { defer func() { pool.completion <- true pool.wg.Done() }() job() }() } func (pool *Pool) Lock() { pool.m.Lock() } func (pool *Pool) Unlock() { pool.m.Unlock() } func (pool *Pool) Wait() { pool.wg.Wait() }
package pool import ( "runtime" "sync" ) type Pool struct { wg *sync.WaitGroup completion chan bool m sync.Mutex } const ( MaxConcurrencyLimit = -1 ) func New(concurrencyLimit int) *Pool { if concurrencyLimit == MaxConcurrencyLimit { concurrencyLimit = runtime.NumCPU() } wg := sync.WaitGroup{} completionChan := make(chan bool, concurrencyLimit) for i := 0; i < concurrencyLimit; i++ { completionChan <- true } return &Pool{&wg, completionChan, sync.Mutex{}} } func (pool *Pool) Spawn(job func()) { <-pool.completion pool.wg.Add(1) go func() { defer func() { pool.completion <- true pool.wg.Done() }() job() }() } func (pool *Pool) Lock() { pool.m.Lock() } func (pool *Pool) Unlock() { pool.m.Unlock() } func (pool *Pool) Wait() { pool.wg.Wait() }
Use api/1/ as url prefix for all REST interfaces This allows separating the "normal" web code from the rest api.
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Revert "OFFSSET filter uses shorthand syntax when in MySQL" This reverts commit cdd6cb52d2f8646f3da10876f7a9caef56c7cd51.
<?php namespace RedBeanPHP\Plugins\RedSql\Filters; use R; use RedBean_QueryWriter_Oracle; class FilterOFFSET implements FilterInterface { public function validate(array $parameters) { if (!array_key_exists('value', $parameters)) { throw new \InvalidArgumentException("OFFSET expects an [offset] value."); } } /** * @todo limit for oracle */ public function apply(&$sql_reference, array &$values_reference, array $parameters) { $writer = R::$toolbox->getWriter(); $values_reference[] = $parameters['value']; if ($writer instanceof RedBean_QueryWriter_Oracle) { return; } $sql_reference .= " OFFSET ? "; } }
<?php namespace RedBeanPHP\Plugins\RedSql\Filters; use R; use RedBean_QueryWriter_Oracle; use RedBean_QueryWriter_MySQL; class FilterOFFSET implements FilterInterface { public function validate(array $parameters) { if (!array_key_exists('value', $parameters)) { throw new \InvalidArgumentException("OFFSET expects an [offset] value."); } } /** * @todo limit for oracle */ public function apply(&$sql_reference, array &$values_reference, array $parameters) { $writer = R::$toolbox->getWriter(); $values_reference[] = $parameters['value']; if ($writer instanceof RedBean_QueryWriter_Oracle) { return; } if ($writer instanceof RedBean_QueryWriter_MySQL) { $sql_reference .= ", ? "; return; } $sql_reference .= " OFFSET ? "; } }
Fix pip installation failure involving README.md Two bugs with "easy" fixes: - README.md was not being included in the source distribution. I'm not sure what I did to fix it, since the distutils/setuptools/distribute docs are quite incomplete and convoluted on something so straight-forward. The fix: I removed some 'package_data' type lines from setup.py, and now LICENSE.txt and README.md are being included. - In addition to README.md not being included in the distribution (tar.gz file) it was being read by setup.py as open('README.md'), which is relative to the current working directory, which I'm not sure pip sets to the directory containing setup.py. The fix is to open the file using the directory of setup.py, via the __file__ attribute.
import os from setuptools import setup, find_packages setup( name = 'diabric', version = '0.1.1', license = 'MIT', description = 'Diabolically atomic Python Fabric fabfile tasks and utilities.', long_description = open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), keywords = 'fabric fabfile boto ec2 virtualenv python wsgi webapp deployment', url = 'https://github.com/todddeluca/diabric', author = 'Todd Francis DeLuca', author_email = 'todddeluca@yahoo.com', classifiers = ['License :: OSI Approved :: MIT License', 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'], packages = ['diabric'], )
from setuptools import setup setup( name = 'diabric', version = '0.1', license = 'MIT', description = 'Diabolically atomic Python Fabric fabfile tasks and utilities.', long_description = open('README.md').read(), keywords = 'fabric fabfile boto ec2 virtualenv python wsgi webapp deployment', url = 'https://github.com/todddeluca/diabric', author = 'Todd Francis DeLuca', author_email = 'todddeluca@yahoo.com', classifiers = ['License :: OSI Approved :: MIT License', 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], packages = ['diabric'], install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'], include_package_data = True, package_data = {'' : ['README.md', 'LICENSE.txt']}, )
Fix a bug when the open311 API returns an error.
from three import Three from django.core.urlresolvers import reverse from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) def post(self, request): open311_response = QC_three.post(**request.POST)[0] if open311_response.get('code') == 'BadRequest': return self.ErrorAPIResponse((open311_response['code'], open311_response['description'])) request_id = open311_response['service_request_id'] location = reverse('request', args = (request_id,)) response = self.OkAPIResponse({ 'id': request_id, 'location': location }) response['Location'] = location return response class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
from three import Three from django.core.urlresolvers import reverse from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) def post(self, request): open311_response = QC_three.post(**request.POST)[0] if open311_response.get('code') == 'BadRequest': return self.ErrorAPIResponse(open311_response) request_id = open311_response['service_request_id'] location = reverse('request', args = (request_id,)) response = self.OkAPIResponse({ 'id': request_id, 'location': location }) response['Location'] = location return response class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
Create reference to app in module
try: import pygame except ImportError: print 'Failed to import pygame' print '-----------------------' print '' print 'tingbot-python requires pygame. Please download and install pygame 1.9.1' print 'or later from http://www.pygame.org/download.shtml' print '' print "If you're using a virtualenv, you should make the virtualenv with the " print "--system-site-packages flag so the system-wide installation is still " print "accessible." print '' print '-----------------------' print '' raise from . import platform_specific, input from .graphics import screen, Surface, Image from .run_loop import main_run_loop, every, once from .input import touch from .button import press from .web import webhook from .tingapp import app platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_after_action_callback(screen.update_if_needed) main_run_loop.add_wait_callback(input.poll) # in case screen updates happen in input.poll... main_run_loop.add_wait_callback(screen.update_if_needed) main_run_loop.run() __all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook'] __author__ = 'Joe Rickerby' __email__ = 'joerick@mac.com' __version__ = '0.3'
try: import pygame except ImportError: print 'Failed to import pygame' print '-----------------------' print '' print 'tingbot-python requires pygame. Please download and install pygame 1.9.1' print 'or later from http://www.pygame.org/download.shtml' print '' print "If you're using a virtualenv, you should make the virtualenv with the " print "--system-site-packages flag so the system-wide installation is still " print "accessible." print '' print '-----------------------' print '' raise from . import platform_specific, input from .graphics import screen, Surface, Image from .run_loop import main_run_loop, every, once from .input import touch from .button import press from .web import webhook from .settings import config platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_after_action_callback(screen.update_if_needed) main_run_loop.add_wait_callback(input.poll) # in case screen updates happen in input.poll... main_run_loop.add_wait_callback(screen.update_if_needed) main_run_loop.run() __all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook'] __author__ = 'Joe Rickerby' __email__ = 'joerick@mac.com' __version__ = '0.3'
chore: Move error validation to the top of the scope Signed-off-by: Adrian Oprea <a1b909ec1cc11cce40c28d3640eab600e582f833@codesi.nz>
package handlers import ( "go-message-masking/persistence" "net/http" "regexp" "github.com/ant0ine/go-json-rest/rest" ) // Message is a code representation of the data sent by the API user through the wire type Message struct { Locale string Text string MaskString string } // MaskSensitiveData is the route handler that responds whenever the `/mask` route // has been called with valid data func MaskSensitiveData(w rest.ResponseWriter, r *rest.Request) { message := Message{} err := r.DecodeJsonPayload(&message) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } var maskString = "(hidden)" if message.MaskString != "" { maskString = message.MaskString } processedMessage := maskSensitiveData(message.Text, persistence.Expressions, maskString) w.WriteJson( &Message{ Locale: message.Locale, Text: processedMessage, MaskString: maskString, }, ) } func maskSensitiveData(s string, expressionMap map[string]string, maskString string) string { for _, value := range expressionMap { s = applyExpression(s, value, maskString) } return s } func applyExpression(s string, expression string, maskString string) string { re := regexp.MustCompile(expression) return re.ReplaceAllString(s, maskString) }
package handlers import ( "go-message-masking/persistence" "net/http" "regexp" "github.com/ant0ine/go-json-rest/rest" ) // Message is a code representation of the data sent by the API user through the wire type Message struct { Locale string Text string MaskString string } // MaskSensitiveData is the route handler that responds whenever the `/mask` route // has been called with valid data func MaskSensitiveData(w rest.ResponseWriter, r *rest.Request) { message := Message{} err := r.DecodeJsonPayload(&message) var maskString = "(hidden)" if message.MaskString != "" { maskString = message.MaskString } if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } processedMessage := maskSensitiveData(message.Text, persistence.Expressions, maskString) w.WriteJson( &Message{ Locale: message.Locale, Text: processedMessage, MaskString: maskString, }, ) } func maskSensitiveData(s string, expressionMap map[string]string, maskString string) string { for _, value := range expressionMap { s = applyExpression(s, value, maskString) } return s } func applyExpression(s string, expression string, maskString string) string { re := regexp.MustCompile(expression) return re.ReplaceAllString(s, maskString) }
Test suite seems to require ContentType to exist
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if not settings.configured: settings.configure( DATABASE_ENGINE='django.db.backends.postgresql_psycopg2', DATABASE_NAME='bitfield_test', INSTALLED_APPS=[ 'django.contrib.contettypes', 'bitfield', 'bitfield.tests', ], ROOT_URLCONF='', DEBUG=False, ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['bitfield'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if not settings.configured: settings.configure( DATABASE_ENGINE='django.db.backends.postgresql_psycopg2', DATABASE_NAME='bitfield_test', INSTALLED_APPS=[ 'bitfield', 'bitfield.tests', ], ROOT_URLCONF='', DEBUG=False, ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['bitfield'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Move default location to class constant
<?php namespace Grav\Common; /** * Offers composer helper methods. * * @author eschmar * @license MIT */ class Composer { /** @const Default composer location */ const DEFAULT_PATH = "bin/composer.phar"; /** * Returns the location of composer. * * @return string */ public static function getComposerLocation() { if (!function_exists('shell_exec')) { return self::DEFAULT_PATH; } // check for global composer install $path = trim(shell_exec("command -v composer")); // fall back to grav bundled composer if (!$path || !preg_match('/(composer|composer\.phar)$/', $path)) { $path = self::DEFAULT_PATH; } return $path; } }
<?php namespace Grav\Common; /** * Offers composer helper methods. * * @author eschmar * @license MIT */ class Composer { /** * Returns the location of composer. * * @return string */ public static function getComposerLocation() { if (!function_exists('shell_exec')) { return "bin/composer.phar"; } // check for global composer install $path = trim(shell_exec("command -v composer")); // fall back to grav bundled composer if (!$path || !preg_match('/(composer|composer\.phar)$/', $path)) { $path = "bin/composer.phar"; } return $path; } }
Add AWS::CodeStarConnections::Connection props, per May 14, 2020 update
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, Tags VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket') def validate_connection_providertype(connection_providertype): """Validate ProviderType for Connection""" if connection_providertype not in VALID_CONNECTION_PROVIDERTYPE: raise ValueError("Connection ProviderType must be one of: %s" % ", ".join(VALID_CONNECTION_PROVIDERTYPE)) return connection_providertype class Connection(AWSObject): resource_type = "AWS::CodeStarConnections::Connection" props = { 'ConnectionName': (basestring, True), 'ProviderType': (validate_connection_providertype, True), 'Tags': (Tags, False), }
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket') def validate_connection_providertype(connection_providertype): """Validate ProviderType for Connection""" if connection_providertype not in VALID_CONNECTION_PROVIDERTYPE: raise ValueError("Connection ProviderType must be one of: %s" % ", ".join(VALID_CONNECTION_PROVIDERTYPE)) return connection_providertype class Connection(AWSObject): resource_type = "AWS::CodeStarConnections::Connection" props = { 'ConnectionName': (basestring, True), 'ProviderType': (validate_connection_providertype, True), }
Use nose for running tests. Signed-off-by: David Black <c4b737561a711e07c31fd1e1811f33a5d770e31c@atlassian.com>
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='atlassian-jwt-auth', packages=find_packages(), version='0.0.1', install_requires=[ 'cryptography==0.8.2', 'PyJWT==1.1.0', 'requests==2.6.0', ], tests_require=['mock', 'nose',], test_suite='nose.collector', platforms=['any'], license='MIT', zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'License :: OSI Approved :: MIT License', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='atlassian-jwt-auth', packages=find_packages(), version='0.0.1', install_requires=[ 'cryptography==0.8.2', 'PyJWT==1.1.0', 'requests==2.6.0', ], tests_require=['mock',], test_suite='atlassian_jwt_auth.test', platforms=['any'], license='MIT', zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'License :: OSI Approved :: MIT License', ], )
Add query for getting sample by external identifier.
package ca.corefacility.bioinformatics.irida.repositories; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.Sample; /** * A repository for storing Sample objects * * @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca> * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca> */ public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> { /** * Get a {@link Sample} with the given string sample identifier from a * specific project. * * @param project * The {@link Project} that the {@link Sample} belongs to. * @param externalSampleId * The string sample identifier for a sample * @return The {@link Sample} for this identifier * @throws EntityNotFoundException * if a sample with this identifier doesn't exist */ @Query("select j.sample from ProjectSampleJoin j where j.project = ?1 and j.sample.externalSampleId = ?2") public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException; }
package ca.corefacility.bioinformatics.irida.repositories; import org.springframework.data.repository.PagingAndSortingRepository; import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.Sample; /** * A repository for storing Sample objects * * @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca> */ public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> { /** * Get a {@link Sample} with the given string sample identifier from a * specific project. * * @param project * The {@link Project} that the {@link Sample} belongs to. * @param externalSampleId * The string sample identifier for a sample * @return The {@link Sample} for this identifier * @throws EntityNotFoundException * if a sample with this identifier doesn't exist */ public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException; }
Convert Cell to ES6 class syntax
export class Cell { constructor(index, rowIndex, value) { this.index = index; this.rowIndex = rowIndex; this.value = value; } id() { return `${this.rowIndex}${this.index}`; } clone() { return new Cell(this.index, this.rowIndex, this.value); } } export function ComputedCell(index, rowIndex, formula) { this.index = index; this.rowIndex = rowIndex; this.value = 0; this.formula = formula; } ComputedCell.prototype.clone = function() { return new ComputedCell(this.index, this.rowIndex, this.formula); }; export function Row(index, cells) { this.index = index; this.cells = cells; } Row.prototype.clone = function() { return new Row(this.index, this.cells.map(c => c.clone())); }; Row.prototype.findCell = function(cellIndex) { return this.cells.find(cell => cell.index === cellIndex); }; Row.prototype.replaceCell = function(cellIndex, newCell) { for(let i = 0; i < this.cells.length; i++) { if(this.cells[i].index === cellIndex) { this.cells[i] = newCell; break; } } };
export function Cell(index, rowIndex, value) { this.index = index; this.rowIndex = rowIndex; this.value = value; } Cell.prototype.id = function() { return `${this.rowIndex}${this.index}`; }; Cell.prototype.clone = function() { return new Cell(this.index, this.rowIndex, this.value); }; export function ComputedCell(index, rowIndex, formula) { this.index = index; this.rowIndex = rowIndex; this.value = 0; this.formula = formula; } ComputedCell.prototype.clone = function() { return new ComputedCell(this.index, this.rowIndex, this.formula); }; export function Row(index, cells) { this.index = index; this.cells = cells; } Row.prototype.clone = function() { return new Row(this.index, this.cells.map(c => c.clone())); }; Row.prototype.findCell = function(cellIndex) { return this.cells.find(cell => cell.index === cellIndex); }; Row.prototype.replaceCell = function(cellIndex, newCell) { for(let i = 0; i < this.cells.length; i++) { if(this.cells[i].index === cellIndex) { this.cells[i] = newCell; break; } } };
Add is_safe option to Twig "form" function for AuraForm
<?php /** * This file is part of the BEAR.Package package * * @license http://opensource.org/licenses/bsd-license.php BSD */ namespace BEAR\Package\Provide\TemplateEngine\Twig\Extension; use Aura\Html\HelperLocatorFactory; class AuraForm_Twig_Extension extends \Twig_Extension { private static $helper; public function getName() { return 'AuraForm'; } public function getFunctions() { return [ new \Twig_SimpleFunction( 'form', [$this, 'createForm'], ['is_safe' => ['html']] ), ]; } public function createForm($hint) { if (! static::$helper) { $factory = new HelperLocatorFactory(); static::$helper = $factory->newInstance(); } $formElementHtml = static::$helper->input($hint); return $formElementHtml; } }
<?php /** * This file is part of the BEAR.Package package * * @license http://opensource.org/licenses/bsd-license.php BSD */ namespace BEAR\Package\Provide\TemplateEngine\Twig\Extension; use Aura\Html\HelperLocatorFactory; class AuraForm_Twig_Extension extends \Twig_Extension { private static $helper; public function getName() { return 'AuraForm'; } public function getFunctions() { return [ new \Twig_SimpleFunction('form', [$this, 'createForm']), ]; } public function createForm($hint) { if (! static::$helper) { $factory = new HelperLocatorFactory(); static::$helper = $factory->newInstance(); } $formElementHtml = static::$helper->input($hint); return $formElementHtml; } }
Call FLAGS.get_help if it's available.
# Copyright 2016 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors if hasattr(flags.FLAGS, 'get_help'): flags.FLAGS.get_help() else: flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
# Copyright 2016 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test that we can generate help for PKB.""" import os import unittest from perfkitbenchmarker import flags # Import pkb to add all flag definitions to flags.FLAGS. from perfkitbenchmarker import pkb # NOQA class HelpTest(unittest.TestCase): def testHelp(self): # Test that help generation finishes without errors flags.FLAGS.GetHelp() class HelpXMLTest(unittest.TestCase): def testHelpXML(self): with open(os.devnull, 'w') as out: flags.FLAGS.WriteHelpInXMLFormat(outfile=out) if __name__ == '__main__': unittest.main()
Add failing test for most recent datum in destroy
var tape = require("tape"), jsdom = require("jsdom"), d3_transition = require("d3-transition"), d3_selection = require("d3-selection"), d3_component = require("../"), d3 = Object.assign(d3_selection, d3_component); var datum, customExit = d3.component("p") .destroy(function (selection, d){ datum = d; return selection.transition().duration(10); }); tape("A component should be able to specify custom destroy transitions.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(customExit); test.equal(div.html(), "<p></p>"); div.call(customExit, []); // The transition is happening, so DOM element not removed yet. test.equal(div.html(), "<p></p>"); // DOM element removed after transition ends. setTimeout(function (){ test.equal(div.html(), ""); test.end(); }, 30); // The transition lasts 10 ms, so it should be done after 30. }); tape("Datum passed to destroy should be most recent.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(customExit, "a"); div.call(customExit, []); test.equal(datum, "a"); div.call(customExit, "a"); div.call(customExit, "b"); div.call(customExit, []); test.equal(datum, "b"); // Fails here, uses "a" test.end(); });
var tape = require("tape"), jsdom = require("jsdom"), d3_transition = require("d3-transition"), d3_selection = require("d3-selection"), d3_component = require("../"), d3 = Object.assign(d3_selection, d3_component); var customExit = d3.component("p") .destroy(function (selection){ return selection.transition().duration(10); }); tape("A component should be able to specify custom destroy transitions.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(customExit); test.equal(div.html(), "<p></p>"); div.call(customExit, []); // The transition is happening, so DOM element not removed yet. test.equal(div.html(), "<p></p>"); // DOM element removed after transition ends. setTimeout(function (){ test.equal(div.html(), ""); test.end(); }, 30); // The transition lasts 10 ms, so it should be done after 30. });
Fix warning in core test
package net.tomp2p.utils; import java.util.ArrayList; import java.util.Collection; import org.junit.Assert; import org.junit.Test; public class TestUtils { @Test public void testDifference1() { Collection<String> collection1 = new ArrayList<String>(); Collection<String> result = new ArrayList<String>(); Collection<String> collection2 = new ArrayList<String>(); Collection<String> collection3 = new ArrayList<String>(); // collection1.add("hallo"); collection1.add("test"); // collection2.add("test"); collection2.add("hallo"); Utils.difference(collection1, result, collection2, collection3); Assert.assertEquals(0, result.size()); } }
package net.tomp2p.utils; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.junit.Test; public class TestUtils { @SuppressWarnings("unchecked") @Test public void testDifference1() { Collection<String> collection1 = new ArrayList<String>(); Collection<String> result = new ArrayList<String>(); Collection<String> collection2 = new ArrayList<String>(); Collection<String> collection3 = new ArrayList<String>(); // collection1.add("hallo"); collection1.add("test"); // collection2.add("test"); collection2.add("hallo"); Utils.difference(collection1, result, collection2, collection3); Assert.assertEquals(0, result.size()); } }
Fix broken order of arguments in send_email Ticket #342
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(content, subject, user): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(user, content, subject): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
Add code to unregister the service worker for now
import firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/database'; import marked from 'marked'; import 'normalize.css'; import prism from 'prismjs'; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import config from './config'; import './global.css'; import App from './components/App'; import { unregister } from './utils/registerServiceWorker'; unregister(); firebase.initializeApp(config[process.env.NODE_ENV]); prism.languages.js = prism.languages.javascript; marked.setOptions({ highlight(code, language) { const grammar = prism.languages[language] || prism.languages.markup; return prism.highlight(code, grammar); }, langPrefix: 'language-', }); ReactDOM.render( <Router> <App /> </Router>, document.getElementById('app'), );
import firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/database'; import marked from 'marked'; import 'normalize.css'; import prism from 'prismjs'; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import config from './config'; import './global.css'; import App from './components/App'; import registerServiceWorker from './utils/registerServiceWorker'; firebase.initializeApp(config[process.env.NODE_ENV]); prism.languages.js = prism.languages.javascript; marked.setOptions({ highlight(code, language) { const grammar = prism.languages[language] || prism.languages.markup; return prism.highlight(code, grammar); }, langPrefix: 'language-', }); ReactDOM.render( <Router> <App /> </Router>, document.getElementById('app'), ); registerServiceWorker();
Fix of detection of dev and test script names
<?php namespace Coral\SiteBundle\Twig; use Symfony\Component\HttpFoundation\RequestStack; use Coral\SiteBundle\Content\Node; class PathExtension extends \Twig_Extension { /** * Request stack * * @var RequestStack */ protected $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } /** * @codeCoverageIgnore */ public function getFunctions() { return array( new \Twig_SimpleFunction('coral_path', array($this, 'path')), ); } public function path(Node $node) { if($node->hasProperty('redirect')) { return $node->getProperty('redirect'); } $request = $this->requestStack->getCurrentRequest(); $path = $node->getUri(); $scriptName = $request->getScriptName(); if((strpos($scriptName, '_dev') !== false) || ((strpos($scriptName, '_test') !== false))) { return $scriptName . $path; } return $path; } public function getName() { return 'path_extension'; } }
<?php namespace Coral\SiteBundle\Twig; use Symfony\Component\HttpFoundation\RequestStack; use Coral\SiteBundle\Content\Node; class PathExtension extends \Twig_Extension { /** * Request stack * * @var RequestStack */ protected $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } /** * @codeCoverageIgnore */ public function getFunctions() { return array( new \Twig_SimpleFunction('coral_path', array($this, 'path')), ); } public function path(Node $node) { if($node->hasProperty('redirect')) { return $node->getProperty('redirect'); } $request = $this->requestStack->getCurrentRequest(); $path = $node->getUri(); $scriptName = $request->getScriptName(); if(strpos($scriptName, '_') !== false) { return $scriptName . $path; } return $path; } public function getName() { return 'path_extension'; } }
Add report domain to registry. Signed-off-by: Michael Handler <331a76cd0f162b0218893a3dfa4df5a8bf659d1e@fullstop.at>
/** Copyright 2010 OpenEngSB Division, Vienna University of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE\-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openengsb.drools; import java.util.HashMap; import java.util.Map; public class DomainRegistry { public final static Map<String, Class<? extends Domain>> domains = new HashMap<String, Class<? extends Domain>>(); static { domains.put("helper", MessageHelper.class); domains.put("issue", DroolsIssuesDomain.class); domains.put("notification", NotificationDomain.class); domains.put("scm", ScmDomain.class); domains.put("test", TestDomain.class); domains.put("build", BuildDomain.class); domains.put("deploy", DeployDomain.class); domains.put("report", ReportDomain.class); } private DomainRegistry() { throw new AssertionError(); } }
/** Copyright 2010 OpenEngSB Division, Vienna University of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE\-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openengsb.drools; import java.util.HashMap; import java.util.Map; public class DomainRegistry { public final static Map<String, Class<? extends Domain>> domains = new HashMap<String, Class<? extends Domain>>(); static { domains.put("helper", MessageHelper.class); domains.put("issue", DroolsIssuesDomain.class); domains.put("notification", NotificationDomain.class); domains.put("scm", ScmDomain.class); domains.put("test", TestDomain.class); domains.put("build", BuildDomain.class); domains.put("deploy", DeployDomain.class); } private DomainRegistry() { throw new AssertionError(); } }
Use [a-z]* pattern to match project ids
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'(.*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'(.*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'(.*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
Add index test for Hadamard+MatMul mix
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct from sympy.matrices import ShapeError from sympy import symbols from sympy.utilities.pytest import raises def test_HadamardProduct(): n, m, k = symbols('n,m,k') Z = MatrixSymbol('Z', n, n) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, k) assert HadamardProduct(A, B, A).shape == A.shape raises(ShapeError, lambda: HadamardProduct(A, B.T)) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1] mix = HadamardProduct(Z*A, B)*C assert mix.shape == (n, k) def test_mixed_indexing(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) Z = MatrixSymbol('Z', 2, 2) assert (X*HadamardProduct(Y, Z))[0, 0] == \ X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
from sympy.matrices.expressions import MatrixSymbol, HadamardProduct from sympy.matrices import ShapeError from sympy import symbols from sympy.utilities.pytest import raises def test_HadamardProduct(): n, m, k = symbols('n,m,k') Z = MatrixSymbol('Z', n, n) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, k) assert HadamardProduct(A, B, A).shape == A.shape raises(ShapeError, lambda: HadamardProduct(A, B.T)) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert HadamardProduct(A, 2*B, -A)[1, 1] == -2 * A[1, 1]**2 * B[1, 1] mix = HadamardProduct(Z*A, B)*C assert mix.shape == (n, k)
Disable crashlytics on debug builds.
/* * Copyright 2017 Arunkumar * * 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 arun.com.chameleonskinforkwlp; import android.app.Application; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import io.fabric.sdk.android.Fabric; import timber.log.Timber; public class Chameleon extends Application { @Override public void onCreate() { super.onCreate(); CrashlyticsCore core = new CrashlyticsCore.Builder() .disabled(BuildConfig.DEBUG) .build(); Fabric.with(this, new Crashlytics.Builder().core(core).build()); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } }
/* * Copyright 2017 Arunkumar * * 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 arun.com.chameleonskinforkwlp; import android.app.Application; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; import timber.log.Timber; public class Chameleon extends Application { @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } }
Remove call to the method connect() on the connection
/* * ***************************************************** * Copyright VMware, Inc. 2010-2012. All Rights Reserved. * ***************************************************** * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS # OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY # DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY # QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. */ package com.vmware.connection.helpers; import com.vmware.connection.Connection; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.VimPortType; public abstract class BaseHelper { Connection connection = null; public BaseHelper(final Connection connection) { this.connection = connection; } public BaseHelper() { } public class HelperException extends RuntimeException { public HelperException(Throwable cause) { super(cause); } } }
/* * ***************************************************** * Copyright VMware, Inc. 2010-2012. All Rights Reserved. * ***************************************************** * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS # OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY # DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY # QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. */ package com.vmware.connection.helpers; import com.vmware.connection.Connection; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.VimPortType; public abstract class BaseHelper { Connection connection = null; public BaseHelper(final Connection connection) { this.connection = connection.connect(); } public BaseHelper() { } public class HelperException extends RuntimeException { public HelperException(Throwable cause) { super(cause); } } }
Make minor edit to db help output
const OS = require("os"); const serveCommand = require("./commands/serve"); const usage = "truffle db <sub-command> [options]" + OS.EOL + " Available sub-commands: " + OS.EOL + " serve \tStart the GraphQL server"; const command = { command: "db", description: "Database interface commands", builder: function (yargs) { return yargs.command(serveCommand).demandCommand(); }, subCommands: { serve: { help: serveCommand.help, description: serveCommand.description } }, help: { usage, options: [] }, run: async function (args) { const [subCommand] = args._; switch (subCommand) { case "serve": await serveCommand.run(args); break; default: console.log(`Unknown command: ${subCommand}`); } } }; module.exports = command;
const OS = require("os"); const serveCommand = require("./commands/serve"); const usage = "truffle db <sub-command> [options]" + OS.EOL + OS.EOL + " Available sub-commands: " + OS.EOL + OS.EOL + " serve \tStart the GraphQL server" + OS.EOL; const command = { command: "db", description: "Database interface commands", builder: function (yargs) { return yargs.command(serveCommand).demandCommand(); }, subCommands: { serve: { help: serveCommand.help, description: serveCommand.description } }, help: { usage, options: [] }, run: async function (args) { const [subCommand] = args._; switch (subCommand) { case "serve": await serveCommand.run(args); break; default: console.log(`Unknown command: ${subCommand}`); } } }; module.exports = command;
Clean up a little bit
from setuptools import setup from fdep import __VERSION__ try: ldsc = open("README.md").read() except: ldsc = "" setup( name="fdep", packages=['fdep'], version=__VERSION__, author="Checkr", author_email="eng@checkr.com", url="http://github.com/checkr/fdep", license="MIT LICENSE", description="Fdep is a simple, easy-to-use, production-ready tool/library written in Python to download datasets, misc. files for your machine learning projects.", long_description=ldsc, entry_points={ 'console_scripts': ['fdep=fdep.__main__:main'] }, install_requires=[ 'PyYAML==3.12', 'boto3==1.4.0', 'requests==2.11.1', 'colorama==0.3.7', 'tqdm==4.8.4' ] )
from setuptools import setup from fdep import __VERSION__ try: ldsc = open("README.md").read() except: ldsc = "" setup( name="fdep", packages=['fdep'], version=__VERSION__, author="Checkr", author_email="eng@checkr.com", url="http://github.com/checkr/fdep", license="MIT LICENSE", description="Fdep is a simple, easy-to-use, production-ready tool/library written in Python to download datasets, misc. files for your machine learning projects.", long_description=ldsc, entry_points={ 'console_scripts': [ 'fdep = fdep.__main__:main' ] }, install_requires=[ 'PyYAML==3.12', 'boto3==1.4.0', 'requests==2.11.1', 'colorama==0.3.7', 'tqdm==4.8.4' ] )
Use an EnumMap rather than a HashMap.
/** * Copyright 2011 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.android; import android.graphics.Typeface; import java.util.EnumMap; import java.util.Map; import playn.core.AbstractFont; class AndroidFont extends AbstractFont { public final Typeface typeface; public AndroidFont(String name, Style style, float size) { super(name, style, size); this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style)); } protected static final Map<Style,Integer> TO_ANDROID_STYLE = new EnumMap<Style,Integer>(Style.class); static { TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL); TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD); TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC); TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC); } }
/** * Copyright 2011 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.android; import android.graphics.Typeface; import java.util.HashMap; import java.util.Map; import playn.core.AbstractFont; class AndroidFont extends AbstractFont { public final Typeface typeface; public AndroidFont(String name, Style style, float size) { super(name, style, size); this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style)); } protected static final Map<Style,Integer> TO_ANDROID_STYLE = new HashMap<Style,Integer>(); static { TO_ANDROID_STYLE.put(Style.PLAIN, Typeface.NORMAL); TO_ANDROID_STYLE.put(Style.BOLD, Typeface.BOLD); TO_ANDROID_STYLE.put(Style.ITALIC, Typeface.ITALIC); TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC); } }
docs: Add comments to label prop types for docgeninfo
import React, { Component } from "react"; import PropTypes from "prop-types"; import { ThemeContext } from "@hig/themes"; import stylesheet from "./stylesheet"; class Label extends Component { static propTypes = { /** * Content of the label, including the label text */ children: PropTypes.node, /** * Dims label text, signifying the related input or control is disabled */ disabled: PropTypes.bool, /** * Reference to the HTML ID of the form element that this label represents */ htmlFor: PropTypes.string, /** * Reference to the HTML ID of the form that contains this label */ form: PropTypes.string }; render() { const { children, htmlFor, form, disabled } = this.props; return ( <ThemeContext.Consumer> {({ themeData }) => { const styles = stylesheet({ disabled }, themeData); return ( <label htmlFor={htmlFor} form={form} style={styles.label}> {children} </label> ); }} </ThemeContext.Consumer> ); } } export default Label;
import React, { Component } from "react"; import PropTypes from "prop-types"; import { ThemeContext } from "@hig/themes"; import stylesheet from "./stylesheet"; class Label extends Component { static propTypes = { children: PropTypes.node, disabled: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types htmlFor: PropTypes.string, form: PropTypes.string }; render() { const { children, htmlFor, form, disabled } = this.props; return ( <ThemeContext.Consumer> {({ themeData }) => { const styles = stylesheet({ disabled }, themeData); return ( <label htmlFor={htmlFor} form={form} style={styles.label}> {children} </label> ); }} </ThemeContext.Consumer> ); } } export default Label;
Make `url` fixture less generic in preparation for additional endpoints
import pytest from mock import patch @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
import pytest from mock import patch @pytest.fixture def url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, url): assert browser.get_json(url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, url): assert browser.get_json(url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, url, mocked_run, settings): browser.post_json(url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
Fix a bug where an extra </script> tag was sitting inside a <script> block.
{% load djblets_utils %} /* * Initial state from the server. These should all be thought of as * constants, not state. */ {% if not error %} var gBugTrackerURL = "{{review_request.repository.bug_tracker}}"; var gReviewRequestPath = '{{review_request.get_absolute_url}}'; var gReviewRequestId = "{{review_request.id}}"; var gReviewRequestSummary = "{{review_request.summary}}"; var gReviewPending = {% if review %}true{% else %}false{% endif %}; {% ifuserorperm review_request.submitter "reviews.can_edit_reviewrequest" %} {% ifequal review_request.status 'P' %} var gEditable = true; {% endifequal %} {% endifuserorperm %} {% else %}{# error #} var gReviewPending = false; {% endif %}{# !error #} var gUserURL = "{% url user user %}"; var gUserAuthenticated = {{user.is_authenticated|lower}}; {% if not user.is_anonymous %} var gUserFullName = "{{user|user_displayname}}"; {% endif %}
{% load djblets_utils %} /* * Initial state from the server. These should all be thought of as * constants, not state. */ {% if not error %} var gBugTrackerURL = "{{review_request.repository.bug_tracker}}"; var gReviewRequestPath = '{{review_request.get_absolute_url}}'; var gReviewRequestId = "{{review_request.id}}"; var gReviewRequestSummary = "{{review_request.summary}}"; var gReviewPending = {% if review %}true{% else %}false{% endif %}; {% ifuserorperm review_request.submitter "reviews.can_edit_reviewrequest" %} {% ifequal review_request.status 'P' %} var gEditable = true; {% endifequal %} {% endifuserorperm %} {% else %}{# error #} var gReviewPending = false; {% endif %}{# !error #} var gUserURL = "{% url user user %}"; var gUserAuthenticated = {{user.is_authenticated|lower}}; {% if not user.is_anonymous %} var gUserFullName = "{{user|user_displayname}}"; {% endif %} </script>
Add missing exports for backwardConnectionArgs and forwardConnectionArgs
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // Helpers for creating connection types in the schema export { backwardConnectionArgs, connectionArgs, connectionDefinitions, forwardConnectionArgs, } from './connection/connection.js'; // Helpers for creating connections from arrays export { connectionFromArray, connectionFromArraySlice, connectionFromPromisedArray, connectionFromPromisedArraySlice, cursorForObjectInConnection, cursorToOffset, getOffsetWithDefault, offsetToCursor, } from './connection/arrayconnection.js'; // Helper for creating mutations with client mutation IDs export { mutationWithClientMutationId, } from './mutation/mutation.js'; // Helper for creating node definitions export { nodeDefinitions, } from './node/node.js'; // Utilities for creating global IDs in systems that don't have them. export { fromGlobalId, globalIdField, toGlobalId, } from './node/node.js';
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // Helpers for creating connection types in the schema export { connectionArgs, connectionDefinitions, } from './connection/connection.js'; // Helpers for creating connections from arrays export { connectionFromArray, connectionFromArraySlice, connectionFromPromisedArray, connectionFromPromisedArraySlice, cursorForObjectInConnection, cursorToOffset, getOffsetWithDefault, offsetToCursor, } from './connection/arrayconnection.js'; // Helper for creating mutations with client mutation IDs export { mutationWithClientMutationId, } from './mutation/mutation.js'; // Helper for creating node definitions export { nodeDefinitions, } from './node/node.js'; // Utilities for creating global IDs in systems that don't have them. export { fromGlobalId, globalIdField, toGlobalId, } from './node/node.js';
Add Trash explosions on lifeTime end.
/*jshint bitwise: false*/ /*globals define*/ define([ 'entities/physics-entity', 'entities/explosion', 'config/colors', 'config/material' ], function( PhysicsEntity, Explosion, Colors, Material ) { 'use strict'; function Trash( options, lifeTime ) { PhysicsEntity.call( this, options ); // In seconds. this.lifeTime = lifeTime || 0; this.time = 0; } Trash.prototype = new PhysicsEntity(); Trash.prototype.constructor = Trash; Trash.prototype.update = function( dt ) { PhysicsEntity.prototype.update.call( this, dt ); this.time += dt; var explosion, fill; if ( this.time > this.lifeTime ) { this.game.removed.push( this ); if ( this.material & Material.MATTER ) { fill = Colors.Explosion.MATTER; } else if ( this.material & Material.ANTIMATTER ) { fill = Colors.Explosion.ANTIMATTER; } if ( fill ) { explosion = new Explosion( this.x, this.y ); explosion.fill.set( fill ); this.game.add( explosion ); } } }; Trash.prototype.draw = function( ctx ) { ctx.lineJoin = 'round'; PhysicsEntity.prototype.draw.call( this, ctx ); ctx.lineJoin = 'miter'; }; return Trash; });
/*globals define*/ define([ 'entities/physics-entity' ], function( PhysicsEntity ) { 'use strict'; function Trash( options, lifeTime ) { PhysicsEntity.call( this, options ); // In seconds. this.lifeTime = lifeTime || 0; this.time = 0; } Trash.prototype = new PhysicsEntity(); Trash.prototype.constructor = Trash; Trash.prototype.update = function( dt ) { PhysicsEntity.prototype.update.call( this, dt ); this.time += dt; if ( this.time > this.lifeTime ) { this.game.removed.push( this ); } }; Trash.prototype.draw = function( ctx ) { ctx.lineJoin = 'round'; PhysicsEntity.prototype.draw.call( this, ctx ); ctx.lineJoin = 'miter'; }; return Trash; });
Add source-map-support only for node env
const path = require("path"); const ROOT = require("./config/path-helper").ROOT; const WebpackIsomorphicTools = require("webpack-isomorphic-tools"); require("source-map-support").install({ environment: "node" }); function hotReloadTemplate(templatesDir) { require("marko/hot-reload").enable(); require("chokidar") .watch(templatesDir) .on("change", filename => { require("marko/hot-reload").handleFileModified(path.join(ROOT, filename)); }); } global.webpackIsomorphicTools = new WebpackIsomorphicTools( require("./config/webpack/webpack-isomorphic-tools") ); // to get the node require instead of dynamic require by webpack global.nodeRequire = require; global.webpackIsomorphicTools .server(ROOT, () => { if (process.env.NODE_DEBUGGER) { require("babel-core/register"); require("./app/server"); } else { require("./build/server"); } if (process.env.NODE_ENV === "development") { hotReloadTemplate("./app/server/application/templates/**/*.marko"); } });
const path = require("path"); const ROOT = require("./config/path-helper").ROOT; const WebpackIsomorphicTools = require("webpack-isomorphic-tools"); function hotReloadTemplate(templatesDir) { require("marko/hot-reload").enable(); require("chokidar") .watch(templatesDir) .on("change", filename => { require("marko/hot-reload").handleFileModified(path.join(ROOT, filename)); }); } global.webpackIsomorphicTools = new WebpackIsomorphicTools( require("./config/webpack/webpack-isomorphic-tools") ); // to get the node require instead of dynamic require by webpack global.nodeRequire = require; global.webpackIsomorphicTools .server(ROOT, () => { require("source-map-support").install(); if (process.env.NODE_DEBUGGER) { require("babel-core/register"); require("./app/server"); } else { require("./build/server"); } if (process.env.NODE_ENV === "development") { hotReloadTemplate("./app/server/application/templates/**/*.marko"); } });
Update array to literal notation
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.createRecord('parseUser'); }, actions: { createUser: function(user) { var interestArray = []; $('input[name=interest]').each(function() { interestArray.push($(this).val()); }); user.set('email', user.get('username')); user.set('interests', interestArray); user.save().then(function() { this.get('session').authenticate('authenticator:parse-token', { sessionToken: user.get('sessionToken') }); this.transitionTo('index'); }.bind(this)); } } });
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.createRecord('parseUser'); }, actions: { createUser: function(user) { var interestArray = new Array(); $('input[name=interest]').each(function() { interestArray.push($(this).val()); }); user.set('email', user.get('username')); user.set('interests', interestArray); user.save().then(function() { this.get('session').authenticate('authenticator:parse-token', { sessionToken: user.get('sessionToken') }); this.transitionTo('index'); }.bind(this)); } } });
Fix a typo in precompute_word_count command help text.
import tqdm from django.core.management.base import BaseCommand import manoseimas.common.utils.words as words_utils import manoseimas.mps_v2.models as mpsv2_models class Command(BaseCommand): help = 'Precompute word counts for stenogram statements' def handle(self, **options): total = mpsv2_models.StenogramStatement.objects.count() statements = mpsv2_models.StenogramStatement.objects.all() for statement in tqdm.tqdm(statements): statement.word_count = words_utils.get_word_count(statement.text) statement.save() self.stdout.write( 'Successfully updated word counts for %d statements.' % total )
import tqdm from django.core.management.base import BaseCommand import manoseimas.common.utils.words as words_utils import manoseimas.mps_v2.models as mpsv2_models class Command(BaseCommand): help = 'Procompute word counts for stenogram statements' def handle(self, **options): total = mpsv2_models.StenogramStatement.objects.count() statements = mpsv2_models.StenogramStatement.objects.all() for statement in tqdm.tqdm(statements): statement.word_count = words_utils.get_word_count(statement.text) statement.save() self.stdout.write( 'Successfully updated word counts for %d statements.' % total )
Make the code evaluation rule use a UnicodeString rather than a NormalizedString, as part of the migration away from NormalizedStrings.
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwar # 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. """Rules for CodeEvaluation objects.""" __author__ = 'Koji Ashida' from extensions.rules import base class OutputEquals(base.CodeEvaluationRule): description = ( 'has output equal to {{x|UnicodeString}} (collapsing spaces)') is_generic = False def _evaluate(self, subject): normalized_result = ' '.join(subject['output'].split()) normalized_expected_output = ' '.join(self.x.split()) return normalized_result == normalized_expected_output class ResultsInError(base.CodeEvaluationRule): description = 'results in an error when run' is_generic = False def _evaluate(self, subject): error = subject['error'].strip() return bool(error)
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwar # 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. """Rules for CodeEvaluation objects.""" __author__ = 'Koji Ashida' from extensions.rules import base class OutputEquals(base.CodeEvaluationRule): description = ( 'has output equal to {{x|NormalizedString}} (collapsing spaces)') is_generic = False def _evaluate(self, subject): normalized_result = ' '.join(subject['output'].split()) normalized_expected_output = ' '.join(self.x.split()) return normalized_result == normalized_expected_output class ResultsInError(base.CodeEvaluationRule): description = 'results in an error when run' is_generic = False def _evaluate(self, subject): error = subject['error'].strip() return bool(error)
Handle Get request if id is present
<?php require_once "autoloader.php"; require_once "/lib/xsrf.php"; require_once("/etc/apache2/teamcuriosity-mysql/encrypted-config.php"); use Edu\Cnm\TeamCuriosity; /** * api for the NewsArticle class * * @author Anthony Williams <awilliams144@cnm.edu> **/ //verify the session, start if not active if(session_status() !== PHP_SESSION_ACTIVE) { session_start(); } //prepare an empty reply $reply = new stdClass(); $reply->status = 200; $reply->data = null; try { //grab the mySQL connection $pdo = connectToEncryptedMySQL("/etc/apache2/teamcuriosity-mysql/newsArticle.ini"); //determine which HTTP method was used $method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"]; //sanitize input $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT); //make sure the id is valid for methods that require it if(($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) { throw(new InvalidArgumentException("id cannot be empty or negative", 405)); } // handle GET request - if id is present, that NewsArticle is returned, otherwise all NewsArticles are returned if($method === "GET") { //set XSRF cookie setXsrfCookie();
<?php require_once "autoloader.php"; require_once "/lib/xsrf.php"; require_once("/etc/apache2/teamcuriosity-mysql/encrypted-config.php"); use Edu\Cnm\TeamCuriosity; /** * api for the NewsArticle class * * @author Anthony Williams <awilliams144@cnm.edu> **/ //verify the session, start if not active if(session_status() !== PHP_SESSION_ACTIVE) { session_start(); } //prepare an empty reply $reply = new stdClass(); $reply->status = 200; $reply->data = null; try { //grab the mySQL connection $pdo = connectToEncryptedMySQL("/etc/apache2/teamcuriosity-mysql/newsArticle.ini"); //determine which HTTP method was used $method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"]; //sanitize input $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT); //make sure the id is valid for methods that require it if(($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) { throw(new InvalidArgumentException("id cannot be empty or negative", 405)); }
Fix issue in item details route
import React, { Component } from 'react' import { Router, Route, browserHistory, } from 'react-router' import { Provider } from 'react-redux' import configureStore from '../store/configure-store' import ClassificationExplorer from './classification-explorer' import ClassificationDetails from './classification-details' import ItemDetails from './item-details' import { path } from '../router-mapping' const store = configureStore() export default class Root extends Component { render() { return ( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={ClassificationExplorer} /> <Route path={path.classificationDetails} component={ClassificationDetails} /> <Route path={path.itemDetails} component={ItemDetails} /> </Router> </Provider> ) } }
import React, { Component } from 'react' import { Router, Route, browserHistory, } from 'react-router' import { Provider } from 'react-redux' import configureStore from '../store/configure-store' import ClassificationExplorer from './classification-explorer' import ClassificationDetails from './classification-details' import ItemDetails from './item-details' import { path } from '../router-mapping' const store = configureStore() export default class Root extends Component { render() { return ( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={ClassificationExplorer} /> <Route path={path.classificationDetails} component={ClassificationDetails} /> <Route path={path.itemDetails.pattern} component={ItemDetails} /> </Router> </Provider> ) } }
Add default value to url field
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddUrlToBadges extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::connection('mysql')->table('osu_badges', function (Blueprint $table) { $table->string('url')->default(''); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::connection('mysql')->table('osu_badges', function (Blueprint $table) { $table->dropColumn('url'); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddUrlToBadges extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::connection('mysql')->table('osu_badges', function (Blueprint $table) { $table->string('url'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::connection('mysql')->table('osu_badges', function (Blueprint $table) { $table->dropColumn('url'); }); } }