text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add option to not break pipe when sass syntax error
'use strict'; var config = require('../config'); var gulp = require('gulp'); var sass = require('gulp-sass'); var gulpif = require('gulp-if'); var handleErrors = require('../util/handleErrors'); var browserSync = require('browser-sync'); var autoprefixer = require('gulp-autoprefixer'); gulp.task('styles', function () { return gulp.src(config.styles.src) .pipe(sass({ includePaths: [ './node_modules/bootstrap-sass/assets/stylesheets', ], sourceComments: global.isProd ? 'none' : 'map', sourceMap: 'sass', outputStyle: global.isProd ? 'compressed' : 'nested', errLogToConsole: true })) .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8")) .on('error', handleErrors) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true }))); });
'use strict'; var config = require('../config'); var gulp = require('gulp'); var sass = require('gulp-sass'); var gulpif = require('gulp-if'); var handleErrors = require('../util/handleErrors'); var browserSync = require('browser-sync'); var autoprefixer = require('gulp-autoprefixer'); gulp.task('styles', function () { return gulp.src(config.styles.src) .pipe(sass({ includePaths: [ './node_modules/bootstrap-sass/assets/stylesheets', ], sourceComments: global.isProd ? 'none' : 'map', sourceMap: 'sass', outputStyle: global.isProd ? 'compressed' : 'nested' })) .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8")) .on('error', handleErrors) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true }))); });
Fix pluralization on program years route
import Ember from 'ember'; var Router = Ember.Router.extend({ location: IliosENV.locationType }); Router.map(function() { this.resource('dashboard', function() { this.route('day'); this.route('week'); this.route('month'); this.route('year'); }); this.resource('programs', function(){ this.route('new'); this.resource('program', { path: ':program_id' }, function(){ this.route('index'); this.route('edit'); this.route('newyear'); this.resource('programyear', { path: 'years/:program_year_id' }, function(){ this.route('index'); this.route('managecompetencies'); this.route('manageobjectives'); this.route('managedirectors'); this.route('managetopics'); this.route('managestewardingschools'); }); }); }); }); export default Router;
import Ember from 'ember'; var Router = Ember.Router.extend({ location: IliosENV.locationType }); Router.map(function() { this.resource('dashboard', function() { this.route('day'); this.route('week'); this.route('month'); this.route('year'); }); this.resource('programs', function(){ this.route('new'); this.resource('program', { path: ':program_id' }, function(){ this.route('index'); this.route('edit'); this.route('newyear'); this.resource('programyear', { path: 'year/:program_year_id' }, function(){ this.route('index'); this.route('managecompetencies'); this.route('manageobjectives'); this.route('managedirectors'); this.route('managetopics'); this.route('managestewardingschools'); }); }); }); }); export default Router;
Use 709 matrix when converting rgb to yuv
#!/usr/bin/env python # -*- coding: utf-8 -*- import hyperspeed.afterscript title = 'H264.720p' cmd = '-vsync 0 -movflags faststart -crf 20 -minrate 0 -maxrate 4M -bufsize 15M -filter_complex "scale=1280:720:out_color_matrix=bt709,setsar=1" -pix_fmt yuv420p -vcodec libx264 -c:a aac -b:a 160k -strict -2 -ac 2 -ar 44100 -acodec aac -af pan=stereo:c0=c0:c1=c1' # Path relative to primary output folder of render:P # default_output = '[project]_[render_name].[codec].mov' # Absolute path: default_output = '/Volumes/SAN3/Masters/[project]/[project]_[rendername]/[project]_[rendername].h264.720p.mov' hyperspeed.afterscript.AfterscriptFfmpeg(__file__, cmd, default_output, title) hyperspeed.afterscript.gtk.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import hyperspeed.afterscript title = 'H264.720p' cmd = '-vsync 0 -movflags faststart -crf 20 -minrate 0 -maxrate 4M -bufsize 15M -filter_complex "scale=1280:720,setsar=1" -pix_fmt yuv420p -vcodec libx264 -c:a aac -b:a 160k -strict -2 -ac 2 -ar 44100 -acodec aac -af pan=stereo:c0=c0:c1=c1' # Path relative to primary output folder of render:P # default_output = '[project]_[render_name].[codec].mov' # Absolute path: default_output = '/Volumes/SAN3/Masters/[project]/[project]_[rendername]/[project]_[rendername].h264.720p.mov' hyperspeed.afterscript.AfterscriptFfmpeg(__file__, cmd, default_output, title) hyperspeed.afterscript.gtk.main()
Fix expected value for youtube api.
var lt = require('loopback-testing'); var chai = require('chai'); var assert = chai.assert; //path to app.js or server.js var app = require('../../server/server.js'); describe('/api/youtube', function() { lt.beforeEach.withApp(app); lt.describe.whenCalledRemotely('GET', '/api/youtube/property?videoId=eZHEnPCEe0o', function() { it('YouTube動画のタイトルが取得できる', function() { var property = this.res.body.property; assert.equal(this.res.statusCode, 200); assert.equal(property.videoId, "eZHEnPCEe0o"); assert.equal(property.title, "Do Cool Things That Matter - Work at Google"); }); }); lt.describe.whenCalledRemotely('GET', '/api/youtube/property?videoId=xxxlsfjkdjwo', function() { it('存在しないYouTube Video IDが渡された際は404応答', function() { assert.equal(this.res.statusCode, 404); }); }); });
var lt = require('loopback-testing'); var chai = require('chai'); var assert = chai.assert; //path to app.js or server.js var app = require('../../server/server.js'); describe('/api/youtube', function() { lt.beforeEach.withApp(app); lt.describe.whenCalledRemotely('GET', '/api/youtube/property?videoId=eZHEnPCEe0o', function() { it('YouTube動画のタイトルが取得できる', function() { var property = this.res.body.property; assert.equal(this.res.statusCode, 200); assert.equal(property.videoId, "eZHEnPCEe0o"); assert.equal(property.title, "Do Cool Things That Matter"); }); }); lt.describe.whenCalledRemotely('GET', '/api/youtube/property?videoId=xxxlsfjkdjwo', function() { it('存在しないYouTube Video IDが渡された際は404応答', function() { assert.equal(this.res.statusCode, 404); }); }); });
Add values to new field one at a time to avoid adding an ArrayList object.
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This stage will rename the field on a document. * @author kwatters * */ public class RenameField extends AbstractStage { private String oldName = "fielda"; private String newName = "fieldb"; @Override public void startStage(StageConfiguration config) { // TODO Auto-generated method stub if (config != null) { oldName = config.getProperty("oldName"); newName = config.getProperty("newName"); } } @Override public List<Document> processDocument(Document doc) { if (!doc.hasField(oldName)) { return null; } for (Object o : doc.getField(oldName)) { doc.addToField(newName, o); } doc.removeField(oldName); return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // TODO Auto-generated method stub } }
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This stage will rename the field on a document. * @author kwatters * */ public class RenameField extends AbstractStage { private String oldName = "fielda"; private String newName = "fieldb"; @Override public void startStage(StageConfiguration config) { // TODO Auto-generated method stub if (config != null) { oldName = config.getProperty("oldName"); newName = config.getProperty("newName"); } } @Override public List<Document> processDocument(Document doc) { if (!doc.hasField(oldName)) { return null; } doc.addToField(newName, doc.getField(oldName)); doc.removeField(oldName); return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // TODO Auto-generated method stub } }
ENH: Add a modified lut-data-generating script to use pickle, rather than npz
#!/usr/bin/env python """ Script used to create lut lists used by mayavi from matplotlib colormaps. This requires matlplotlib to be installed and should not be ran by the user, but only once in a while to synchronize with MPL developpement. """ # Authors: Frederic Petit <fredmfp@gmail.com>, # Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2007-2009, Enthought, Inc. # License: BSD Style. import os import numpy as np from matplotlib.cm import datad, get_cmap from enthought.mayavi.core import lut as destination_module from enthought.persistence import state_pickler target_dir = os.path.dirname(destination_module.__file__) values = np.linspace(0., 1., 256) lut_dic = {} for name in datad.keys(): if name.endswith('_r'): continue lut_dic[name] = get_cmap(name)(values.copy()) out_name = os.path.join(target_dir, 'pylab_luts.pkl') state_pickler.dump(lut_dic, out_name)
#!/usr/bin/env python """ Script used to create lut lists used by mayavi from matplotlib colormaps. This requires matlplotlib to be installed and should not be ran by the user, but only once in a while to synchronize with MPL developpement. """ # Authors: Frederic Petit <fredmfp@gmail.com>, # Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. from matplotlib.cm import datad, get_cmap import numpy as np from enthought.mayavi.core import lut as destination_module import os target_dir = os.path.dirname(destination_module.__file__) values = np.linspace(0., 1., 256) lut_dic = {} for name in datad.keys(): if name.endswith('_r'): continue lut_dic[name] = get_cmap(name)(values.copy()) out_name = os.path.join(target_dir, 'pylab_luts.npz') np.savez(out_name, **lut_dic)
Bump version: 0.1.9 → 0.1.10
# -*- coding: utf-8 -* """ `grappa` provides two different testing styles: `should` and `expect`. should ------ Example using ``should`` style:: from grappa import should should('foo').be.equal.to('foo') 'foo' | should.be.equal.to('foo') expect ------ Example using ``expect`` style:: from grappa import expect expect([1, 2, 3]).to.contain([2, 3]) [1, 2, 3] | expect.to.contain([2, 3]) For assertion operators and aliases, see `operators documentation`_. .. _`operators documentation`: operators.html Reference --------- """ # Export public API module members from .api import * # noqa from .api import __all__ # noqa # Package metadata __author__ = 'Tomas Aparicio' __license__ = 'MIT' # Current package version __version__ = '0.1.10'
# -*- coding: utf-8 -* """ `grappa` provides two different testing styles: `should` and `expect`. should ------ Example using ``should`` style:: from grappa import should should('foo').be.equal.to('foo') 'foo' | should.be.equal.to('foo') expect ------ Example using ``expect`` style:: from grappa import expect expect([1, 2, 3]).to.contain([2, 3]) [1, 2, 3] | expect.to.contain([2, 3]) For assertion operators and aliases, see `operators documentation`_. .. _`operators documentation`: operators.html Reference --------- """ # Export public API module members from .api import * # noqa from .api import __all__ # noqa # Package metadata __author__ = 'Tomas Aparicio' __license__ = 'MIT' # Current package version __version__ = '0.1.9'
Fix error off by one error related to constructor with stopPoint, added output
public class FizzBuzzTester{ public static void main(String[] args){ FizzBuzzer firstFizz = new FizzBuzzer(20); System.out.println(firstFizz); //output: 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz } } class FizzBuzzer{ public int fizz; public int buzz; public int stopPoint; public FizzBuzzer(){ fizz = 3; buzz = 5; stopPoint = 30; }; public FizzBuzzer(int stop){ this(); stopPoint = stop + 1; } public String toString(){ String temp = ""; for (int i = 1; i < stopPoint; i++){ if (i % 3 == 0) { temp += "fizz"; } if (i % 5 == 0) { temp += "buzz"; } if (i % 3 != 0 && i % 5 != 0){ temp += i; } if( i < stopPoint -1) { temp+= " "; } } return temp; } }
public class FizzBuzzTester{ public static void main(String[] args){ FizzBuzzer firstFizz = new FizzBuzzer(20); System.out.println(firstFizz); } } class FizzBuzzer{ public int fizz; public int buzz; public int stopPoint; public FizzBuzzer(){ fizz = 3; buzz = 5; stopPoint = 30; }; public FizzBuzzer(int stop){ this(); stopPoint = stop; } public String toString(){ String temp = ""; for (int i = 1; i < stopPoint; i++){ if (i % 3 == 0) { temp += "fizz"; } if (i % 5 == 0) { temp += "buzz"; } if (i % 3 != 0 && i % 5 != 0){ temp += i; } if( i < stopPoint -1) { temp+= " "; } } return temp; } }
Allow distinguish document generation dates (days)
<?php /** @var integer $id */ /** @var array $statistic */ ?> <div class="table-responsive"> <table id="<?= $id ?>" class="table no-margin"> <thead> <tr> <th><?= Yii::t('hipanel:document', 'Date') ?></th> <th><?= Yii::t('hipanel:document', 'Count') ?></th> </tr> </thead> <tbody> <?php foreach ($statistic as $date => $count) : ?> <tr> <td><?= Yii::$app->formatter->asDate($date, 'php:Y-m-d') ?></td> <td><?= $count ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div>
<?php /** @var integer $id */ /** @var array $statistic */ ?> <div class="table-responsive"> <table id="<?= $id ?>" class="table no-margin"> <thead> <tr> <th><?= Yii::t('hipanel:document', 'Date') ?></th> <th><?= Yii::t('hipanel:document', 'Count') ?></th> </tr> </thead> <tbody> <?php foreach ($statistic as $date => $count) : ?> <tr> <td><?= Yii::$app->formatter->asDate($date, 'php:M Y') ?></td> <td><?= $count ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div>
Increase waiting time to pass testing on console
package com.leafriend.kspay.receiver; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.Test; public class DaemonTest { @Test public void testCallingShutdonwCallback() throws InterruptedException { // Given class Callback implements Runnable { boolean isCalled = false; @Override public void run() { isCalled = true; } @Override public String toString() { return "TestCallback"; } } Daemon daemon = new Daemon(29992); Callback callback = new Callback(); daemon.addShutdownCallback(callback); new Thread(daemon).start(); // When Thread.sleep(200); daemon.stop(); Thread.sleep(200); // Then assertThat("Callback is called", callback.isCalled, is(true)); } }
package com.leafriend.kspay.receiver; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.Test; public class DaemonTest { @Test public void testCallingShutdonwCallback() throws InterruptedException { // Given class Callback implements Runnable { boolean isCalled = false; @Override public void run() { isCalled = true; } @Override public String toString() { return "TestCallback"; } } Daemon daemon = new Daemon(29992); Callback callback = new Callback(); daemon.addShutdownCallback(callback); new Thread(daemon).start(); // When Thread.sleep(100); daemon.stop(); Thread.sleep(100); // Then assertThat("Callback is called", callback.isCalled, is(true)); } }
Change from request.ENABLED to settings.ENABLED
import re from django_seo_js import settings from django_seo_js.backends import SelectedBackend from django_seo_js.helpers import request_should_be_ignored import logging logger = logging.getLogger(__name__) class UserAgentMiddleware(SelectedBackend): def __init__(self, *args, **kwargs): super(UserAgentMiddleware, self).__init__(*args, **kwargs) regex_str = "|".join(settings.USER_AGENTS) regex_str = ".*?(%s)" % regex_str self.USER_AGENT_REGEX = re.compile(regex_str, re.IGNORECASE) def process_request(self, request): if not settings.ENABLED: return if request_should_be_ignored(request): return if "HTTP_USER_AGENT" not in request.META: return if not self.USER_AGENT_REGEX.match(request.META["HTTP_USER_AGENT"]): return url = request.build_absolute_uri() try: return self.backend.get_response_for_url(url) except Exception as e: logger.exception(e)
import re from django_seo_js import settings from django_seo_js.backends import SelectedBackend from django_seo_js.helpers import request_should_be_ignored import logging logger = logging.getLogger(__name__) class UserAgentMiddleware(SelectedBackend): def __init__(self, *args, **kwargs): super(UserAgentMiddleware, self).__init__(*args, **kwargs) regex_str = "|".join(settings.USER_AGENTS) regex_str = ".*?(%s)" % regex_str self.USER_AGENT_REGEX = re.compile(regex_str, re.IGNORECASE) def process_request(self, request): if not hasattr(request, 'ENABLED') or not request.ENABLED: return if request_should_be_ignored(request): return if "HTTP_USER_AGENT" not in request.META: return if not self.USER_AGENT_REGEX.match(request.META["HTTP_USER_AGENT"]): return url = request.build_absolute_uri() try: return self.backend.get_response_for_url(url) except Exception as e: logger.exception(e)
Use getElasticsearchData method / reactive variable
import { ReactiveVar } from 'meteor/reactive-var' import { Template } from 'meteor/templating'; Template.dashboard.onCreated(function () { // Get reference to template instance const templateInstance = this; // Create reactive variable for Elasticsearch host templateInstance.elasticsearchHost = new ReactiveVar(); // Create reactive variable for Elasticsearch data templateInstance.elasticsearchData = new ReactiveVar(); // Handle changes to Elasticsearch host templateInstance.autorun(function () { // Get value of Elasticsearch host const host = templateInstance.elasticsearchHost.get(); if (host) { Meteor.call('getElasticsearchData', host, function (error, result) { if (error) { throw Meteor.Error('error', error) } else { // Update Elasticsearch data reactive variable templateInstance.elasticsearchData.set(result); } }); } }); }); Template.dashboard.events({ 'submit #elasticsearch-host' (event, templateInstance) { // prevent default form action event.preventDefault(); // Get Elasticsearch host from form const host = event.target.host.value; // Update Elasticsearch host reactive variable templateInstance.elasticsearchHost.set(host); } });
import { ReactiveVar } from 'meteor/reactive-var' import { Template } from 'meteor/templating'; Template.dashboard.onCreated(function () { // Get reference to template instance const templateInstance = this; // Create reactive variable for Elasticsearch host templateInstance.elasticsearchHost = new ReactiveVar(); // Handle changes to Elasticsearch host templateInstance.autorun(function () { // Get value of Elasticsearch host const host = templateInstance.elasticsearchHost.get(); if (host) { Meteor.call('getElasticsearchData', host); } }); }); Template.dashboard.events({ 'submit #elasticsearch-host' (event, templateInstance) { // prevent default form action event.preventDefault(); // Get Elasticsearch host from form const host = event.target.host.value; // Update Elasticsearch host reactive variable templateInstance.elasticsearchHost.set(host); } });
Build to server public directory
var webpack = require('webpack'); var Config = require('webpack-config').Config; module.exports = new Config().merge({ entry: "./entry.js", output: { path: __dirname + "/../../server/public", filename: "bundle.js" }, module: { loaders: [ { test: /\.css$/, loader: 'style!css?sourceMap' }, { test: /\.(png)$/, loader: 'url-loader?limit=100000' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000" }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" } ] }, plugins: [ new webpack.DefinePlugin({ VERSION : JSON.stringify(require("../package.json").version) }) ] });
var webpack = require('webpack'); var Config = require('webpack-config').Config; module.exports = new Config().merge({ entry: "./entry.js", output: { path: __dirname, filename: "bundle.js" }, module: { loaders: [ { test: /\.css$/, loader: 'style!css?sourceMap' }, { test: /\.(png)$/, loader: 'url-loader?limit=100000' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000" }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" } ] }, plugins: [ new webpack.DefinePlugin({ VERSION : JSON.stringify(require("../package.json").version) }) ] });
Fix bugs with code for multiple gateways
import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" routes = [] with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))) print(routes) return routes def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() for g in default_gw: print(get_mac(g))
import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" routes = [] with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))) print(routes) return routes def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() for g in default_gw: print(get_mac(default_gw))
Remove unused 'skip_run' option flag
# -*- coding: utf-8 -*- """ pytest_pipeline.plugin ~~~~~~~~~~~~~~~~~~~~~~ pytest plugin entry point. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ ## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfailed = item def pytest_addoption(parser): group = parser.getgroup("general") group.addoption("--base-pipeline-dir", dest="base_pipeline_dir", default=None, metavar="dir", help="Base directory to put all pipeline test directories") group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true", default=False, help="Whether to fail a class immediately if any of its tests fail")
# -*- coding: utf-8 -*- """ pytest_pipeline.plugin ~~~~~~~~~~~~~~~~~~~~~~ pytest plugin entry point. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ ## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfailed = item def pytest_addoption(parser): group = parser.getgroup("general") group.addoption("--base-pipeline-dir", dest="base_pipeline_dir", default=None, metavar="dir", help="Base directory to put all pipeline test directories") group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true", default=False, help="Whether to fail a class immediately if any of its tests fail") group.addoption("--skip-run", dest="skip_run", action="store_true", default=False, help="Whether to skip the pipeline run and all tests after it")
Change the way of parsing method comments to make the app starting displaying proper comments
<?php /** * Created by PhpStorm. * User: alex * Date: 20/10/2016 * Time: 23:36 */ namespace vr\api\doc\components; use yii\base\BaseObject; /** * Class DocCommentParser * @package vr\api\doc\components * @property string $description */ class DocCommentParser extends BaseObject { /** * @var */ public $source; /** * @var */ public $params; /** * */ public function init() { } /** * @return string */ public function getDescription() { $string = explode(PHP_EOL, $this->source); $values = array_splice($string, 1); array_walk($values, function (&$item) { $item = trim($item, '* /\t\r\n'); }); return implode(array_filter($values), '<br/>'); } }
<?php /** * Created by PhpStorm. * User: alex * Date: 20/10/2016 * Time: 23:36 */ namespace vr\api\doc\components; use yii\base\BaseObject; use yii\helpers\ArrayHelper; /** * Class DocCommentParser * @package vr\api\doc\components * @property string $description */ class DocCommentParser extends BaseObject { /** * @var */ public $source; /** * @var */ public $params; /** * */ public function init() { } /** * @return string */ public function getDescription() { return trim(ArrayHelper::getValue(explode(PHP_EOL, $this->source), 1), " *"); } }
Fix not being able to type "w"
define(['constants', 'storage','tabs'], function(C, storage, tabs){ 'use strict'; function init() { $(window).keydown(function(e){ switch(e.which){ case C.KEYCODES.T: if (e.ctrlKey) { tabs.open_new_tab(); } break; case C.KEYCODES.Q: if (e.ctrlKey) { storage.clear(); } break; case C.KEYCODES.W: if (e.ctrlKey) { console.log("close window key"); e.preventDefault(); } break; case C.KEYCODES.L: if(e.ctrlKey) { tabs.focus_address_bar(); } break; default: console.log(e); } }); } return { init: init }; });
define(['constants', 'storage','tabs'], function(C, storage, tabs){ 'use strict'; function init() { $(window).keydown(function(e){ switch(e.which){ case C.KEYCODES.T: if(e.ctrlKey) tabs.open_new_tab(); break; case C.KEYCODES.Q: if(e.ctrlKey) storage.clear(); break; case C.KEYCODES.W: if(e.ctrlKey) console.log("close window key"); e.preventDefault(); break; case C.KEYCODES.L: if(e.ctrlKey) tabs.focus_address_bar(); break; default: console.log(e); } }); } return { init: init }; });
Update handling of datasources.txt URL
var config = require('./config.js'); var jsonLdContext = require('./context.json'); var MetadataService = require('./metadata-service.js'); var Organism = require('./organism.js'); var Xref = require('./xref.js'); var BridgeDb = { getEntityReferenceIdentifiersIri: function(metadataForDbName, dbId, callback) { var iri = metadataForDbName.linkoutPattern.replace('$id', dbId); return iri; }, init: function(options) { console.log('BridgeDb instance'); console.log(options); this.config = Object.create(config); // TODO loop through properties on options.config, if any, and update the instance config values. this.config.apiUrlStub = (!!options && options.apiUrlStub) || config.apiUrlStub; this.config.datasourcesUrl = (!!options && options.datasourcesUrl) || config.datasourcesUrl; this.organism = Object.create(Organism(this)); this.xref = Object.create(Xref(this)); }, config: config, organism: Organism(this), xref: Xref(this) }; var BridgeDbInstanceCreator = function(options) { var bridgedbInstance = Object.create(BridgeDb); bridgedbInstance.init(options); return bridgedbInstance; }; module.exports = BridgeDbInstanceCreator;
var config = require('./config.js'); var jsonLdContext = require('./context.json'); var MetadataService = require('./metadata-service.js'); var Organism = require('./organism.js'); var Xref = require('./xref.js'); var BridgeDb = { getEntityReferenceIdentifiersIri: function(metadataForDbName, dbId, callback) { var iri = metadataForDbName.linkoutPattern.replace('$id', dbId); return iri; }, init: function(options) { console.log('BridgeDb instance'); console.log(options); this.config = Object.create(config); this.config.apiUrlStub = (!!options && options.apiUrlStub) || config.apiUrlStub; this.organism = Object.create(Organism(this)); this.xref = Object.create(Xref(this)); }, config: config, organism: Organism(this), xref: Xref(this) }; var BridgeDbInstanceCreator = function(options) { var bridgedbInstance = Object.create(BridgeDb); bridgedbInstance.init(options); return bridgedbInstance; }; module.exports = BridgeDbInstanceCreator;
Allow Context subclasses in acceptance tests to access parent actor Although uncommon, in some cases a Context may need to be extended (for example, to override a step defined in the server with a specific behaviour in the acceptance tests of an app); in those cases the subclass should be able to access the actor attribute defined in the Context it is extending. Signed-off-by: Daniel Calviño Sánchez <bd7629e975cc0e00ea7cda4ab6a120f2ee42ac1b@gmail.com>
<?php /** * * @copyright Copyright (c) 2017, Daniel Calviño Sánchez (danxuliu@gmail.com) * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ trait ActorAware { /** * @var Actor */ protected $actor; /** * @param Actor $actor */ public function setCurrentActor(Actor $actor) { $this->actor = $actor; } }
<?php /** * * @copyright Copyright (c) 2017, Daniel Calviño Sánchez (danxuliu@gmail.com) * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ trait ActorAware { /** * @var Actor */ private $actor; /** * @param Actor $actor */ public function setCurrentActor(Actor $actor) { $this->actor = $actor; } }
:racehorse: Use some best practices Learnt from the node.js core peeps
'use babel' /* @flow */ module.exports = function promisify(callback: Function): Function { return function promisified(){ const parameters = Array.from(arguments) const parametersLength = parameters.length + 1 return new Promise((resolve, reject) => { parameters.push(function(error, data) { if (error) { reject(error) } else resolve(data) }) if (parametersLength === 1) { callback.call(this, parameters[0]) } else if (parametersLength === 2) { callback.call(this, parameters[0], parameters[1]) } else if (parametersLength === 3) { callback.call(this, parameters[0], parameters[1], parameters[2]) } else if (parametersLength === 4) { callback.call(this, parameters[0], parameters[1], parameters[2], parameters[3]) } else { callback.apply(this, parameters) } }) } }
'use babel' /* @flow */ module.exports = function promisify(callback: Function): Function { return function promisified(){ const parameters = arguments const parametersLength = arguments.length + 1 return new Promise((resolve, reject) => { Array.prototype.push.call(parameters, function(error, data) { if (error) { reject(error) } else resolve(data) }) if (parametersLength === 1) { callback.call(this, parameters[0]) } else if (parametersLength === 2) { callback.call(this, parameters[0], parameters[1]) } else if (parametersLength === 3) { callback.call(this, parameters[0], parameters[1], parameters[2]) } else if (parametersLength === 4) { callback.call(this, parameters[0], parameters[1], parameters[2], parameters[3]) } else { callback.apply(this, parameters) } }) } }
Extend AbstractType and use getParent
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <integrated@e-active.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Bundle\ContentBundle\Form\Type\Job; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; use Braincrafted\Bundle\BootstrapBundle\Form\Type\BootstrapCollectionType; /** * @author Johan Liefers <johan@e-active.nl> */ class ContactPersonsType extends AbstractType { /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'type' => CompanyJobType::class, 'allow_add' => true, 'allow_delete' => true, 'label' => 'Contact persons', 'delete_button_text' => 'x' ]); } public function getParent() { return BootstrapCollectionType::class; } /** * @return string */ public function getBlockPrefix() { return 'integrated_contact_persons'; } }
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <integrated@e-active.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Bundle\ContentBundle\Form\Type\Job; use Symfony\Component\OptionsResolver\OptionsResolver; use Braincrafted\Bundle\BootstrapBundle\Form\Type\BootstrapCollectionType; /** * @author Johan Liefers <johan@e-active.nl> */ class ContactPersonsType extends BootstrapCollectionType { /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults([ 'type' => CompanyJobType::class, 'allow_add' => true, 'allow_delete' => true, 'label' => 'Contact persons', 'delete_button_text' => 'x' ]); } /** * @return string */ public function getBlockPrefix() { return 'integrated_contact_persons'; } }
Make fast config have less space between games
anyware_config = { DEBUG: { status: true, // Persistent status icons debugView: true, // Show game debug view console: false, // Javascript console debug output }, // The sequence of the games to be run. The first game is run on startup GAMES_SEQUENCE: [ "mole", "disk", "simon", ], SPACE_BETWEEN_GAMES_SECONDS: 2, MOLE_GAME: { GAME_END: 3, }, DISK_GAME: { LEVELS: [ { rule: 'absolute', disks: { disk0: -10, disk1: 10, disk2: 10 } }, ], }, SIMON_GAME: { PATTERN_LEVELS: [ // level 0 sequence { stripId: '2', // Each array of panel IDs is lit up one at a time // Each array within this array is called a "frame" in the "sequence" panelSequences: [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ], frameDelay: 750 // Overriding default frame delay to make first level slower }, ], } };
anyware_config = { DEBUG: { status: true, // Persistent status icons debugView: true, // Show game debug view console: false, // Javascript console debug output }, // The sequence of the games to be run. The first game is run on startup GAMES_SEQUENCE: [ "mole", "disk", "simon", ], MOLE_GAME: { GAME_END: 3, }, DISK_GAME: { LEVELS: [ { rule: 'absolute', disks: { disk0: -10, disk1: 10, disk2: 10 } }, ], }, SIMON_GAME: { PATTERN_LEVELS: [ // level 0 sequence { stripId: '2', // Each array of panel IDs is lit up one at a time // Each array within this array is called a "frame" in the "sequence" panelSequences: [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ], frameDelay: 750 // Overriding default frame delay to make first level slower }, ], } };
Fix the tool tests when run with buck Summary: Not sure why source-map-support is starting to return `null` as the filename for some stack frames. Also not sure why this only happens when run with buck. This does fix all the tests, though. Reviewed By: samwgoldman Differential Revision: D5427555 fbshipit-source-id: 2d30606452a11e2c2d744cf07c04af2f35deae38
/* @flow */ import {sync as resolve} from 'resolve'; import {dirname} from 'path'; import type {AssertionLocation} from './assertions/assertionTypes'; /* We need to use source-map-support in order to extract the right locations * from a stack trace. Unfortunately, we need to use the exact same version * that babel-register uses. We can use resolve() to find it. */ let wrapCallSite = null; function getWrapCallSite() { if (wrapCallSite == null) { const babelRegisterPath = resolve('babel-register'); const sourceMapSupportPath = resolve( 'source-map-support', {basedir: dirname(babelRegisterPath)}, ); // $FlowFixMe - This is necessary :( wrapCallSite = require(sourceMapSupportPath).wrapCallSite; } return wrapCallSite; } export default function(): ?AssertionLocation { const oldPrepareStackTrace = Error.prepareStackTrace; const wrapCallSite = getWrapCallSite(); Error.prepareStackTrace = (_, stack) => stack.map(wrapCallSite); const stack: Array<Object> = ((new Error()).stack: any); Error.prepareStackTrace = oldPrepareStackTrace; for (const callSite of stack) { const filename = callSite.getFileName(); if (filename != null && filename.match(/test.js$/)) { return { filename, line: callSite.getLineNumber(), column: callSite.getColumnNumber(), }; } } return null; }
/* @flow */ import {sync as resolve} from 'resolve'; import {dirname} from 'path'; import type {AssertionLocation} from './assertions/assertionTypes'; /* We need to use source-map-support in order to extract the right locations * from a stack trace. Unfortunately, we need to use the exact same version * that babel-register uses. We can use resolve() to find it. */ let wrapCallSite = null; function getWrapCallSite() { if (wrapCallSite == null) { const babelRegisterPath = resolve('babel-register'); const sourceMapSupportPath = resolve( 'source-map-support', {basedir: dirname(babelRegisterPath)}, ); // $FlowFixMe - This is necessary :( wrapCallSite = require(sourceMapSupportPath).wrapCallSite; } return wrapCallSite; } export default function(): ?AssertionLocation { const oldPrepareStackTrace = Error.prepareStackTrace; const wrapCallSite = getWrapCallSite(); Error.prepareStackTrace = (_, stack) => stack.map(wrapCallSite); const stack: Array<Object> = ((new Error()).stack: any); Error.prepareStackTrace = oldPrepareStackTrace; for (const callSite of stack) { const filename = callSite.getFileName(); if (filename.match(/test.js$/)) { return { filename, line: callSite.getLineNumber(), column: callSite.getColumnNumber(), }; } } return null; }
Fix indentation in test suite
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.ete; import java.util.List; import org.junit.ClassRule; import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.google.common.collect.ImmutableList; @RunWith(Suite.class) @Suite.SuiteClasses({ TodoEteTest.class, TimestampManagementEteTest.class }) public class DbKvsTestSuite extends EteSetup { private static final List<String> CLIENTS = ImmutableList.of("ete1", "ete2", "ete3"); @ClassRule public static final RuleChain COMPOSITION_SETUP = EteSetup.setupComposition( DbKvsTestSuite.class, "docker-compose.dbkvs.yml", CLIENTS); }
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.ete; import java.util.List; import org.junit.ClassRule; import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.google.common.collect.ImmutableList; @RunWith(Suite.class) @Suite.SuiteClasses({ TodoEteTest.class, TimestampManagementEteTest.class }) public class DbKvsTestSuite extends EteSetup { private static final List<String> CLIENTS = ImmutableList.of("ete1", "ete2", "ete3"); @ClassRule public static final RuleChain COMPOSITION_SETUP = EteSetup.setupComposition( DbKvsTestSuite.class, "docker-compose.dbkvs.yml", CLIENTS); }
Revert "Prevent to update latest version of requirements." This reverts commit 0f341482c7dc9431ed89444c8be2688ea57f61ba.
from setuptools import setup setup( name='restea', packages=['restea', 'restea.adapters'], version='0.3.2', description='Simple RESTful server toolkit', author='Walery Jadlowski', author_email='bodb.digr@gmail.com', url='https://github.com/bodbdigr/restea', download_url='https://github.com/bodbdigr/restea/archive/0.3.2.tar.gz', keywords=['rest', 'restful', 'restea'], install_requires=[ 'future==0.16.0', ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest==3.0.6', 'pytest-cov==2.4.0', 'pytest-mock==1.5.0', 'coveralls==1.1', ], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP', ] )
from setuptools import setup setup( name='restea', packages=['restea', 'restea.adapters'], version='0.3.2', description='Simple RESTful server toolkit', author='Walery Jadlowski', author_email='bodb.digr@gmail.com', url='https://github.com/bodbdigr/restea', download_url='https://github.com/bodbdigr/restea/archive/0.3.2.tar.gz', keywords=['rest', 'restful', 'restea'], install_requires=[ 'future==0.15.2', ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest==2.9.1', 'pytest-cov==1.8.1', 'pytest-mock==0.4.3', 'coveralls==0.5', ], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP', ] )
Enable plugin for inline js in html files
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ilya Akhmadullin # Copyright (c) 2013 Ilya Akhmadullin # # License: MIT # """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' regex = ( r'^\s+?\<error line=\"(?P<line>\d+)\" ' r'column=\"(?P<col>\d+)\" ' # jscs always reports with error severity; show as warning r'severity=\"(?P<warning>error)\" ' r'message=\"(?P<message>.+)\" source=\"jscs\" />' ) multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ilya Akhmadullin # Copyright (c) 2013 Ilya Akhmadullin # # License: MIT # """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript') executable = 'jscs' cmd = 'jscs -r checkstyle' regex = ( r'^\s+?\<error line=\"(?P<line>\d+)\" ' r'column=\"(?P<col>\d+)\" ' # jscs always reports with error severity; show as warning r'severity=\"(?P<warning>error)\" ' r'message=\"(?P<message>.+)\" source=\"jscs\" />' ) multiline = True # currently jscs does not accept stdin so this does not work # selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js'
Fix scope for correlation object
var uniqueID = require('../unique-id'); promise = require('../promise'), commandTimeout = 1000; module.exports = function(serviceType, serviceInstance, command, params){ var correlationId = uniqueID(), params = JSON.stringify(params), msg = [ "MDPC02", 0x01, correlationId, serviceType, serviceInstance, command, params ], dfd = promise.defer() correlation = {promise: dfd}, self = this; //set timeout to reject promise if there is no response correlation.rejectTimeout = setTimeout(function() { if(dfd.promise.isPending()) { dfd.reject("TIMEOUT"); } if(self.correlations[correlationId]) { delete self.correlations[correlationId]; } }, commandTimeout); this.correlations[correlationId] = correlation; this.socket.send(msg); return dfd.promise; };
var uniqueID = require('../unique-id'); promise = require('../promise'), commandTimeout = 1000; module.exports = function(serviceType, serviceInstance, command, params){ var correlationId = uniqueID(), params = JSON.stringify(params), msg = [ "MDPC02", 0x01, correlationId, serviceType, serviceInstance, command, params ], dfd = promise.defer() correlation = {promise: dfd}; //set timeout to reject promise if there is no response correlation.rejectTimeout = setTimeout(function() { if(dfd.promise.isPending()) { dfd.reject("TIMEOUT"); } if(this.correlations[correlationId]) { delete this.correlations[correlationId]; } }, commandTimeout); this.correlations[correlationId] = correlation; this.socket.send(msg); return dfd.promise; };
Remove reference to openshfit specifics.
//Dependencies var restify = require('restify'); var cors = require('cors'); var appInfo = require('./package.json'); //Configuration var port = process.env.PORT || 1337; var server = restify.createServer(); //Plug-ins server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.CORS()); //Routes server.get(/\//, echo); server.get(/\/(echo)\b/, echo); server.post(/\/(parse)\b/, parse); /****************************************************************************** End-points ******************************************************************************/ function echo(req, res) { var info = { name: appInfo.name, version: appInfo.version, description: appInfo.description, homepage: appInfo.homepage, author:{ name: appInfo.author.name, email: appInfo.author.email, } }; res.send(info); } function parse(req, res) { //Parse the data var agentString = req.body.userAgent || req.body.UserAgent || req.params['useragent']; var useragent = require('useragent'); useragent(true); var agent = useragent.lookup(agentString); res.send(agent.toJSON()); } /*****************************************************************************/ //Start server server.listen(port, function () { console.log('listening on port: ' + port); });
//Dependencies var restify = require('restify'); var cors = require('cors'); var appInfo = require('./package.json'); //Configuration //var address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'; var port = process.env.PORT || 1337; var server = restify.createServer(); //Plug-ins server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.CORS()); //Routes server.get(/\//, echo); server.get(/\/(echo)\b/, echo); server.post(/\/(parse)\b/, parse); /****************************************************************************** End-points ******************************************************************************/ function echo(req, res) { var info = { name: appInfo.name, version: appInfo.version, description: appInfo.description, homepage: appInfo.homepage, author:{ name: appInfo.author.name, email: appInfo.author.email, } }; res.send(info); } function parse(req, res) { //Parse the data var agentString = req.body.userAgent || req.body.UserAgent || req.params['useragent']; var useragent = require('useragent'); useragent(true); var agent = useragent.lookup(agentString); res.send(agent.toJSON()); } /*****************************************************************************/ //Start server server.listen(port, function () { console.log('listening on port: ' + port); });
Revert "Add author to doctrine migrations" This reverts commit bd227b32da43419226f3003dc2c4d98966adb25c.
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20150920220909 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('DROP TABLE post'); } }
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20150920220909 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, author VARCHAR(255) NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('DROP TABLE post'); } }
Fix name of function after renaming
var landmarkRoles = kslib.aria.getRolesByType('landmark'), firstLink = node.querySelector('a[href]'); function isSkipLink(n) { return firstLink && kslib.dom.isFocusable(kslib.dom.getElementByReference(firstLink, 'href')) && firstLink === n; } function isLandmark(n) { var role = n.getAttribute('role'); return role && (landmarkRoles.indexOf(role) !== -1); } function checkRegion(n) { if (isLandmark(n)) { return null; } if (isSkipLink(n)) { return getViolatingChildren(n); } if (kslib.dom.isVisible(n, true) && (kslib.text.visible(n, true, true) || kslib.dom.isVisualContent(n))) { return n; } return getViolatingChildren(n); } function getViolatingChildren(n) { var children = kslib.utils.toArray(n.children); if (children.length === 0) { return []; } return children.map(checkRegion) .filter(function (c) { return c !== null; }) .reduce(function (a, b) { return a.concat(b); }, []); } var v = getViolatingChildren(node); this.relatedNodes(v); return !v.length;
var landmarkRoles = kslib.aria.getRolesByType('landmark'), firstLink = node.querySelector('a[href]'); function isSkipLink(n) { return firstLink && kslib.dom.isFocusable(kslib.dom.getElementByReference(firstLink, 'href')) && firstLink === n; } function isLandmark(n) { var role = n.getAttribute('role'); return role && (landmarkRoles.indexOf(role) !== -1); } function checkRegion(n) { if (isLandmark(n)) { return null; } if (isSkipLink(n)) { return getViolatingChildren(n); } if (kslib.dom.isVisible(n, true) && (kslib.text.visible(n, true, true) || kslib.dom.hasVisualContent(n))) { return n; } return getViolatingChildren(n); } function getViolatingChildren(n) { var children = kslib.utils.toArray(n.children); if (children.length === 0) { return []; } return children.map(checkRegion) .filter(function (c) { return c !== null; }) .reduce(function (a, b) { return a.concat(b); }, []); } var v = getViolatingChildren(node); this.relatedNodes(v); return !v.length;
Update the PyPI version to 7.0.3.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.3', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.2', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Delete entries from the South migration history too
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from south.models import MigrationHistory from django.db import models from django.db.utils import DatabaseError from django.contrib.contenttypes.models import ContentType class Migration(SchemaMigration): def forwards(self, orm): # Do the deletes in a separate transaction, as database errors when # deleting a table that does not exist would cause a transaction to be # rolled back db.start_transaction() ContentType.objects.filter(app_label='user_profile').delete() # Remove the entries from South's tables as we don't want to leave # incorrect entries in there. MigrationHistory.objects.filter(app_name='user_profile').delete() # Commit the deletes to the various tables. db.commit_transaction() try: db.delete_table('user_profile_userprofile') except DatabaseError: # table does not exist to delete, probably because the database was # not created at a time when the user_profile app was still in use. pass def backwards(self, orm): # There is no backwards - to create the user_profile tables again add the app # back in and letting its migrations do the work. pass models = {} complete_apps = ['user_profile']
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.db.utils import DatabaseError from django.contrib.contenttypes.models import ContentType class Migration(SchemaMigration): def forwards(self, orm): # Do the deletes in a separate transaction, as database errors when # deleting a table that does not exist would cause a transaction to be # rolled back db.start_transaction() ContentType.objects.filter(app_label='user_profile').delete() # Commit the deletes to the various tables. db.commit_transaction() try: db.delete_table('user_profile_userprofile') except DatabaseError: # table does not exist to delete, probably because the database was # not created at a time when the user_profile app was still in use. pass def backwards(self, orm): # There is no backwards - to create the user_profile tables again add the app # back in and letting its migrations do the work. pass models = {} complete_apps = ['user_profile']
Clarify variable name in pagination tests We should avoid using abbreviations, as they aren't universally understood i.e. they're not worth the small saving in typing.
from app.utils.pagination import generate_next_dict, generate_previous_dict def test_generate_previous_dict(client): result = generate_previous_dict('main.view_jobs', 'foo', 2, {}) assert 'page=1' in result['url'] assert result['title'] == 'Previous page' assert result['label'] == 'page 1' def test_generate_next_dict(client): result = generate_next_dict('main.view_jobs', 'foo', 2, {}) assert 'page=3' in result['url'] assert result['title'] == 'Next page' assert result['label'] == 'page 3' def test_generate_previous_next_dict_adds_other_url_args(client): result = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'}) assert 'notifications/blah' in result['url']
from app.utils.pagination import generate_next_dict, generate_previous_dict def test_generate_previous_dict(client): ret = generate_previous_dict('main.view_jobs', 'foo', 2, {}) assert 'page=1' in ret['url'] assert ret['title'] == 'Previous page' assert ret['label'] == 'page 1' def test_generate_next_dict(client): ret = generate_next_dict('main.view_jobs', 'foo', 2, {}) assert 'page=3' in ret['url'] assert ret['title'] == 'Next page' assert ret['label'] == 'page 3' def test_generate_previous_next_dict_adds_other_url_args(client): ret = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'}) assert 'notifications/blah' in ret['url']
Fix product re-crawl to use correct method from interface
<?php /** * Handles product re-crawl requests to Nosto via the API. */ class NostoProductReCrawl { /** * Sends a product re-crawl request to nosto. * * @param NostoProductInterface $product the product to re-crawl. * @param NostoAccountInterface $account the account to re-crawl the product for. * @return bool true on success, false otherwise. * @throws NostoException if the request fails. */ public static function send(NostoProductInterface $product, NostoAccountInterface $account) { $token = $account->getApiToken('products'); if ($token === null) { return false; } $request = new NostoApiRequest(); $request->setPath(NostoApiRequest::PATH_PRODUCT_RE_CRAWL); $request->setContentType('application/json'); $request->setAuthBasic('', $token); $response = $request->post(json_encode(array('product_ids' => array($product->getProductId())))); if ($response->getCode() !== 200) { throw new NostoException('Failed to send product re-crawl to Nosto'); } return true; } }
<?php /** * Handles product re-crawl requests to Nosto via the API. */ class NostoProductReCrawl { /** * Sends a product re-crawl request to nosto. * * @param NostoProductInterface $product the product to re-crawl. * @param NostoAccountInterface $account the account to re-crawl the product for. * @return bool true on success, false otherwise. * @throws NostoException if the request fails. */ public static function send(NostoProductInterface $product, NostoAccountInterface $account) { $token = $account->getApiToken('products'); if ($token === null) { return false; } $request = new NostoApiRequest(); $request->setPath(NostoApiRequest::PATH_PRODUCT_RE_CRAWL); $request->setContentType('application/json'); $request->setAuthBasic('', $token); $response = $request->post(json_encode(array('product_ids' => array($product->getId())))); if ($response->getCode() !== 200) { throw new NostoException('Failed to send product re-crawl to Nosto'); } return true; } }
Remove special chars from file and save
<?php namespace OfxParser; /** * @author Diogo Alexsander Cavilha <diogo@agenciasys.com.br> */ class Fix { private $file; public function __construct($file) { $this->file = $file; } public function replaceStartDate($search, $replace = '20000101100000') { $fileContent = $this->getFileContent($this->file); $fileContent = str_replace( '<DTSTART>' . $search, '<DTSTART>' . $replace, $fileContent ); $this->saveFileContent($this->file, $fileContent); return $this; } protected function getFileContent($file) { return file_get_contents($file); } protected function saveFileContent($file, $content) { file_put_contents($file, $content); } public function removeSpecialChars() { $fileContent = $this->getFileContent($this->file); $fileContent = str_replace('&', 'e', $fileContent); $this->saveFileContent($this->file, $fileContent); return $this; } }
<?php namespace OfxParser; /** * @author Diogo Alexsander Cavilha <diogo@agenciasys.com.br> */ class Fix { private $file; public function __construct($file) { $this->file = $file; } public function replaceStartDate($search, $replace = '20000101100000') { $fileContent = $this->getFileContent($this->file); $fileContent = str_replace( '<DTSTART>' . $search, '<DTSTART>' . $replace, $fileContent ); $this->saveFileContent($this->file, $fileContent); return $this; } protected function getFileContent($file) { return file_get_contents($file); } protected function saveFileContent($file, $content) { file_put_contents($file, $content); } }
Remove unused zk data for default flavor override
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.maintenance; import com.yahoo.path.Path; import com.yahoo.vespa.config.server.ApplicationRepository; import com.yahoo.vespa.curator.Curator; import java.time.Duration; /** * Removes unused zookeeper data (for now only data used by old file distribution code is removed) */ public class ZooKeeperDataMaintainer extends Maintainer { ZooKeeperDataMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) { super(applicationRepository, curator, interval); } @Override protected void maintain() { curator.delete(Path.fromString("/vespa/filedistribution")); curator.delete(Path.fromString("/vespa/config")); curator.delete(Path.fromString("/provision/v1/defaultFlavor")); } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.maintenance; import com.yahoo.path.Path; import com.yahoo.vespa.config.server.ApplicationRepository; import com.yahoo.vespa.curator.Curator; import java.time.Duration; /** * Removes unused zookeeper data (for now only data used by old file distribution code is removed) */ public class ZooKeeperDataMaintainer extends Maintainer { ZooKeeperDataMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) { super(applicationRepository, curator, interval); } @Override protected void maintain() { curator.delete(Path.fromString("/vespa/filedistribution")); curator.delete(Path.fromString("/vespa/config")); } }
Remove prod appUrl trailing slash.
/** * Production environment settings * * This file can include shared settings for a production environment, * such as API keys or remote database passwords. If you're using * a version control solution for your Sails app, this file will * be committed to your repository unless you add it to your .gitignore * file. If your repository will be publicly viewable, don't add * any private information to this file! * */ module.exports = { // Just a placeholder until the app is actualy deployed. // @todo: change to real hostname. appUrl: 'http://localhost', /*************************************************************************** * Set the default database connection for models in the production * * environment (see config/connections.js and config/models.js ) * ***************************************************************************/ // models: { // connection: 'someMysqlServer' // }, /*************************************************************************** * Set the port in the production environment to 80 * ***************************************************************************/ // port: 80, /*************************************************************************** * Set the log level in production environment to "silent" * ***************************************************************************/ // log: { // level: "silent" // } };
/** * Production environment settings * * This file can include shared settings for a production environment, * such as API keys or remote database passwords. If you're using * a version control solution for your Sails app, this file will * be committed to your repository unless you add it to your .gitignore * file. If your repository will be publicly viewable, don't add * any private information to this file! * */ module.exports = { // Just a placeholder until the app is actualy deployed. // @todo: change to real hostname. appUrl: 'http://localhost/', /*************************************************************************** * Set the default database connection for models in the production * * environment (see config/connections.js and config/models.js ) * ***************************************************************************/ // models: { // connection: 'someMysqlServer' // }, /*************************************************************************** * Set the port in the production environment to 80 * ***************************************************************************/ // port: 80, /*************************************************************************** * Set the log level in production environment to "silent" * ***************************************************************************/ // log: { // level: "silent" // } };
Remove useless function that already exist in strings pakage.
package xmpp import ( "fmt" "net" "strings" ) const ( // Standard port for XMPP clients to connect to. XMPP_CLIENT_PORT = 5222 ) // Perform a DNS SRV lookup and return an ordered list of "host:port" TCP // addresses for the JID's home server. If no SRV records are found then assume // the JID's domain is also the home server. func HomeServerAddrs(jid JID) (addr []string, err error) { // DNS lookup. _, addrs, _ := net.LookupSRV("xmpp-client", "tcp", jid.Domain) // If there's nothing in DNS then assume the JID's domain and the standard // port will work. if len(addrs) == 0 { addr = []string{fmt.Sprintf("%s:%d", jid.Domain, XMPP_CLIENT_PORT)} return } // Build list of "host:port" strings. for _, a := range addrs { target := strings.TrimRight(a.Target, ".") addr = append(addr, fmt.Sprintf("%s:%d", target, a.Port)) } return }
package xmpp import ( "fmt" "net" ) const ( // Standard port for XMPP clients to connect to. XMPP_CLIENT_PORT = 5222 ) // Perform a DNS SRV lookup and return an ordered list of "host:port" TCP // addresses for the JID's home server. If no SRV records are found then assume // the JID's domain is also the home server. func HomeServerAddrs(jid JID) (addr []string, err error) { // DNS lookup. _, addrs, _ := net.LookupSRV("xmpp-client", "tcp", jid.Domain) // If there's nothing in DNS then assume the JID's domain and the standard // port will work. if len(addrs) == 0 { addr = []string{fmt.Sprintf("%s:%d", jid.Domain, XMPP_CLIENT_PORT)} return } // Build list of "host:port" strings. for _, a := range addrs { target := parseTargetDomainName(a.Target) addr = append(addr, fmt.Sprintf("%s:%d", target, a.Port)) } return } // Remove the last dot in the domain name if exist func parseTargetDomainName(domainName string) (ret string) { if domainName[len(domainName)-1] == '.' { ret = parseTargetDomainName(domainName[:len(domainName)-1]) } else { ret = domainName } return }
Check if beta flag is activated
/** * Validate if the application is in beta * and the user has the access token to * view the beta version. * * If not authorized session, then display coming soon */ const env = require('../env') module.exports = (app) => { // This is only valid for Heroku. // Change this if you're using other // hosting provider. if (process.env.BETA_ACTIVATED === 'true' && process.env.NODE_ENV === 'production') { app.use(setupBetaFirewall) } } function setupBetaFirewall (req, res, next) { const betaSecretToken = process.env.BETA_TOKEN let key = null if (req.query && req.query.beta) { key = req.query.token } else if (req.cookies) { key = req.cookies['betaToken'] } if (!key) { return res.render('comingSoon') } if (key === betaSecretToken) { // Set the beta cookie res.cookie('betaToken', process.env.BETA_TOKEN, { maxAge: 7 * (24 * 3600000), httpOnly: true }) return next() } return res.render('comingSoon', { message: 'Invalid beta token or session has expired...' }) }
/** * Validate if the application is in beta * and the user has the access token to * view the beta version. * * If not authorized session, then display coming soon */ const env = require('../env') module.exports = (app) => { // This is only valid for Heroku. // Change this if you're using other // hosting provider. if (process.env.BETA_ACTIVATED && process.env.NODE_ENV === 'production') { app.use(setupBetaFirewall) } } function setupBetaFirewall (req, res, next) { const betaSecretToken = process.env.BETA_TOKEN let key = null if (req.query && req.query.beta) { key = req.query.token } else if (req.cookies) { key = req.cookies['betaToken'] } if (!key) { return res.render('comingSoon') } if (key === betaSecretToken) { // Set the beta cookie res.cookie('betaToken', process.env.BETA_TOKEN, { maxAge: 7 * (24 * 3600000), httpOnly: true }) return next() } return res.render('comingSoon', { message: 'Invalid beta token or session has expired...' }) }
Allow editing user levels by providing string id
package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { setLevel(BotUtil.getId(user), level); } public void setLevel(String user, UserLevel level) { if (!user.equals(ownerId)) levels.put(user, level); } public void removeLevel(User user) { removeLevel(BotUtil.getId(user)); } public void removeLevel(String user) { if (!user.equals(ownerId)) levels.remove(user); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } }
package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.put(id, level); } public void removeLevel(User user) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.remove(id); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } }
Set up weather station to receive updates
import datetime import zmq from . import monitor from panoptes.utils import logger, config, messaging, threads @logger.has_logger @config.has_config class WeatherStation(monitor.EnvironmentalMonitor): """ This object is used to determine the weather safe/unsafe condition. It inherits from the monitor.EnvironmentalMonitor base class. It listens on the 'weather' channel of the messaging system. Config: weather_station.port (int): Port to publish to. Defaults to 6500 weather_station.channel (str): the channel topic to publish on. Defaults to 'weather' Args: messaging (panoptes.messaging.Messaging): A messaging Object for creating new sockets. """ def __init__(self, messaging=None, connect_on_startup=False): super().__init__(messaging=messaging, name='WeatherStation') # Get the messaging information self.port = self.config.get('messaging').get('messaging_port', 6500) self.channel = self.config.get('messaging').get('channel', 'weather') # Create our Publishing socket self.socket = self.messaging.create_subscriber(port=self.port, channel=self.channel) if connect_on_startup: self.start_monitoring() def monitor(self): """ Reads serial information off the attached weather station """ msg = self.socket.recv_json()
import datetime import zmq from . import monitor from panoptes.utils import logger, config, messaging, threads @logger.has_logger @config.has_config class WeatherStation(monitor.EnvironmentalMonitor): """ This object is used to determine the weather safe/unsafe condition. It inherits from the monitor.EnvironmentalMonitor base class. It listens on the 'weather' channel of the messaging system. Config: weather_station.port (int): Port to publish to. Defaults to 6500 weather_station.channel (str): the channel topic to publish on. Defaults to 'weather' Args: messaging (panoptes.messaging.Messaging): A messaging Object for creating new sockets. """ def __init__(self, messaging=None, connect_on_startup=False): super().__init__(messaging=messaging, name='WeatherStation') # Get the messaging information self.port = self.config.get('messaging').get('messaging_port', 6500) self.channel = self.config.get('messaging').get('channel', 'weather') # Create our Publishing socket self.socket = self.messaging.create_subscriber(port=self.port, channel=self.channel) if connect_on_startup: self.start_monitoring() def monitor(self): """ Reads serial information off the attached weather station and publishes message with status """ self.send_message('UNSAFE')
Remove spurious test group for work-in-progress
<?php namespace OpenCFP\Test\Infrastructure\Persistence; use OpenCFP\Infrastructure\Persistence\IlluminateAirportInformationDatabase; /** * Tests integration with illuminate/database and airports table to implement * an AirportInfromationDatabase */ class IlluminateAirportInformationDatabaseTest extends \DatabaseTestCase { private $airports; protected function setUp() { parent::setUp(); $this->airports = $this->getAirportInformationDatabase(); } /** @test */ public function it_queries_airports_table_by_code() { $airport = $this->airports->withCode('RDU'); $this->assertEquals('RDU', $airport->code); $this->assertEquals('Raleigh/Durham (NC)', $airport->name); $this->assertEquals('USA', $airport->country); } /** @test */ public function it_squawks_when_airport_is_not_found() { $this->setExpectedException(\Exception::class, 'not found'); $this->airports->withCode('foobarbaz'); } /** * @return IlluminateAirportInformationDatabase */ private function getAirportInformationDatabase() { return new IlluminateAirportInformationDatabase($this->getCapsule()); } }
<?php namespace OpenCFP\Test\Infrastructure\Persistence; use OpenCFP\Infrastructure\Persistence\IlluminateAirportInformationDatabase; /** * Tests integration with illuminate/database and airports table to implement * an AirportInfromationDatabase * * @group wip */ class IlluminateAirportInformationDatabaseTest extends \DatabaseTestCase { private $airports; protected function setUp() { parent::setUp(); $this->airports = $this->getAirportInformationDatabase(); } /** @test */ public function it_queries_airports_table_by_code() { $airport = $this->airports->withCode('RDU'); $this->assertEquals('RDU', $airport->code); $this->assertEquals('Raleigh/Durham (NC)', $airport->name); $this->assertEquals('USA', $airport->country); } /** @test */ public function it_squawks_when_airport_is_not_found() { $this->setExpectedException(\Exception::class, 'not found'); $this->airports->withCode('foobarbaz'); } /** * @return IlluminateAirportInformationDatabase */ private function getAirportInformationDatabase() { return new IlluminateAirportInformationDatabase($this->getCapsule()); } }
Send user false if does not exist
module.exports = { setUp: function(self, passport){ return function(){ Array.prototype.push.call(arguments, passport); self.login.apply(this, arguments); }; }, login: function(req, res, next, passport){ passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { info.user = false; if(info){ return res.send(info); } } req.logIn(user, function(err) { if (err) { return next(err); } return res.send({user: user.email}); }); })(req, res, next); }, logout: function(req, res){ req.session.destroy(); res.send({user: false}); } };
module.exports = { setUp: function(self, passport){ return function(){ Array.prototype.push.call(arguments, passport); self.login.apply(this, arguments); }; }, login: function(req, res, next, passport){ passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { if(info){ return res.send(info); } } req.logIn(user, function(err) { if (err) { return next(err); } return res.send({user: user.email}); }); })(req, res, next); }, logout: function(req, res){ req.session.destroy(); res.send({user: false}); } };
Implement update_distance(), init setup for Bellman-Ford alg
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np def update_distance(v, v_neighbor, w_graph_d, previous_d): if (distance_d[v_neighbor] > distance_d[v] + w_graph_d[v][v_neighbor]): distance_d[v_neighbor] = ( distance_d[v] + w_graph_d[v][v_neighbor]) previous_d[v_neighbor] = v def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph.""" distance_d = {v: np.inf for v in w_graph_d.keys()} previous_d = {v: None for v in w_graph_d.keys()} n = len(w_graph_d.keys()) for i in xrange(1, n): pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3, 'c': 1}, 'b': {'a': -5, 'd': 2}, 'c': {'b': 1, 'e': 4, 'f': 2}, 'd': {'c': 3, 'f': 2}, 'e': {}, 'f': {'e': 1} } start_vertex = 's' if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def bellman_ford(w_graph_d, start_vertex): """Bellman-Ford algorithm for weighted / negative graph. """ pass def main(): w_graph_d = { 's': {'a': 2, 'b': 6}, 'a': {'b': 3, 'c': 1}, 'b': {'a': -5, 'd': 2}, 'c': {'b': 1, 'e': 4, 'f': 2}, 'd': {'c': 3, 'f': 2}, 'e': {}, 'f': {'e': 1} } start_vertex = 's' if __name__ == '__main__': main()
Add a IconButton story to demo the 'element' prop
import React from 'react'; import PropTable from './components/propTable'; import { storiesOf } from '@storybook/react'; import { checkA11y } from 'storybook-addon-a11y'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, boolean, select } from '@storybook/addon-knobs/react'; import { IconAddMediumOutline, IconAddSmallOutline } from '@teamleader/ui-icons'; import { IconButton } from '../components'; const colors = ['white', 'neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']; const elements = ['a', 'button', 'div', 'span']; const sizes = ['small', 'medium', 'large']; storiesOf('IconButtons', module) .addDecorator((story, context) => withInfo({ TableComponent: PropTable })(story)(context)) .addDecorator(checkA11y) .addDecorator(withKnobs) .add('Basic', () => ( <IconButton icon={select('Size', sizes, 'medium') === 'small' ? <IconAddSmallOutline /> : <IconAddMediumOutline />} color={select('Color', colors, 'neutral')} size={select('Size', sizes, 'medium')} disabled={boolean('Disabled', false)} /> )) .add('With custom element', () => ( <IconButton icon={select('Size', sizes, 'medium') === 'small' ? <IconAddSmallOutline /> : <IconAddMediumOutline />} color={select('Color', colors, 'neutral')} element={select('Element', elements, 'a')} size={select('Size', sizes, 'medium')} disabled={boolean('Disabled', false)} /> ));
import React from 'react'; import PropTable from './components/propTable'; import { storiesOf } from '@storybook/react'; import { checkA11y } from 'storybook-addon-a11y'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, boolean, select } from '@storybook/addon-knobs/react'; import { IconAddMediumOutline, IconAddSmallOutline } from '@teamleader/ui-icons'; import { IconButton } from '../components'; const colors = ['white', 'neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby']; const sizes = ['small', 'medium', 'large']; storiesOf('IconButtons', module) .addDecorator((story, context) => withInfo({ TableComponent: PropTable })(story)(context)) .addDecorator(checkA11y) .addDecorator(withKnobs) .add('Basic', () => ( <IconButton icon={select('Size', sizes, 'medium') === 'small' ? <IconAddSmallOutline /> : <IconAddMediumOutline />} color={select('Color', colors, 'neutral')} size={select('Size', sizes, 'medium')} disabled={boolean('Disabled', false)} /> ));
Revise for loop for timezones to work with Chrome
window.onload = function main() { var timezones = document.querySelectorAll('.timezone'); var getCalendarOffset = function getCalendarOffset(timezone) { var localTime = moment.tz(moment().format('YYYY-MM-DD, HH:mm:ss'), 'America/Los_Angeles'); return moment.tz(timezone).calendar(localTime, { sameDay: '[Today]', nextDay: '[Tomorrow]', nextWeek: 'dddd', lastDay: '[Yesterday]', lastWeek: '[Last] dddd', sameElse: 'YYYY-MM-DD' }); } var updateTimes = function updateTimes() { for (var i = 0, length = timezones.length; i < length; i++) { var timezone = timezones[i]; timezone.getElementsByClassName('timezone__time')[0].textContent = moment.tz(timezone.dataset.timezone).format('HH:mm:ss z'); timezone.getElementsByClassName('timezone__offset')[0].textContent = getCalendarOffset(timezone.dataset.timezone); } } setInterval(updateTimes, 500); };
window.onload = function main() { var timezones = document.querySelectorAll('.timezone'); var getCalendarOffset = function getCalendarOffset(timezone) { var localTime = moment.tz(moment().format('YYYY-MM-DD, HH:mm:ss'), 'America/Los_Angeles'); return moment.tz(timezone).calendar(localTime, { sameDay: '[Today]', nextDay: '[Tomorrow]', nextWeek: 'dddd', lastDay: '[Yesterday]', lastWeek: '[Last] dddd', sameElse: 'YYYY-MM-DD' }); } var updateTimes = function updateTimes() { for (var timezone of timezones) { timezone.getElementsByClassName('timezone__time')[0].textContent = moment.tz(timezone.dataset.timezone).format('HH:mm:ss z'); timezone.getElementsByClassName('timezone__offset')[0].textContent = getCalendarOffset(timezone.dataset.timezone); } } setInterval(updateTimes, 500); };
Add bold to current category on list
import React, { Component, PropTypes } from 'react' import Relay from 'react-relay'; export default class CategoryFilter extends Component { static propTypes = { category: PropTypes.object.isRequired } render() { const { category } = this.props; return ( <div className="categories"> <h3>Categories:</h3> <ul> <li className="current"> <a href={category.url}><strong>{category.name}</strong></a> <span>{category.productsCount}</span> </li> {category.siblings && (category.siblings.map((sibling) => { return ( <li key={sibling.pk} className="item"> <a href={sibling.url}>{sibling.name}</a> <span>{sibling.productsCount}</span> </li> ); }) )} </ul> </div> ); } }
import React, { Component, PropTypes } from 'react' import Relay from 'react-relay'; export default class CategoryFilter extends Component { static propTypes = { category: PropTypes.object.isRequired } render() { const { category } = this.props; return ( <div className="categories"> <h3>Categories:</h3> <ul> <li className="current"> <a href={category.url}>{category.name}</a> <span>{category.productsCount}</span> </li> {category.siblings && (category.siblings.map((sibling) => { return ( <li key={sibling.pk} className="item"> <a href={sibling.url}>{sibling.name}</a> <span>{sibling.productsCount}</span> </li> ); }) )} </ul> </div> ); } }
Fix SpiderState bug in Windows platforms The spider state file was not opened in binary mode.
import os, cPickle as pickle from scrapy import signals class SpiderState(object): """Store and load spider state during a scraping job""" def __init__(self, jobdir=None): self.jobdir = jobdir @classmethod def from_crawler(cls, crawler): obj = cls(crawler.settings.get('JOBDIR')) crawler.signals.connect(obj.spider_closed, signal=signals.spider_closed) crawler.signals.connect(obj.spider_opened, signal=signals.spider_opened) return obj def spider_closed(self, spider): if self.jobdir: with open(self.statefn, 'wb') as f: pickle.dump(spider.state, f, protocol=2) def spider_opened(self, spider): if self.jobdir and os.path.exists(self.statefn): with open(self.statefn, 'rb') as f: spider.state = pickle.load(f) else: spider.state = {} @property def statefn(self): return os.path.join(self.jobdir, 'spider.state')
import os, cPickle as pickle from scrapy import signals class SpiderState(object): """Store and load spider state during a scraping job""" def __init__(self, jobdir=None): self.jobdir = jobdir @classmethod def from_crawler(cls, crawler): obj = cls(crawler.settings.get('JOBDIR')) crawler.signals.connect(obj.spider_closed, signal=signals.spider_closed) crawler.signals.connect(obj.spider_opened, signal=signals.spider_opened) return obj def spider_closed(self, spider): if self.jobdir: with open(self.statefn, 'wb') as f: pickle.dump(spider.state, f, protocol=2) def spider_opened(self, spider): if self.jobdir and os.path.exists(self.statefn): with open(self.statefn) as f: spider.state = pickle.load(f) else: spider.state = {} @property def statefn(self): return os.path.join(self.jobdir, 'spider.state')
Tweak login required and auth settings to work with C3
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ from django.conf.urls.defaults import * from xgds_map_server import settings from xgds_map_server.views import * urlpatterns = patterns( '', (r'^$', getMapListPage, {'readOnly': True}, 'xgds_map_server_index'), # Map server urls # HTML list of maps with description and links to individual maps, and a link to the kml feed (r'^list/', getMapListPage, {'readOnly': True}, 'mapList'), # This URL should receive a static files (r'^data/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR, 'show_indexes' : True, 'readOnly': True}, 'xgds_map_server_static'), # By default if you just load the app you should see the list (r'^feed/(?P<feedname>.*)', getMapFeed, {'readOnly': True, 'loginRequired': False}, 'xgds_map_server_feed'), )
# __BEGIN_LICENSE__ # Copyright (C) 2008-2010 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # __END_LICENSE__ from django.conf.urls.defaults import * from xgds_map_server import settings from xgds_map_server.views import * urlpatterns = patterns( '', (r'^$', getMapListPage, {'readOnly': True}, 'xgds_map_server_index'), # Map server urls # HTML list of maps with description and links to individual maps, and a link to the kml feed (r'^list/', getMapListPage, {'readOnly': True}, 'mapList'), # This URL should receive a static files (r'^data/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR, 'show_indexes' : True, 'readOnly': True}, 'xgds_map_server_static'), # By default if you just load the app you should see the list (r'^feed/(?P<feedname>.*)', getMapFeed, {'readOnly': True, 'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE}, 'xgds_map_server_feed'), )
Fix tag preFetch request param bug.
/** * Created by jack on 16-8-27. */ import vue from 'vue'; import { mapState, mapActions } from 'vuex'; import template from './tags.html'; import tagsActions from 'vuexModule/tags/actions'; const Tags = vue.extend({ template, computed: mapState({ header: state => state.tags.header, tagsList: state => state.tags.list, isLoading: state => state.tags.isLoading, tagName: state => state.route.params.tagName }), methods: mapActions(['initTagsPage', 'queryTagsList']), watch: { 'tagName': function() { this.queryTagsList({ tagName: this.tagName, router: this.$router }); } }, created() { this.initTagsPage(); this.queryTagsList({ tagName: this.tagName, enableLoading: this.$root._isMounted, router: this.$router }); }, preFetch(store) { return tagsActions.queryTagsList(store, { tagName: store.state.route.params.tagName, enableLoading: false, router: this.$router }); } }); export default Tags;
/** * Created by jack on 16-8-27. */ import vue from 'vue'; import { mapState, mapActions } from 'vuex'; import template from './tags.html'; import tagsActions from 'vuexModule/tags/actions'; const Tags = vue.extend({ template, computed: mapState({ header: state => state.tags.header, tagsList: state => state.tags.list, isLoading: state => state.tags.isLoading, tagName: state => state.route.params.tagName }), methods: mapActions(['initTagsPage', 'queryTagsList']), watch: { 'tagName': function() { this.queryTagsList({ tagName: this.tagName, router: this.$router }); } }, created() { this.initTagsPage(); this.queryTagsList({ tagName: this.tagName, enableLoading: this.$root._isMounted, router: this.$router }); }, preFetch(store) { return tagsActions.queryTagsList(store, { postName: store.state.route.params.postName, enableLoading: false, router: this.$router }); } }); export default Tags;
Initialize the ApplicationModule for Dagger.
package com.studio4plus.homerplayer; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; public class HomerPlayerApplication extends Application { private static final String AUDIOBOOKS_DIRECTORY = "AudioBooks"; private ApplicationComponent component; private MediaScannerReceiver mediaScannerReceiver; @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .audioBookManagerModule(new AudioBookManagerModule(AUDIOBOOKS_DIRECTORY)) .build(); IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addDataScheme("file"); mediaScannerReceiver = new MediaScannerReceiver(); registerReceiver(mediaScannerReceiver, intentFilter); } @Override public void onTerminate() { super.onTerminate(); unregisterReceiver(mediaScannerReceiver); mediaScannerReceiver = null; } public static ApplicationComponent getComponent(Context context) { return ((HomerPlayerApplication) context.getApplicationContext()).component; } }
package com.studio4plus.homerplayer; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; public class HomerPlayerApplication extends Application { private static final String AUDIOBOOKS_DIRECTORY = "AudioBooks"; private ApplicationComponent component; private MediaScannerReceiver mediaScannerReceiver; @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder() .audioBookManagerModule(new AudioBookManagerModule(AUDIOBOOKS_DIRECTORY)) .build(); IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addDataScheme("file"); mediaScannerReceiver = new MediaScannerReceiver(); registerReceiver(mediaScannerReceiver, intentFilter); } @Override public void onTerminate() { super.onTerminate(); unregisterReceiver(mediaScannerReceiver); mediaScannerReceiver = null; } public static ApplicationComponent getComponent(Context context) { return ((HomerPlayerApplication) context.getApplicationContext()).component; } }
Revert "check defaultPrevented when intercepting link clicks"
/* global window */ 'use strict' var win = typeof window === 'undefined' ? null : window exports.routeFromLocation = function routeFromLocation (event, router) { router.route(win.location.href) } exports.routeFromLinkClick = function routeFromLinkClick (event, router) { // ignore if it could open a new window, if a right click if ( event.metaKey || event.shiftKey || event.ctrlKey || event.altKey || event.which === 3 || event.button === 2 ) return // ignore if not a link click var html = win.document.documentElement var target = event.target while (target && !target.href && target !== html) { target = target.parentNode } if (!target || !target.href) return // ignore if not the same origin as the page var location = win.location var origin = location.origin || (location.protocol + '//' + location.host) if (target.href.slice(0, origin.length) !== origin) return event.preventDefault() var path = target.href.slice(origin.length) var hash = router.hash if (hash && path.indexOf(hash) >= 0) { path = path.slice(path.indexOf(hash) + hash.length) } router.navigate(path) }
/* global window */ 'use strict' var win = typeof window === 'undefined' ? null : window exports.routeFromLocation = function routeFromLocation (event, router) { router.route(win.location.href) } exports.routeFromLinkClick = function routeFromLinkClick (event, router) { setTimeout(function () { // ignore if it could open a new window, if a right click if ( event.metaKey || event.shiftKey || event.ctrlKey || event.altKey || event.which === 3 || event.button === 2 || event.defaultPrevented ) return // ignore if not a link click var html = win.document.documentElement var target = event.target while (target && !target.href && target !== html) { target = target.parentNode } if (!target || !target.href) return // ignore if not the same origin as the page var location = win.location var origin = location.origin || (location.protocol + '//' + location.host) if (target.href.slice(0, origin.length) !== origin) return event.preventDefault() var path = target.href.slice(origin.length) var hash = router.hash if (hash && path.indexOf(hash) >= 0) { path = path.slice(path.indexOf(hash) + hash.length) } router.navigate(path) }, 0) }
Add Gygabytes filter unit test
(function () { 'use strict'; describe('filters module', function () { var $filter; beforeEach(module('filters')); beforeEach(inject(function ($injector) { $filter = $injector.get('$filter'); })); describe('Megabytes', function () { var Megabytes; beforeEach(function () { Megabytes = $filter('Megabytes'); }); it('should append the suffix MB to an argument', function () { expect(Megabytes(0)).toBe('0 MB'); }); }); describe('Gygabytes', function () { var Gygabytes; beforeEach(function () { Gygabytes = $filter('Gygabytes'); }); it('should append the suffix GB to an argument', function () { expect(Gygabytes(0)).toBe('0 GB'); }); }); }); })();
(function () { 'use strict'; describe('filters module', function () { var $filter; beforeEach(module('filters')); beforeEach(inject(function ($injector) { $filter = $injector.get('$filter'); })); describe('Megabytes', function () { var Megabytes; beforeEach(function () { Megabytes = $filter('Megabytes'); }); it('should append the suffix MB to an argument', function () { expect(Megabytes(0)).toBe('0 MB'); }); }); }); })();
Fix variable conflict in source condition.
/* * Copyright 2013 the original author or 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 net.kuujo.vertigo.output.condition; import net.kuujo.vertigo.messaging.JsonMessage; import org.vertx.java.core.json.JsonObject; /** * A source condition. * * @author Jordan Halterman */ public class SourceCondition implements Condition { private String source; public SourceCondition() { } public SourceCondition(String source) { this.source = source; } @Override public JsonObject getState() { return new JsonObject().putString("source", source); } @Override public void setState(JsonObject state) { source = state.getString("source"); } @Override public boolean isValid(JsonMessage message) { String source = message.source(); return source != null && source.equals(this.source); } }
/* * Copyright 2013 the original author or 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 net.kuujo.vertigo.output.condition; import net.kuujo.vertigo.messaging.JsonMessage; import org.vertx.java.core.json.JsonObject; /** * A source condition. * * @author Jordan Halterman */ public class SourceCondition implements Condition { private String source; public SourceCondition() { } public SourceCondition(String source) { this.source = source; } @Override public JsonObject getState() { return new JsonObject().putString("source", source); } @Override public void setState(JsonObject state) { source = state.getString("source"); } @Override public boolean isValid(JsonMessage message) { String source = message.source(); return source != null && source.equals(source); } }
Fix the default size for emojis This is a left over from the default props eslint update. [Finishes: #137727295](https://www.pivotaltracker.com/story/show/137727295)
import React, { PropTypes } from 'react' import classNames from 'classnames' const Emoji = (props) => { const { alt, className, name = 'ello', size, src, title, width, height } = props const tip = name.replace(/_|-/, ' ') return ( <img {...props} alt={alt || tip} className={classNames(className, 'Emoji')} src={src || `${ENV.AUTH_DOMAIN}/images/emoji/${name}.png`} title={title || tip} width={width || size} height={height || size} size={null} name={null} /> ) } Emoji.propTypes = { alt: PropTypes.string, className: PropTypes.string, name: PropTypes.string, size: PropTypes.number, src: PropTypes.string, title: PropTypes.string, width: PropTypes.number, height: PropTypes.number, } Emoji.defaultProps = { alt: null, className: null, name: null, size: 20, src: null, title: null, width: null, height: null, } export default Emoji
import React, { PropTypes } from 'react' import classNames from 'classnames' const Emoji = (props) => { const { alt, className, name = 'ello', size = 20, src, title, width, height } = props const tip = name.replace(/_|-/, ' ') return ( <img {...props} alt={alt || tip} className={classNames(className, 'Emoji')} src={src || `${ENV.AUTH_DOMAIN}/images/emoji/${name}.png`} title={title || tip} width={width || size} height={height || size} size={null} name={null} /> ) } Emoji.propTypes = { alt: PropTypes.string, className: PropTypes.string, name: PropTypes.string, size: PropTypes.number, src: PropTypes.string, title: PropTypes.string, width: PropTypes.number, height: PropTypes.number, } Emoji.defaultProps = { alt: null, className: null, name: null, size: null, src: null, title: null, width: null, height: null, } export default Emoji
Make the test a bit more verbose.
#!/usr/bin/env python3 """An orange rectangle should be displayed on top of a green one. When you click with the mouse, the green rectangle should move on top. When you release the mouse, the orange rectangle should move back to the top.""" import pyglet import glooey import vecrec from glooey.drawing import green, orange print(__doc__) window = pyglet.window.Window() batch = pyglet.graphics.Batch() rect_1 = vecrec.Rect.from_pyglet_window(window) rect_1.shrink(50) rect_2 = rect_1 + (10,-10) bg = pyglet.graphics.OrderedGroup(0) fg = pyglet.graphics.OrderedGroup(1) artist_1 = glooey.drawing.Rectangle(rect_1, color=green, batch=batch, group=bg) artist_2 = glooey.drawing.Rectangle(rect_2, color=orange, batch=batch, group=fg) @window.event def on_draw(): window.clear() batch.draw() @window.event def on_mouse_press(self, *args): print("- green in front") artist_1.group = fg artist_2.group = bg @window.event def on_mouse_release(self, *args): print("- orange in front") artist_1.group = bg artist_2.group = fg pyglet.app.run()
#!/usr/bin/env python3 """An orange rectangle should be displayed on top of a green one. When you click with the mouse, the green rectangle should move on top. When you release the mouse, the orange rectangle should move back to the top.""" import pyglet import glooey import vecrec from glooey.drawing import green, orange print(__doc__) window = pyglet.window.Window() batch = pyglet.graphics.Batch() rect_1 = vecrec.Rect.from_pyglet_window(window) rect_1.shrink(50) rect_2 = rect_1 + (10,-10) bg = pyglet.graphics.OrderedGroup(0) fg = pyglet.graphics.OrderedGroup(1) artist_1 = glooey.drawing.Rectangle(rect_1, color=green, batch=batch, group=bg) artist_2 = glooey.drawing.Rectangle(rect_2, color=orange, batch=batch, group=fg) @window.event def on_draw(): print('(draw)') window.clear() batch.draw() @window.event def on_mouse_press(self, *args): print("- green in front") artist_1.group = fg artist_2.group = bg @window.event def on_mouse_release(self, *args): print("- orange in front") artist_1.group = bg artist_2.group = fg pyglet.app.run()
Add press releases to dashboard panel
# Do not commit secrets to VCS. # Local environment variables will be loaded from `.env.local`. # Additional environment variables will be loaded from `.env.$DOTENV`. # Local settings will be imported from `icekit_settings_local.py` from icekit.project.settings.calculated import * # OVERRIDE #################################################################### # Override the default ICEkit settings to form project settings. # Add apps for your project here. INSTALLED_APPS += ( # 'debug_toolbar', # INSTALLED BY SETUP.PY 'sponsors', 'press_releases', # INCLUDED IN PROJECT TEMPLATE 'articles', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) # Add "Articles" to the dashboard. FEATURED_APPS[0]['models']['glamkit_articles.Article'] = { 'verbose_name_plural': 'Articles', } FEATURED_APPS[0]['models']['icekit_press_releases.PressRelease'] = { 'verbose_name_plural': 'Press releases', }
# Do not commit secrets to VCS. # Local environment variables will be loaded from `.env.local`. # Additional environment variables will be loaded from `.env.$DOTENV`. # Local settings will be imported from `icekit_settings_local.py` from icekit.project.settings.calculated import * # OVERRIDE #################################################################### # Override the default ICEkit settings to form project settings. # Add apps for your project here. INSTALLED_APPS += ( # 'debug_toolbar', # INSTALLED BY SETUP.PY 'sponsors', 'press_releases', # INCLUDED IN PROJECT TEMPLATE 'articles', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) # Add "Articles" to the dashboard. FEATURED_APPS[0]['models']['glamkit_articles.Article'] = { 'verbose_name_plural': 'Articles', } ICEKIT['LAYOUT_TEMPLATES'] += ( ( SITE_NAME, os.path.join(PROJECT_DIR, 'templates/layouts'), 'layouts', ), )
Add more detail to test failure message
<?php declare(strict_types=1); namespace Tests\Feature; use Tests\TestCase; class SimpleRequestsTest extends TestCase { /** * Test simple, non-CAS requests load without any authentication. */ public function testUnauthenticatedRequests(): void { $response = $this->get('/privacy'); $response->assertStatus(200); $response = $this->get('/attendance/kiosk'); $response->assertStatus(200); } /** * Test that the home page loads successfully. */ public function testHome(): void { $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); // $response->assertStatus(200); $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); // $response->assertStatus(200); } }
<?php declare(strict_types=1); namespace Tests\Feature; use Tests\TestCase; class SimpleRequestsTest extends TestCase { /** * Test simple, non-CAS requests load without any authentication. */ public function testUnauthenticatedRequests(): void { $response = $this->get('/privacy'); $response->assertStatus(200); $response = $this->get('/attendance/kiosk'); $response->assertStatus(200); } /** * Test that the home page loads successfully. */ public function testHome(): void { $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/'); $response->assertStatus(200); $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/'); $response->assertStatus(200); } }
Print out all the failing things Instead of just running one check, run them all. Signed-off-by: Anthony Emengo <7b3c5a7825e2f856203b8d882230abcb78036abf@pivotal.io>
package main import ( "checks" "flag" "log" "github.com/mitchellh/go-ps" ) var ( gardenAddr = flag.String("gardenAddr", "localhost:9241", "Garden host and port (typically localhost:9241)") requiredProcesses = []string{"consul.exe", "containerizer.exe", "garden-windows.exe", "rep.exe", "metron.exe"} bbsConsulHost = "bbs.service.cf.internal" ) func main() { flag.Parse() processes, err := ps.Processes() if err == nil { err = checks.ProcessCheck(processes, requiredProcesses) if err != nil { log.Print(err) } } else { log.Print(err) } err = checks.ContainerCheck(*gardenAddr) if err != nil { log.Print(err) } err = checks.ConsulDnsCheck(bbsConsulHost) if err != nil { log.Print(err) } err = checks.FairShareCpuCheck() if err != nil { log.Print(err) } err = checks.FirewallCheck() if err != nil { log.Print(err) } err = checks.NtpCheck() if err != nil { log.Print(err) } }
package main import ( "checks" "flag" "log" "github.com/mitchellh/go-ps" ) var ( gardenAddr = flag.String("gardenAddr", "localhost:9241", "Garden host and port (typically localhost:9241)") requiredProcesses = []string{"consul.exe", "containerizer.exe", "garden-windows.exe", "rep.exe", "metron.exe"} bbsConsulHost = "bbs.service.cf.internal" ) func main() { flag.Parse() processes, err := ps.Processes() if err != nil { panic(err) } err = checks.ProcessCheck(processes, requiredProcesses) if err != nil { log.Fatal(err) } err = checks.ContainerCheck(*gardenAddr) if err != nil { log.Fatal(err) } err = checks.ConsulDnsCheck(bbsConsulHost) if err != nil { log.Fatal(err) } err = checks.FairShareCpuCheck() if err != nil { log.Fatal(err) } err = checks.FirewallCheck() if err != nil { log.Fatal(err) } err = checks.NtpCheck() if err != nil { log.Fatal(err) } }
Refactor the CachedTemplate so that the render method does not have to use 'this'.
(function(Mustache) { var CachedTemplate = function(template) { var self = this; /* The text of the template. */ self.template = template; /* Turns this template into HTML using the given view data. */ self.render = function(view, partials, send_fun) { // Use either the parials specified, or the entire set of templates // stored in Mustache.TEMPLATES partials = partials || Mustache.TEMPLATES; return Mustache.to_html(self.template, view, partials, send_fun); }; }; /* Creates a new Template object. */ Mustache.template = function(name) { var template = Mustache.TEMPLATES[name]; return new CachedTemplate(template); }; })(Mustache);
(function(Mustache) { var CachedTemplate = function(template) { this.template = template; }; CachedTemplate.prototype = { /* Turns this template into HTML using the given view data. */ render: function(view, partials, send_fun) { // Use either the parials specified, or the entire set of templates // stored in Mustache.TEMPLATES partials = partials || Mustache.TEMPLATES; return Mustache.to_html(this.template, view, partials, send_fun); } } /* Creates a new Template object. */ Mustache.template = function(name) { var template = Mustache.TEMPLATES[name]; return new CachedTemplate(template); }; })(Mustache);
Remove unnecessary wrapping div from search block.
<?php /** * @file * Displays the search form block. * * Available variables: * - $search_form: The complete search form ready for print. * - $search: Associative array of search elements. Can be used to print each * form element separately. * * Default elements within $search: * - $search['search_block_form']: Text input area wrapped in a div. * - $search['actions']: Rendered form buttons. * - $search['hidden']: Hidden form elements. Used to validate forms when * submitted. * * Modules can add to the search form, so it is recommended to check for their * existence before printing. The default keys will always exist. To check for * a module-provided field, use code like this: * @code * <?php if (isset($search['extra_field'])): ?> * <div class="extra-field"> * <?php print $search['extra_field']; ?> * </div> * <?php endif; ?> * @endcode * * @see template_preprocess_search_block_form() */ ?> <?php if (empty($variables['form']['#block']->subject)): ?> <?php endif; ?> <?php print $search['search_block_form']; ?> <?php print $search['hidden']; ?>
<?php /** * @file * Displays the search form block. * * Available variables: * - $search_form: The complete search form ready for print. * - $search: Associative array of search elements. Can be used to print each * form element separately. * * Default elements within $search: * - $search['search_block_form']: Text input area wrapped in a div. * - $search['actions']: Rendered form buttons. * - $search['hidden']: Hidden form elements. Used to validate forms when * submitted. * * Modules can add to the search form, so it is recommended to check for their * existence before printing. The default keys will always exist. To check for * a module-provided field, use code like this: * @code * <?php if (isset($search['extra_field'])): ?> * <div class="extra-field"> * <?php print $search['extra_field']; ?> * </div> * <?php endif; ?> * @endcode * * @see template_preprocess_search_block_form() */ ?> <div class="container-inline"> <?php if (empty($variables['form']['#block']->subject)): ?> <?php endif; ?> <?php print $search['search_block_form']; ?> <?php print $search['hidden']; ?> </div>
Set default date to current
<?php class Denkmal_Form_EventAdd extends CM_Form_Abstract { public function setup () { $this->registerField(new Denkmal_FormField_Venue('venue')); $this->registerField(new CM_FormField_Text('venueAddress')); $this->registerField(new CM_FormField_Text('venueUrl')); $this->registerField(new CM_FormField_Date('date', date('Y'), (int) date('Y') + 1)); $this->registerField(new Denkmal_FormField_Time('fromTime')); $this->registerField(new Denkmal_FormField_Time('untilTime')); $this->registerField(new CM_FormField_Text('title')); $this->registerField(new CM_FormField_Text('artists')); $this->registerField(new CM_FormField_Text('genres')); $this->registerField(new CM_FormField_Text('urls')); $this->registerAction(new Denkmal_FormAction_EventAdd_Create()); } public function renderStart(array $params = null) { $this->getField('date')->setValue(new DateTime()); } }
<?php class Denkmal_Form_EventAdd extends CM_Form_Abstract { public function setup () { $this->registerField(new Denkmal_FormField_Venue('venue')); $this->registerField(new CM_FormField_Text('venueAddress')); $this->registerField(new CM_FormField_Text('venueUrl')); $this->registerField(new CM_FormField_Date('date', date('Y'), (int) date('Y') + 1)); $this->registerField(new Denkmal_FormField_Time('fromTime')); $this->registerField(new Denkmal_FormField_Time('untilTime')); $this->registerField(new CM_FormField_Text('title')); $this->registerField(new CM_FormField_Text('artists')); $this->registerField(new CM_FormField_Text('genres')); $this->registerField(new CM_FormField_Text('urls')); $this->registerAction(new Denkmal_FormAction_EventAdd_Create()); } }
Remove a not using import stantment
<?php namespace App\Auth; abstract class PermissionManager { abstract public function __construct(array $settings = []); /** * @return array|null */ abstract public function getRolesByOperation($operation); /** * @return bool */ public function hasAllowedRole($accountId, $operation) { $operationAllowedRoles = $this->getRolesByOperation($operation); $accountRoles = AuthManager::getAccountManager()->getRole($accountId) ?: []; if ($operationAllowedRoles === null) { return AuthManager::isDefaultAllow(); } foreach ($accountRoles as $role) { if (in_array($role, $operationAllowedRoles) === true) { return true; } } return false; } }
<?php namespace App\Auth; use Prob\Handler\ProcInterface; abstract class PermissionManager { abstract public function __construct(array $settings = []); /** * @return array|null */ abstract public function getRolesByOperation($operation); /** * @return bool */ public function hasAllowedRole($accountId, $operation) { $operationAllowedRoles = $this->getRolesByOperation($operation); $accountRoles = AuthManager::getAccountManager()->getRole($accountId) ?: []; if ($operationAllowedRoles === null) { return AuthManager::isDefaultAllow(); } foreach ($accountRoles as $role) { if (in_array($role, $operationAllowedRoles) === true) { return true; } } return false; } }
Remove README from pypi descriptioj
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', 'tabulate==0.7.7', ] setup( name="wincast", version='0.0.8', url='https://github.com/kahnjw/wincast', author_email='jarrod.kahn+wincast@gmail.com', license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, package_data={ 'wincast': ['models/wincast.clf.pkl', 'models/wincast.scaler.pkl'] } )
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', 'tabulate==0.7.7', ] with open('README.md', 'r') as f: readme = f.read() setup( name="wincast", version='0.0.8', url='https://github.com/kahnjw/wincast', author_email='jarrod.kahn+wincast@gmail.com', long_description=readme, license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, package_data={ 'wincast': ['models/wincast.clf.pkl', 'models/wincast.scaler.pkl'] } )
Make client key checking actually work.
from locksmith.common import apicall import urllib2 try: from django.conf import settings SIGNING_KEY = settings.LOCKSMITH_SIGNING_KEY API_NAME = settings.LOCKSMITH_API_NAME ENDPOINT = settings.LOCKSMITH_HUB_URL.replace('analytics', 'accounts') + 'checkkey/' except: SIGNING_KEY = "" API_NAME = "" ENDPOINT = "" def check_key(key, signing_key=SIGNING_KEY, api=API_NAME, endpoint=ENDPOINT): try: apicall(endpoint, signing_key, api=api, key=key ) return True except urllib2.HTTPError as e: if e.code == 404: return None else: raise
from locksmith.common import apicall try: from django.conf import settings SIGNING_KEY = settings.LOCKSMITH_SIGNING_KEY, API_NAME = settings.LOCKSMITH_API_NAME ENDPOINT = settings.LOCKSMITH_HUB_URL.replace('analytics', 'accounts') + 'checkkey/' except: SIGNING_KEY = "" API_NAME = "" ENDPOINT = "" def check_key(key, signing_key=SIGNING_KEY, api=API_NAME, endpoint=ENDPOINT): try: apicall(endpoint, signing_key, api=api, endpoint=endpoint, key=key ) except urllib2.HTTPError as e: if e.code == 404: return None else: raise
Add .pull-right to resources sidebar nav. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
@extends('orchestra/foundation::layout.main') @section('content') <div class="row"> <div class="three columns"> <div class="list-group"> <?php foreach ($resources['list'] as $name => $resource) : ?> <a href="<?php echo resources($name); ?>" class="list-group-item <?php echo Request::is("*/resources/{$name}*") ? 'active' : ''; ?>"> <?php echo $resource->name; ?> <span class="glyphicon glyphicon-chevron-right pull-right"></span> </a> <?php endforeach; ?> </div> @placeholder("orchestra.resources: {$resource->name}") @placeholder('orchestra.resources') </div> <div class="nine columns"> <?php echo $content; ?> </div> </div> @stop
@extends('orchestra/foundation::layout.main') @section('content') <div class="row"> <div class="three columns"> <div class="list-group"> <?php foreach ($resources['list'] as $name => $resource) : ?> <a href="<?php echo resources($name); ?>" class="list-group-item <?php echo Request::is("*/resources/{$name}*") ? 'active' : ''; ?>"> <?php echo $resource->name; ?> <span class="glyphicon glyphicon-chevron-right"></span> </a> <?php endforeach; ?> </div> @placeholder("orchestra.resources: {$resource->name}") @placeholder('orchestra.resources') </div> <div class="nine columns"> <?php echo $content; ?> </div> </div> @stop
Hide WP Logo form the admin bar
<?php /* * Plugin Name: Hide Menu * Plugin URI: http://pothi.info * Author: Pothi Kalimuthu * Author URI: http://pothi.info * Description: Hides unneccessary menu item/s * Version: 1.0 * License: Apache 2.0 */ function tiny_remove_menus() { // Hide Ewww image optimizer settings that are found in four places $page = remove_submenu_page( 'options-general.php', 'ewww-image-optimizer/ewww-image-optimizer.php' ); $page = remove_submenu_page( 'tools.php', 'ewww-image-optimizer-aux-images' ); $page = remove_submenu_page( 'themes.php', 'ewww-image-optimizer-theme-images' ); $page = remove_submenu_page( 'upload.php', 'ewww-image-optimizer-bulk' ); } add_action( 'admin_menu', 'tiny_remove_menus', 999 ); function tiny_remove_admin_bar_nodes() { // Hide WP Logo from the admin bar global $wp_admin_bar; $wp_admin_bar->remove_node( 'wp-logo' ); } add_action( 'admin_bar_menu', 'tiny_remove_admin_bar_nodes', 999 );
<?php /* * Plugin Name: Hide Menu * Plugin URI: http://pothi.info * Author: Pothi Kalimuthu * Author URI: http://pothi.info * Description: Hides unneccessary menu item/s * Version: 1.0 * License: Apache 2.0 */ function tiny_remove_menus() { // Hide Ewww image optimizer settings that are found in four places $page = remove_submenu_page( 'options-general.php', 'ewww-image-optimizer/ewww-image-optimizer.php' ); $page = remove_submenu_page( 'tools.php', 'ewww-image-optimizer-aux-images' ); $page = remove_submenu_page( 'themes.php', 'ewww-image-optimizer-theme-images' ); $page = remove_submenu_page( 'upload.php', 'ewww-image-optimizer-bulk' ); } add_action( 'admin_menu', 'tiny_remove_menus', 999 );
Order status changed to integer
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from bazaar.listings.models import Publishing, Store @python_2_unicode_compatible class Order(models.Model): ORDER_PENDING = 0 ORDER_COMPLETED = 1 ORDER_STATUS_CHOICES = ( (ORDER_PENDING, "Pending"), (ORDER_COMPLETED, "Completed"), ) external_id = models.CharField(max_length=256) store = models.ForeignKey(Store) publishing = models.ForeignKey(Publishing, null=True, blank=True) quantity = models.IntegerField(default=1) status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING) def __str__(self): return "Order %s from %s" % (self.external_id, self.store)
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from bazaar.listings.models import Publishing, Store @python_2_unicode_compatible class Order(models.Model): ORDER_PENDING = 0 ORDER_COMPLETED = 1 ORDER_STATUS_CHOICES = ( (ORDER_PENDING, "Pending"), (ORDER_COMPLETED, "Completed"), ) external_id = models.CharField(max_length=256) store = models.ForeignKey(Store) publishing = models.ForeignKey(Publishing, null=True, blank=True) quantity = models.IntegerField(default=1) status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING) def __str__(self): return "Order %s from %s" % (self.external_id, self.store)
Change wait period from 30 seconds to 60 seconds
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set()
Remove hardcoded shipping modification in order PDF view
from decimal import Decimal import StringIO from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.shortcuts import get_object_or_404 from pdfdocument.utils import pdf_response import plata import plata.reporting.product import plata.reporting.order @staff_member_required def product_xls(request): output = StringIO.StringIO() workbook = plata.reporting.product.product_xls() workbook.save(output) response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=products.xls' return response @staff_member_required def order_pdf(request, order_id): order = get_object_or_404(plata.shop_instance().order_model, pk=order_id) pdf, response = pdf_response('order-%09d' % order.id) plata.reporting.order.order_pdf(pdf, order) return response
from decimal import Decimal import StringIO from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.shortcuts import get_object_or_404 from pdfdocument.utils import pdf_response import plata import plata.reporting.product import plata.reporting.order @staff_member_required def product_xls(request): output = StringIO.StringIO() workbook = plata.reporting.product.product_xls() workbook.save(output) response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=products.xls' return response @staff_member_required def order_pdf(request, order_id): order = get_object_or_404(plata.shop_instance().order_model, pk=order_id) order.shipping_cost = 8 / Decimal('1.076') order.shipping_discount = 0 order.recalculate_total(save=False) pdf, response = pdf_response('order-%09d' % order.id) plata.reporting.order.order_pdf(pdf, order) return response
Fix Cross-domain issue with Tumblr AJAX response
<?php header('Access-Control-Allow-Origin: *'); header('Content-type: application/json'); include ("lib/tumblrPHP.php"); // Check if parameter is sent if(isset($_GET['user']) && $_GET['user'] != ''){ // Tumblr Username $username = $_GET['user']; // Enter your Consumer / Secret Key: $consumer = "CONSUMER_KEY"; $secret = "COMSUMER_SECRET"; $oauth_token = "OAUTH_TOKEN"; $oauth_token_secret = "OAUTH_TOKEN_SECRET"; // Create Instance of Tumblr class $tumblr = new Tumblr($consumer, $secret, $oauth_token, $oauth_token_secret); // Grab the followers by using the oauth_get method. $followers = $tumblr->oauth_get("/blog/".$username.".tumblr.com/followers"); // Encode JSON Response $json = json_encode($followers,true); $data = array('followers'=>$followers->response->total_users); // Print JSON Response echo json_encode($data, JSON_NUMERIC_CHECK); } ?>
<?php include ("lib/tumblrPHP.php"); // Check if parameter is sent if(isset($_GET['user']) && $_GET['user'] != ''){ // Tumblr Username $username = $_GET['user']; // Enter your Consumer / Secret Key: $consumer = "CONSUMER_KEY"; $secret = "COMSUMER_SECRET"; $oauth_token = "OAUTH_TOKEN"; $oauth_token_secret = "OAUTH_TOKEN_SECRET"; // Create Instance of Tumblr class $tumblr = new Tumblr($consumer, $secret, $oauth_token, $oauth_token_secret); // Grab the followers by using the oauth_get method. $followers = $tumblr->oauth_get("/blog/".$username.".tumblr.com/followers"); // Encode JSON Response $json = json_encode($followers,true); $data = array('followers'=>$followers->response->total_users); // Print JSON Response echo json_encode($data, JSON_NUMERIC_CHECK); } ?>
Fix invalid test and disable it due to V8 bug
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function () { return this; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); // http://code.google.com/p/v8/issues/detail?id=1381 // assertUndefined(obj.makeFilterLostThis()()); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function (x) { return x == this.element; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); assertFalse(obj.makeFilterLostThis()(40)); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
Remove outdated discord.py version requirement We'll come to incompatible versions when we get there. So far I've just been updating discord.py without issue.
#!/usr/bin/env python3 # WARNING! WIP, doesn't work correctly. # Still needs to understand the assets folder and make an executable out of __main__ from setuptools import setup, find_packages # TODO read README(.rst? .md looks bad on pypi) for long_description. # Could use pandoc, but the end user shouldn't need to do this in setup. # Alt. could have package-specific description. More error-prone though. setup( # More permanent entries name='crabbot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License' 'Programming Language :: Python :: 3.5' ], # Entries likely to be modified description='A simple Discord bot', version='0.0.1', # TODO figure out a version scheme. Ensure this gets updated. packages=find_packages(), # A little lazy install_requires=[ 'discord.py{}'.format(discordpy_version) ], extras_require={ 'voice': [ 'discord.py[voice]', 'youtube_dl' ] } # scripts=['__main__.py'] )
#!/usr/bin/env python3 # WARNING! WIP, doesn't work correctly. # Still needs to understand the assets folder and make an executable out of __main__ from setuptools import setup, find_packages # We want to restrict newer versions while we deal with upstream breaking changes. discordpy_version = '==0.11.0' # TODO read README(.rst? .md looks bad on pypi) for long_description. # Could use pandoc, but the end user shouldn't need to do this in setup. # Alt. could have package-specific description. More error-prone though. setup( # More permanent entries name='crabbot', author='TAOTheCrab', url='https://github.com/TAOTheCrab/CrabBot', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License' 'Programming Language :: Python :: 3.5' ], # Entries likely to be modified description='A simple Discord bot', version='0.0.1', # TODO figure out a version scheme. Ensure this gets updated. packages=find_packages(), # A little lazy install_requires=[ 'discord.py{}'.format(discordpy_version) ], extras_require={ 'voice': [ 'discord.py[voice]{}'.format(discordpy_version), 'youtube_dl' ] } # scripts=['__main__.py'] )
Put test stuff inside `if __name__ == '__main__'`
import re _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def strip_ansi(value): return _ansi_re.sub('', value) def len_exclude_ansi(value): return len(strip_ansi(value)) class ansi_str(str): """A str subclass, specialized for strings containing ANSI escapes. When you call the ``len`` method, it discounts ANSI color escape codes. This is beneficial, because ANSI color escape codes won't mess up code that tries to do alignment, padding, printing in columns, etc. """ _stripped = None def __len__(self, exclude_ansi=True): if exclude_ansi is False: return len(self[:]) if self._stripped is None: self._stripped = strip_ansi(self[:]) return len(self._stripped) if __name__ == '__main__': # s = ansi_str('abc') # print s # print len(s) s = ansi_str(u'\x1b[32m\x1b[1mSUCCESS\x1b[0m') print s print len(s) print s.__len__() print s.__len__(exclude_ansi=False) print(len_exclude_ansi(u'\x1b[32m\x1b[1mSUCCESS\x1b[0m'))
import re _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def strip_ansi(value): return _ansi_re.sub('', value) def len_exclude_ansi(value): return len(strip_ansi(value)) class ansi_str(str): """A str subclass, specialized for strings containing ANSI escapes. When you call the ``len`` method, it discounts ANSI color escape codes. This is beneficial, because ANSI color escape codes won't mess up code that tries to do alignment, padding, printing in columns, etc. """ _stripped = None def __len__(self, exclude_ansi=True): if exclude_ansi is False: return len(self[:]) if self._stripped is None: self._stripped = strip_ansi(self[:]) return len(self._stripped) # s = ansi_str('abc') # print s # print len(s) s = ansi_str(u'\x1b[32m\x1b[1mSUCCESS\x1b[0m') print s print len(s) print s.__len__() print s.__len__(exclude_ansi=False) print(len_exclude_ansi(u'\x1b[32m\x1b[1mSUCCESS\x1b[0m'))
Add timezone on api reset
<?php namespace App\Console; use App\Console\Commands\BackupRun; use App\Console\Commands\ResetApiKeyCount; use App\Console\Commands\UserCreate; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ UserCreate::class, ResetApiKeyCount::class, BackupRun::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('api-key:reset')->dailyAt('00:00')->timezone('America/Los_Angeles'); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
<?php namespace App\Console; use App\Console\Commands\BackupRun; use App\Console\Commands\ResetApiKeyCount; use App\Console\Commands\UserCreate; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ UserCreate::class, ResetApiKeyCount::class, BackupRun::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); $schedule->command('api-key:reset')->dailyAt('00:00'); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
Order in a more intuitive way Even though it doesn't matter which order these are in it ready better to have the board respond to a click after it is drawn.
const $ = require('jquery'); const Board = require('./board'); const Game = require('./game'); function start() { var board = new Board(); var game = new Game(board); board.game = game; game.welcome(); var canvasElement = document.getElementById('game'); canvasElement.addEventListener('click', update, false); function update(event) { var pos = getMousePos(canvasElement, event); var posx = pos.x; var posy = pos.y; board.renderBoard(canvasElement); board.respondToClick(posx, posy); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } } $(document).ready( function () { start(); });
const $ = require('jquery'); const Board = require('./board'); const Game = require('./game'); function start() { var board = new Board(); var game = new Game(board); board.game = game; game.welcome(); var canvasElement = document.getElementById('game'); canvasElement.addEventListener('click', update, false); function update(event) { var pos = getMousePos(canvasElement, event); var posx = pos.x; var posy = pos.y; board.respondToClick(posx, posy); board.renderBoard(canvasElement); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } } $(document).ready( function () { start(); });
fix(webpack): Fix whatwg-url URL externals entry
var path = require('path') module.exports = { entry: [ './src/index.js' ], output: { path: path.join(__dirname, '/dist/'), filename: 'oidc.rp.min.js', library: 'OIDC', libraryTarget: 'var' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }, externals: { 'node-fetch': 'fetch', 'text-encoding': 'TextEncoder', 'whatwg-url': 'window', '@trust/webcrypto': 'crypto' }, devtool: 'source-map' }
var path = require('path') module.exports = { entry: [ './src/index.js' ], output: { path: path.join(__dirname, '/dist/'), filename: 'oidc.rp.min.js', library: 'OIDC', libraryTarget: 'var' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }, externals: { 'node-fetch': 'fetch', 'text-encoding': 'TextEncoder', 'whatwg-url': 'URL', '@trust/webcrypto': 'crypto' }, devtool: 'source-map' }
Extend vim-devicons display script range
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e5fa" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, 16) + 1): print unichr(ii), font_awesome_start = "f000" font_awesome_end = "f295" print "\nFont Awesome" for ii in xrange(int(font_awesome_start, 16), int(font_awesome_end, 16) + 1): print unichr(ii), powerline_start = "e0a0" powerline_end = "e0d4" print "\nPowerline" for ii in xrange(int(powerline_start, 16), int(powerline_end, 16) + 1): print unichr(ii),
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e600" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, 16) + 1): print unichr(ii), font_awesome_start = "f000" font_awesome_end = "f280" print "\nFont Awesome" for ii in xrange(int(font_awesome_start, 16), int(font_awesome_end, 16) + 1): print unichr(ii), powerline_start = "e0a0" powerline_end = "e0d4" print "\nPowerline" for ii in xrange(int(powerline_start, 16), int(powerline_end, 16) + 1): print unichr(ii),
Fix overflowing page title when resizing the page In the moe-list page, after the height of the thumbnails have been calculated and evened out, when resizing the page, the page title overfloed with the page count at time. Closes #89
/* Cached Variables *******************************************************************************/ var context = sessionStorage.getItem('context'); var rowThumbnails = document.querySelector('.row-thumbnails'); /* Initialization *********************************************************************************/ rowThumbnails.addEventListener("click", moeRedirect, false); function moeRedirect(event) { var target = event.target; var notImage = target.className !== 'thumbnail-image'; if(notImage) return; var pageId = target.getAttribute('data-page-id'); window.location.href = context + '/page/' + pageId; } var thumbnails = window.document.querySelectorAll('.thumbnail'); var tallestThumbnailSize = 0; thumbnails.forEach(function(value, key, listObj, argument) { var offsetHeight = listObj[key].offsetHeight; if(offsetHeight > tallestThumbnailSize) tallestThumbnailSize = offsetHeight; }); thumbnails.forEach(function(value, key, listObj, argument) { listObj[key].setAttribute('style','min-height:' + tallestThumbnailSize + 'px'); });
/* Cached Variables *******************************************************************************/ var context = sessionStorage.getItem('context'); var rowThumbnails = document.querySelector('.row-thumbnails'); /* Initialization *********************************************************************************/ rowThumbnails.addEventListener("click", moeRedirect, false); function moeRedirect(event) { var target = event.target; var notImage = target.className !== 'thumbnail-image'; if(notImage) return; var pageId = target.getAttribute('data-page-id'); window.location.href = context + '/page/' + pageId; } var thumbnails = window.document.querySelectorAll('.thumbnail'); var tallestThumbnailSize = 0; thumbnails.forEach(function(value, key, listObj, argument) { var offsetHeight = listObj[key].offsetHeight; if(offsetHeight > tallestThumbnailSize) tallestThumbnailSize = offsetHeight; }); thumbnails.forEach(function(value, key, listObj, argument) { listObj[key].setAttribute('style','height:' + tallestThumbnailSize + 'px'); });
Remove my personal domain from the public jirafs git config.
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IGNORE_FILE = '.jirafs_remote_ignore' GIT_IGNORE_FILE_PARTIAL = '.jirafs_ignore' GIT_IGNORE_FILE = '.jirafs/combined_ignore' GIT_EXCLUDE_FILE = '.jirafs/git/info/exclude' TICKET_OPERATION_LOG = 'operation.log' METADATA_DIR = '.jirafs' GLOBAL_CONFIG = '.jirafs_config' GIT_AUTHOR = 'Jirafs %s <jirafs@localhost>' % ( version ) # Config sections CONFIG_JIRA = 'jira' CONFIG_PLUGINS = 'plugins' NO_DETAIL_FIELDS = [ 'comment', 'watches', 'attachment' ] FILE_FIELDS = [ 'description', ] FILE_FIELD_BLACKLIST = [ 'new_comment', 'fields', 'links', ] CURRENT_REPO_VERSION = 16
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IGNORE_FILE = '.jirafs_remote_ignore' GIT_IGNORE_FILE_PARTIAL = '.jirafs_ignore' GIT_IGNORE_FILE = '.jirafs/combined_ignore' GIT_EXCLUDE_FILE = '.jirafs/git/info/exclude' TICKET_OPERATION_LOG = 'operation.log' METADATA_DIR = '.jirafs' GLOBAL_CONFIG = '.jirafs_config' GIT_AUTHOR = 'Jirafs %s <jirafs@adamcoddington.net>' % ( version ) # Config sections CONFIG_JIRA = 'jira' CONFIG_PLUGINS = 'plugins' NO_DETAIL_FIELDS = [ 'comment', 'watches', 'attachment' ] FILE_FIELDS = [ 'description', ] FILE_FIELD_BLACKLIST = [ 'new_comment', 'fields', 'links', ] CURRENT_REPO_VERSION = 16
Expand alternatives to import aio module
# Copyright 2019 The gRPC 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. import logging import unittest from tests_aio.unit._test_base import AioTestBase class TestInit(AioTestBase): async def test_grpc(self): import grpc # pylint: disable=wrong-import-position channel = grpc.aio.insecure_channel('dummy') self.assertIsInstance(channel, grpc.aio.Channel) async def test_grpc_dot_aio(self): import grpc.aio # pylint: disable=wrong-import-position channel = grpc.aio.insecure_channel('dummy') self.assertIsInstance(channel, grpc.aio.Channel) async def test_aio_from_grpc(self): from grpc import aio # pylint: disable=wrong-import-position channel = aio.insecure_channel('dummy') self.assertIsInstance(channel, aio.Channel) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) unittest.main(verbosity=2)
# Copyright 2019 The gRPC 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. import logging import unittest import grpc from tests_aio.unit._test_base import AioTestBase class TestInit(AioTestBase): async def test_grpc_dot_aio(self): channel = grpc.aio.insecure_channel('dummy') self.assertIsInstance(channel, grpc.aio.Channel) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) unittest.main(verbosity=2)
Use new user info endpoint.
<?php /** * @file * Northstar OpenID Connect client. */ class OpenIDConnectClientNorthstar extends OpenIDConnectClientBase { /** * Overrides OpenIDConnectClientBase::settingsForm(). */ public function settingsForm() { $form = parent::settingsForm(); // @TODO: Store public key here. return $form; } /** * Overrides OpenIDConnectClientBase::getEndpoints(). */ public function getEndpoints() { // @TODO: Build these from Northstar module settings. $url = 'http://northstar.dev:8000'; return [ 'authorization' => $url . '/authorize', 'token' => $url . '/v2/auth/token', 'userinfo' => $url . '/v2/auth/info', ]; } /** * Implements OpenIDConnectClientInterface::decodeIdToken(). */ public function decodeIdToken($id_token) { // @TODO: Verify JWT using public key. return parent::decodeIdToken($id_token); } /** * Overrides OpenIDConnectClientBase::retrieveUserInfo(). */ public function retrieveUserInfo($access_token) { $base = parent::retrieveUserInfo($access_token); if ($base) { return $base['data']; } return null; } }
<?php /** * @file * Northstar OpenID Connect client. */ class OpenIDConnectClientNorthstar extends OpenIDConnectClientBase { /** * Overrides OpenIDConnectClientBase::settingsForm(). */ public function settingsForm() { $form = parent::settingsForm(); // @TODO: Store public key here. return $form; } /** * Overrides OpenIDConnectClientBase::getEndpoints(). */ public function getEndpoints() { // @TODO: Build these from Northstar module settings. $url = 'http://northstar.dev:8000'; return [ 'authorization' => $url . '/authorize', 'token' => $url . '/v2/auth/token', 'userinfo' => $url . '/v1/profile', ]; } /** * Implements OpenIDConnectClientInterface::decodeIdToken(). */ public function decodeIdToken($id_token) { // @TODO: Verify JWT using public key. return parent::decodeIdToken($id_token); } /** * Overrides OpenIDConnectClientBase::retrieveUserInfo(). */ public function retrieveUserInfo($access_token) { $base = parent::retrieveUserInfo($access_token); if ($base) { return $base['data']; } return null; } }
[DG,LL] Add test to the test suite
package com.sw_ss16.lc_app.ui.tests; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import junit.framework.TestSuite; public class AllTests extends ActivityInstrumentationTestCase2<Activity> { public AllTests(Class<Activity> activityClass) { super(activityClass); } /** * Add test classes in order of execution here */ public static TestSuite suite() { TestSuite t = new TestSuite(); t.addTestSuite(ListActivityTest.class); t.addTestSuite(SettingsActivityTest.class); t.addTestSuite(StudyRoomDetailTest.class); return t; } /** * Individual test classes call these methods */ @Override public void setUp() throws Exception { } /** * Individual test classes call these methods */ @Override public void tearDown() throws Exception { } }
package com.sw_ss16.lc_app.ui.tests; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import junit.framework.TestSuite; public class AllTests extends ActivityInstrumentationTestCase2<Activity> { public AllTests(Class<Activity> activityClass) { super(activityClass); } /** * Add test classes in order of execution here */ public static TestSuite suite() { TestSuite t = new TestSuite(); t.addTestSuite(ListActivityTest.class); t.addTestSuite(SettingsActivityTest.class); return t; } /** * Individual test classes call these methods */ @Override public void setUp() throws Exception { } /** * Individual test classes call these methods */ @Override public void tearDown() throws Exception { } }
Add security on time filter to be sure this is an integer and not a float
(function(app){ "use strict" /** * Creates a filter to convert a time in milliseconds to * an hours:minutes:seconds format. * * e.g. * {{60000 | millisecondsToTime}} // 01:00 * {{3600000 | millisecondsToTime}} // 01:00:00 */ app.filter("millisecondsToTime", MillisecondsToTime); function MillisecondsToTime(){ return function(time){ if(time < 0 || isNaN(time)) return ""; time = parseInt(time); var seconds = parseInt((time / 1000) % 60); var minutes = parseInt((time / (60000)) % 60); var hours = parseInt((time / (3600000)) % 24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds; } }; })(angular.module("ov.player"));
(function(app){ "use strict" /** * Creates a filter to convert a time in milliseconds to * an hours:minutes:seconds format. * * e.g. * {{60000 | millisecondsToTime}} // 01:00 * {{3600000 | millisecondsToTime}} // 01:00:00 */ app.filter("millisecondsToTime", MillisecondsToTime); function MillisecondsToTime(){ return function(time){ if(time < 0 || isNaN(time)) return ""; var seconds = parseInt((time / 1000) % 60); var minutes = parseInt((time / (60000)) % 60); var hours = parseInt((time / (3600000)) % 24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds; } }; })(angular.module("ov.player"));
Use the correct dep "BitcoindNode"
'use strict'; var should = require('chai').should(); var bitcoinlib = require('../../'); var sinon = require('sinon'); var Chain = bitcoinlib.BitcoindNode.Chain; describe('Bitcoind Chain', function() { describe('#_writeBlock', function() { it('should update hashes and call putBlock', function(done) { var chain = new Chain(); chain.db = { putBlock: sinon.stub().callsArg(1) }; chain._writeBlock({hash: 'hash', prevHash: 'prevhash'}, function(err) { should.not.exist(err); chain.db.putBlock.callCount.should.equal(1); chain.cache.hashes.hash.should.equal('prevhash'); done(); }); }); }); describe('#_validateBlock', function() { it('should call the callback', function(done) { var chain = new Chain(); chain._validateBlock('block', function(err) { should.not.exist(err); done(); }); }); }); });
'use strict'; var should = require('chai').should(); var bitcoinlib = require('../../'); var sinon = require('sinon'); var Chain = bitcoinlib.RPCNode.Chain; describe('Bitcoind Chain', function() { describe('#_writeBlock', function() { it('should update hashes and call putBlock', function(done) { var chain = new Chain(); chain.db = { putBlock: sinon.stub().callsArg(1) }; chain._writeBlock({hash: 'hash', prevHash: 'prevhash'}, function(err) { should.not.exist(err); chain.db.putBlock.callCount.should.equal(1); chain.cache.hashes.hash.should.equal('prevhash'); done(); }); }); }); describe('#_validateBlock', function() { it('should call the callback', function(done) { var chain = new Chain(); chain._validateBlock('block', function(err) { should.not.exist(err); done(); }); }); }); });
Add test for current Str::words behavior with leading and trailing spaces.
<?php use Illuminate\Support\Str; class SupportStrTest extends PHPUnit_Framework_TestCase { /** * Test the Str::words method. * * @group laravel */ public function testStringCanBeLimitedByWords() { $this->assertEquals('Taylor...', Str::words('Taylor Otwell', 1)); $this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___')); $this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3)); } public function testBehaviorWithLeadingAndTrailingSpaces() { $this->assertEquals(' Taylor Otwell', Str::words(' Taylor Otwell ', 3)); $this->assertEquals(' Taylor...', Str::words(' Taylor Otwell ', 1)); } public function testStringWithoutWordsDoesntProduceError() { $nbsp = chr(0xC2).chr(0xA0); $this->assertEquals('', Str::words(' ')); $this->assertEquals('', Str::words($nbsp)); } public function testStringMacros() { Illuminate\Support\Str::macro(__CLASS__, function() { return 'foo'; }); $this->assertEquals('foo', Str::SupportStrTest()); } }
<?php use Illuminate\Support\Str; class SupportStrTest extends PHPUnit_Framework_TestCase { /** * Test the Str::words method. * * @group laravel */ public function testStringCanBeLimitedByWords() { $this->assertEquals('Taylor...', Str::words('Taylor Otwell', 1)); $this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___')); $this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3)); } public function testStringWithoutWordsDoesntProduceError() { $nbsp = chr(0xC2).chr(0xA0); $this->assertEquals('', Str::words(' ')); $this->assertEquals('', Str::words($nbsp)); } public function testStringMacros() { Illuminate\Support\Str::macro(__CLASS__, function() { return 'foo'; }); $this->assertEquals('foo', Str::SupportStrTest()); } }
:wrench: Tweak error handler to prevent undefined in URL
const fourOhFourHandler = require('./fourOhFourHandler'); /** * Handles compilation errors * like when a template or page does not exist * @param {object} req - Request object * @param {object} res - Response object * @param {String} type - Type of error * @param {String} [template] - Template that the error happened with */ function handleCompileErrorRoutes(req, res, type, template) { switch (type) { case 'no-html': case 'no-template': case 'no-homepage': { const obj = { r: type, p: req.originalUrl, }; if (template) obj.t = template; const queryString = Object.keys(obj).reduce((prev, curr, i) => { let queryParam = `${curr}=${obj[curr]}`; if (i !== 0) queryParam = `&${queryParam}`; return `${prev}${queryParam}`; }, ''); return res.redirect(`/admin/error?${queryString}`); } case 'no-exist': return fourOhFourHandler(req, res); default: return res.send(type); } } module.exports = handleCompileErrorRoutes;
const fourOhFourHandler = require('./fourOhFourHandler'); /** * Handles compilation errors * like when a template or page does not exist * @param {object} req - Request object * @param {object} res - Response object * @param {String} type - Type of error * @param {String} [template] - Template that the error happened with */ function handleCompileErrorRoutes(req, res, type, template) { switch (type) { case 'no-html': case 'no-template': case 'no-homepage': { const r = type; const p = req.originalUrl; const t = template; return res.redirect(`/admin/error?r=${r}&p=${p}&t=${t}`); } case 'no-exist': return fourOhFourHandler(req, res); default: return res.send(type); } } module.exports = handleCompileErrorRoutes;
Update tests to use Translate
import { mount } from 'enzyme'; import assert from 'assert'; import counterpart from 'counterpart'; import React from 'react'; import Summary from './summary'; import { workflow } from '../../../pages/dev-classifier/mock-data'; import enLocale from '../../../locales/en'; counterpart.registerTranslations('en', enLocale); const annotation = { value: [{ "choice": "ar", "answers": { "ho": "two", "be": [ "mo", "ea" ] }, "filters": {} }] }; const task = workflow.tasks.survey const expectedSummary = 'Armadillo: 2; Moving, Eating'; describe('Survey task summary, not expanded', function() { const wrapper = mount(<Summary annotation={annotation} task={task} />); const answers = wrapper.find('.answers .answer'); it('should show one answer node', function(){ assert.equal(answers.length, 1); }); it('should summarise the number of identifications', function() { assert.equal(answers.text(), '1 identification'); }); }); describe('Survey task summary, expanded', function() { const wrapper = mount(<Summary annotation={annotation} task={task} expanded={true} />); const answers = wrapper.find('.answers .answer'); it('should show two answer nodes', function(){ assert.equal(answers.length, 2); }); it('should summarise the identification and questions', function() { assert.equal(answers.last().text(), expectedSummary); }); })
import { shallow } from 'enzyme'; import assert from 'assert'; import React from 'react'; import Summary from './summary'; import { workflow } from '../../../pages/dev-classifier/mock-data'; const annotation = { value: [{ "choice": "ar", "answers": { "ho": "two", "be": [ "mo", "ea" ] }, "filters": {} }] }; const task = workflow.tasks.survey const expectedSummary = 'Armadillo: 2; Moving, Eating'; describe('Survey task summary, not expanded', function() { const wrapper = shallow(<Summary annotation={annotation} task={task} />); const answers = wrapper.find('.answers .answer'); it('should show one answer node', function(){ assert.equal(answers.length, 1); }); it('should summarise the number of identifications', function() { assert.equal(answers.text(), '1 identifications'); }); }); describe('Survey task summary, expanded', function() { const wrapper = shallow(<Summary annotation={annotation} task={task} expanded={true} />); const answers = wrapper.find('.answers .answer'); it('should show two answer nodes', function(){ assert.equal(answers.length, 2); }); it('should summarise the identification and questions', function() { assert.equal(answers.last().text(), expectedSummary); }); })
Move the closing parenthesis to the next line
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) from libqtile.bar import CALCULATED from libqtile.widget import TextBox from powerline import Powerline class QTilePowerline(Powerline): def do_setup(self, obj): obj.powerline = self class PowerlineTextBox(TextBox): def __init__(self, timeout=2, text=' ', width=CALCULATED, **config): super(PowerlineTextBox, self).__init__(text, width, **config) self.timeout_add(timeout, self.update) powerline = QTilePowerline(ext='wm', renderer_module='pango_markup') powerline.setup(self) def update(self): if not self.configured: return True self.text = self.powerline.render(side='right') self.bar.draw() return True def cmd_update(self, text): self.update(text) def cmd_get(self): return self.text def _configure(self, qtile, bar): super(PowerlineTextBox, self)._configure(qtile, bar) self.layout = self.drawer.textlayout( self.text, self.foreground, self.font, self.fontsize, self.fontshadow, markup=True, ) # TODO: Remove this at next major release Powerline = PowerlineTextBox
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) from libqtile.bar import CALCULATED from libqtile.widget import TextBox from powerline import Powerline class QTilePowerline(Powerline): def do_setup(self, obj): obj.powerline = self class PowerlineTextBox(TextBox): def __init__(self, timeout=2, text=' ', width=CALCULATED, **config): super(PowerlineTextBox, self).__init__(text, width, **config) self.timeout_add(timeout, self.update) powerline = QTilePowerline(ext='wm', renderer_module='pango_markup') powerline.setup(self) def update(self): if not self.configured: return True self.text = self.powerline.render(side='right') self.bar.draw() return True def cmd_update(self, text): self.update(text) def cmd_get(self): return self.text def _configure(self, qtile, bar): super(PowerlineTextBox, self)._configure(qtile, bar) self.layout = self.drawer.textlayout( self.text, self.foreground, self.font, self.fontsize, self.fontshadow, markup=True) # TODO: Remove this at next major release Powerline = PowerlineTextBox
Improve error handling and fix dopey close() placement
// asmjsunpack-worker.js: this file is concatenated at the end of unpack.js. // This file implements a worker that responds to a single initial message containing a url to // fetch and unpack and the name of the callback to pass into decoding. The worker responds by // transfering an Int8Array view of the decoded utf8 chars. onmessage = function(e) { var url = e.data.url; var callbackName = e.data.callbackName; var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = 'arraybuffer'; xhr.onerror = function (e) { postMessage('Loading ' + url + ' failed'); } xhr.onload = function (e) { if (xhr.status !== 200) { postMessage("failed to download " + url + " with status: " + xhr.statusText); } else { try { var bef = Date.now(); var utf8 = unpack(xhr.response, callbackName); var aft = Date.now(); console.log("unpack of " + url + " took " + (aft - bef) + "ms"); postMessage(new Blob([utf8])); } catch (e) { postMessage("failed to unpack " + url + ": " + e); } } self.close(); } xhr.send(null); }
// asmjsunpack-worker.js: this file is concatenated at the end of unpack.js. // This file implements a worker that responds to a single initial message containing a url to // fetch and unpack and the name of the callback to pass into decoding. The worker responds by // transfering an Int8Array view of the decoded utf8 chars. onmessage = function(e) { var url = e.data.url; var callbackName = e.data.callbackName; var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = 'arraybuffer'; xhr.onerror = function (e) { postMessage('Loading ' + url + ' failed'); } xhr.onload = function (e) { try { var bef = Date.now(); var utf8 = unpack(xhr.response, callbackName); var aft = Date.now(); console.log("Unpack of " + url + " took " + (aft - bef) + "ms"); postMessage(new Blob([utf8])); } catch (e) { postMessage("Failed to unpack " + url + " in worker: " + e); } } xhr.send(null); close(); }
Add back in running of extra tests
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', extra_tests) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', ) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
Add heading structure to tracking script for clarity
$(document).ready(function() { // check if the Google Analytics function is available if (typeof ga == 'function') { // Following function trackFollow() { ga('send', 'event', 'Following', 'click Follow button'); }; function trackUnsubscribe() { ga('send', 'event', 'Following', 'click Unsubscribe button'); }; $('.track-request-action').click(function(e) { trackFollow(); }); $('.track__action').click(function(e) { trackFollow(); }); $('.unsubscribe__action').click(function(e) { trackUnsubscribe() }); $('.unsubscribe-request-action').click(function(e) { trackUnsubscribe() }); // Request for personal information question $("#request_personal_switch_yes").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click Yes'); }); $("#request_personal_switch_no").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click No'); }); $(".request_personal_message .request_email a").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click Authority email address'); }); } })
$(document).ready(function() { // check if the Google Analytics function is available if (typeof ga == 'function') { function trackFollow() { ga('send', 'event', 'Following', 'click Follow button'); }; function trackUnsubscribe() { ga('send', 'event', 'Following', 'click Unsubscribe button'); }; $('.track-request-action').click(function(e) { trackFollow(); }); $('.track__action').click(function(e) { trackFollow(); }); $('.unsubscribe__action').click(function(e) { trackUnsubscribe() }); $('.unsubscribe-request-action').click(function(e) { trackUnsubscribe() }); $("#request_personal_switch_yes").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click Yes'); }); $("#request_personal_switch_no").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click No'); }); $(".request_personal_message .request_email a").click(function(e) { ga('send', 'event', 'Request for personal information question', 'click Authority email address'); }); } })
test: Fix test to reflect new API changes
# archivebox init # archivebox add import os import subprocess from pathlib import Path import json from .fixtures import * def test_init(tmp_path, process): assert "Initializing a new ArchiveBox collection in this folder..." in process.stdout.decode("utf-8") def test_update(tmp_path, process): os.chdir(tmp_path) update_process = subprocess.run(['archivebox', 'init'], capture_output=True) assert "Updating existing ArchiveBox collection in this folder" in update_process.stdout.decode("utf-8") def test_add_link(tmp_path, process): os.chdir(tmp_path) add_process = subprocess.run(['archivebox', 'add', 'http://example.com'], capture_output=True) archived_item_path = list(tmp_path.glob('archive/**/*'))[0] assert "index.json" in [x.name for x in archived_item_path.iterdir()] with open(archived_item_path / "index.json", "r") as f: output_json = json.load(f) assert "Example Domain" == output_json['history']['title'][0]['output'] with open(tmp_path / "index.html", "r") as f: output_html = f.read() assert "Example Domain" in output_html
# archivebox init # archivebox add import os import subprocess from pathlib import Path import json from .fixtures import * def test_init(tmp_path, process): assert "Initializing a new ArchiveBox collection in this folder..." in process.stdout.decode("utf-8") def test_update(tmp_path, process): os.chdir(tmp_path) update_process = subprocess.run(['archivebox', 'init'], capture_output=True) assert "Updating existing ArchiveBox collection in this folder" in update_process.stdout.decode("utf-8") def test_add_link(tmp_path, process): os.chdir(tmp_path) add_process = subprocess.run(['archivebox', 'add', 'http://example.com'], capture_output=True) archived_item_path = list(tmp_path.glob('archive/**/*'))[0] assert "index.json" in [x.name for x in archived_item_path.iterdir()] with open(archived_item_path / "index.json", "r") as f: output_json = json.load(f) assert "IANA — IANA-managed Reserved Domains" == output_json['history']['title'][0]['output'] with open(tmp_path / "index.html", "r") as f: output_html = f.read() assert "IANA — IANA-managed Reserved Domains" in output_html
Convert UnicodeDictReader to an iterator class, so that EmptyCSVError will get thrown on instantiation, rather than on iteration.
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support class EmptyCSVError(Exception): pass def UnicodeDictReader(file_or_str, encoding='utf8', **kwargs): import csv def decode(s, encoding): if s is None: return None return s.decode(encoding) csv_reader = csv.DictReader(file_or_str, **kwargs) if not csv_reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") keymap = dict((k, k.decode(encoding)) for k in csv_reader.fieldnames) for row in csv_reader: yield dict((keymap[k], decode(v, encoding)) for k, v in row.iteritems())
Fix the dependencies of set os unit tests
'use strict'; module.exports = { assets: { lib: { css: [ 'lib/bootstrap/dist/css/bootstrap.css', 'lib/bootstrap/dist/css/bootstrap-theme.css', 'lib/font-awesome/css/font-awesome.css' ], js: [ 'lib/angular/angular.js', 'lib/angular-resource/angular-resource.js', 'lib/angular-cookies/angular-cookies.js', 'lib/angular-animate/angular-animate.js', 'lib/angular-touch/angular-touch.js', 'lib/angular-sanitize/angular-sanitize.js', 'lib/angular-ui-router/release/angular-ui-router.js', 'lib/angular-ui-utils/ui-utils.js', 'lib/angular-bootstrap/ui-bootstrap-tpls.js', 'lib/angular-breadcrumb/release/angular-breadcrumb.js', 'lib/angular-xeditable/dist/js/xeditable.js' ] }, css: [ 'modules/**/css/*.css', 'dashboard.css' ], js: [ 'config.js', 'application.js', 'modules/*/*.js', 'modules/*/*[!tests]*/*.js' ], tests: [ 'lib/angular-mocks/angular-mocks.js', 'modules/*/tests/*.js' ] } };
'use strict'; module.exports = { assets: { lib: { css: [ 'lib/bootstrap/dist/css/bootstrap.css', 'lib/bootstrap/dist/css/bootstrap-theme.css', 'lib/font-awesome/css/font-awesome.css' ], js: [ 'lib/angular/angular.js', 'lib/angular-resource/angular-resource.js', 'lib/angular-cookies/angular-cookies.js', 'lib/angular-animate/angular-animate.js', 'lib/angular-touch/angular-touch.js', 'lib/angular-sanitize/angular-sanitize.js', 'lib/angular-ui-router/release/angular-ui-router.js', 'lib/angular-ui-utils/ui-utils.js', 'lib/angular-bootstrap/ui-bootstrap-tpls.js', 'lib/angular-breadcrumb/release/angular-breadcrumb.js' ] }, css: [ 'modules/**/css/*.css', 'dashboard.css' ], js: [ 'config.js', 'application.js', 'modules/*/*.js', 'modules/*/*[!tests]*/*.js' ], tests: [ 'lib/angular-mocks/angular-mocks.js', 'modules/*/tests/*.js' ] } };
Remove redundant flag from flake8 task The max line length is already specified in Flake8's configuration.
import os import sys from invoke import task, util in_ci = os.environ.get("CI", "false") == "true" if in_ci: pty = False else: pty = util.isatty(sys.stdout) and util.isatty(sys.stderr) @task def reformat(c): c.run("isort mopidy_webhooks tests setup.py tasks.py", pty=pty) c.run("black mopidy_webhooks tests setup.py tasks.py", pty=pty) @task def lint(c): c.run( "flake8 --show-source --statistics mopidy_webhooks tests", pty=pty, ) c.run("check-manifest", pty=pty) @task def test(c, onefile=""): pytest_args = [ "pytest", "--strict-config", "--cov=mopidy_webhooks", "--cov-report=term-missing", ] if in_ci: pytest_args.extend(("--cov-report=xml", "--strict-markers")) else: pytest_args.append("--cov-report=html") if onefile: pytest_args.append(onefile) c.run(" ".join(pytest_args), pty=pty) @task def type_check(c): c.run("mypy mopidy_webhooks tests", pty=pty)
import os import sys from invoke import task, util in_ci = os.environ.get("CI", "false") == "true" if in_ci: pty = False else: pty = util.isatty(sys.stdout) and util.isatty(sys.stderr) @task def reformat(c): c.run("isort mopidy_webhooks tests setup.py tasks.py", pty=pty) c.run("black mopidy_webhooks tests setup.py tasks.py", pty=pty) @task def lint(c): c.run( "flake8 --show-source --statistics --max-line-length 100 mopidy_webhooks tests", pty=pty, ) c.run("check-manifest", pty=pty) @task def test(c, onefile=""): pytest_args = [ "pytest", "--strict-config", "--cov=mopidy_webhooks", "--cov-report=term-missing", ] if in_ci: pytest_args.extend(("--cov-report=xml", "--strict-markers")) else: pytest_args.append("--cov-report=html") if onefile: pytest_args.append(onefile) c.run(" ".join(pytest_args), pty=pty) @task def type_check(c): c.run("mypy mopidy_webhooks tests", pty=pty)
Enable Enterprise edition features for modePortal (SAAS-1370)
'use strict'; angular.module('ncsaas') .constant('MODE', { modeName: 'modePortal', toBeFeatures: [ 'localSignup', 'localSignin', 'password', 'people', 'compare', 'backups', 'templates', 'sizing', 'projectGroups', 'apps', 'premiumSupport' ], featuresVisible: false, appStoreCategories: [ { name: 'VMs', type: 'provider', icon: 'desktop', services: ['Amazon', 'DigitalOcean', 'OpenStack'] } ], serviceCategories: [ { name: 'Virtual machines', services: ['Amazon', 'DigitalOcean', 'OpenStack'], } ], futureCategories: [ { name: 'Private clouds', icon: 'cloud' }, { name: 'Applications', icon: 'database' }, { name: 'Support', icon: 'wrench' } ] });
'use strict'; angular.module('ncsaas') .constant('MODE', { modeName: 'modePortal', toBeFeatures: [ 'localSignup', 'localSignin', 'password', 'team', 'people', 'payment', 'compare', 'monitoring', 'backups', 'templates', 'sizing', 'projectGroups', 'apps', 'private_clouds', 'premiumSupport' ], featuresVisible: false, appStoreCategories: [ { name: 'VMs', type: 'provider', icon: 'desktop', services: ['Amazon', 'DigitalOcean', 'OpenStack'] } ], serviceCategories: [ { name: 'Virtual machines', services: ['Amazon', 'DigitalOcean', 'OpenStack'], } ], futureCategories: [ { name: 'Private clouds', icon: 'cloud' }, { name: 'Applications', icon: 'database' }, { name: 'Support', icon: 'wrench' } ] });
Correct variable name to maxValues
const isDate = (key) => key === "date"; module.exports = function (initialData, fields, maxValues) { if (initialData.length > maxValues) { initialData = initialData.slice(initialData.length - maxValues); } var columnData = { 'date': [] }; fields.forEach(f => columnData[f] = []); initialData.forEach((value) => { for (let key of Object.keys(value)) { if (!columnData[key]) continue; columnData[key].push(isDate(key) ? new Date(value[key]) : value[key]); } }); var columns = []; for (let key of Object.keys(columnData)) { if (isDate(key)) { columns.push(['x'].concat(columnData[key])); } else columns.push([key].concat(columnData[key])); } return columns; };
const isDate = (key) => key === "date"; module.exports = function (initialData, fields, maxValues) { if (initialData.length > maxValues) { initialData = initialData.slice(initialData.length - this.limit); } var columnData = { 'date': [] }; fields.forEach(f => columnData[f] = []); initialData.forEach((value) => { for (let key of Object.keys(value)) { if (!columnData[key]) continue; columnData[key].push(isDate(key) ? new Date(value[key]) : value[key]); } }); var columns = []; for (let key of Object.keys(columnData)) { if (isDate(key)) { columns.push(['x'].concat(columnData[key])); } else columns.push([key].concat(columnData[key])); } return columns; };
Update new task dialog size after selecting a plugin
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog; import org.eclipse.swt.widgets.Shell; import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration; public class NewTaskDialogShell extends Shell { private static final long serialVersionUID = -4970825745896119968L; NewTaskDialog newTaskDialog; private RumPluginConfiguration rumPluginConfiguration; public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) { super(parent, style); this.newTaskDialog=newTaskDialog; } public RumPluginConfiguration getRumPluginConfiguration() { return rumPluginConfiguration; } public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) { this.pack(); this.rumPluginConfiguration = rumPluginConfiguration; } public NewTaskDialog getNewTaskDialog() { return newTaskDialog; } }
package ee.ut.cs.rum.workspaces.internal.ui.task.newtask.dialog; import org.eclipse.swt.widgets.Shell; import ee.ut.cs.rum.plugins.interfaces.factory.RumPluginConfiguration; public class NewTaskDialogShell extends Shell { private static final long serialVersionUID = -4970825745896119968L; NewTaskDialog newTaskDialog; private RumPluginConfiguration rumPluginConfiguration; public NewTaskDialogShell(Shell parent, int style, NewTaskDialog newTaskDialog) { super(parent, style); this.newTaskDialog=newTaskDialog; } public RumPluginConfiguration getRumPluginConfiguration() { return rumPluginConfiguration; } public void setRumPluginConfiguration(RumPluginConfiguration rumPluginConfiguration) { this.rumPluginConfiguration = rumPluginConfiguration; } public NewTaskDialog getNewTaskDialog() { return newTaskDialog; } }
Add missing translation (in users admin page).
<?php $TRANSLATIONS = array( "If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.", "Version of %s:" => "Version de %s :", "Change log" => "Change log", "GTU" => "CGU", "Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?", "User suppression" => "Suppression d'un utilisateur", "Help translate My CoRe" => "Aidez à traduire My CoRe", "Help translate ownCloud" => "Aidez à traduire ownCloud", "Connectivity Checks" => "Vérifications des connections", "No problems found" => "Aucun problème trouvé", "Please double check the <a href=\'%s\'>installation guides</a>." => "Merci de bien vérifier les <a href=\'%s\'>guides d'installation</a>.", "Paid client app" => "Client payant", "Free client app" => "Client gratuit", "Show storage location" => "Emplacement du stockage", "Show last log in" => "Dernière connexion", ); $PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
<?php $TRANSLATIONS = array( "If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.", "Version of %s:" => "Version de %s :", "Change log" => "Change log", "GTU" => "CGU", "Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?", "User suppression" => "Suppression d'un utilisateur", "Help translate My CoRe" => "Aidez à traduire My CoRe", "Help translate ownCloud" => "Aidez à traduire ownCloud", "Connectivity Checks" => "Vérifications des connections", "No problems found" => "Aucun problème trouvé", "Please double check the <a href=\'%s\'>installation guides</a>." => "Merci de bien vérifier les <a href=\'%s\'>guides d'installation</a>.", "Paid client app" => "Client payant", "Free client app" => "Client gratuit", ); $PLURAL_FORMS = "nplurals=2; plural=(n > 1);";