text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add martserver-linkeddata-1:8081 to default target servers
//the list of servers we can access const serverPaths = [ 'http://malmo.lizenn.net:8080', 'http://localhost:8080', 'http://localhost:8081', 'http://malmo.lizenn.net:8082', 'http://martserver-linkeddata-1:8081' ] //the adress used internally in the application to proxy const proxyURL = '/proxiedOCCIServer'; //the adress of the initial backend Server const backendURL = serverPaths[0]; //the prefix to append to categories queries const backendCategoriesPrefix_erocci = '/categories/'; const backendCategoriesPrefix_mart = '/'; const initialState = { currentPath: '/-/', currentJson: {}, errorMessage: { simple: '', detailed: '' }, okMessage: '', currentURLServer: backendURL, // readings (toolified), or write (edit) codeRights: 'read', schemes: {schemeName: [{title: '', term: ''}]} }; //this const will be changed when deploying on standalone. Must be false by default const integratedVersion = false; module.exports = {initialState: initialState, proxyURL: proxyURL, backendURL: backendURL, serverPaths: serverPaths, integratedVersion: integratedVersion, backendCategoriesPrefix_erocci: backendCategoriesPrefix_erocci, backendCategoriesPrefix_mart: backendCategoriesPrefix_mart};
//the list of servers we can access const serverPaths = [ 'http://malmo.lizenn.net:8080', 'http://localhost:8080', 'http://localhost:8081', 'http://malmo.lizenn.net:8082', ] //the adress used internally in the application to proxy const proxyURL = '/proxiedOCCIServer'; //the adress of the initial backend Server const backendURL = serverPaths[0]; //the prefix to append to categories queries const backendCategoriesPrefix_erocci = '/categories/'; const backendCategoriesPrefix_mart = '/'; const initialState = { currentPath: '/-/', currentJson: {}, errorMessage: { simple: '', detailed: '' }, okMessage: '', currentURLServer: backendURL, // readings (toolified), or write (edit) codeRights: 'read', schemes: {schemeName: [{title: '', term: ''}]} }; //this const will be changed when deploying on standalone. Must be false by default const integratedVersion = false; module.exports = {initialState: initialState, proxyURL: proxyURL, backendURL: backendURL, serverPaths: serverPaths, integratedVersion: integratedVersion, backendCategoriesPrefix_erocci: backendCategoriesPrefix_erocci, backendCategoriesPrefix_mart: backendCategoriesPrefix_mart};
Use paths instead of toString
package me.deftware.mixin.mixins.item; import me.deftware.client.framework.registry.ItemRegistry; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Items.class) public class MixinItems { @Inject(method = "register(Lnet/minecraft/util/Identifier;Lnet/minecraft/item/Item;)Lnet/minecraft/item/Item;", at = @At("TAIL")) private static void register(Identifier id, Item item, CallbackInfoReturnable<Item> ci) { ItemRegistry.INSTANCE.register(id.getPath(), item); } }
package me.deftware.mixin.mixins.item; import me.deftware.client.framework.registry.ItemRegistry; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Items.class) public class MixinItems { @Inject(method = "register(Lnet/minecraft/util/Identifier;Lnet/minecraft/item/Item;)Lnet/minecraft/item/Item;", at = @At("TAIL")) private static void register(Identifier id, Item item, CallbackInfoReturnable<Item> ci) { ItemRegistry.INSTANCE.register(id.toString(), item); } }
Fix Invoke doc intersphinx path (and tweak formatting)
# Obtain shared config values import os, sys from os.path import abspath, join, dirname sys.path.append(abspath(join(dirname(__file__), '..'))) sys.path.append(abspath(join(dirname(__file__), '..', '..'))) from shared_conf import * # Enable autodoc, intersphinx extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']) # Autodoc settings autodoc_default_flags = ['members', 'special-members'] # Default is 'local' building, but reference the public WWW site when building # under RTD. target = join(dirname(__file__), '..', 'www', '_build') if os.environ.get('READTHEDOCS') == 'True': target = 'http://www.fabfile.org/' www = (target, None) # Ditto Invoke target = join( dirname(__file__), '..', '..', '..', 'invoke', 'sites', 'docs', '_build' ) if os.environ.get('READTHEDOCS') == 'True': target = 'http://docs.pyinvoke.org/' invoke = (target, None) # Intersphinx connection to stdlib + www site intersphinx_mapping = { 'python': ('http://docs.python.org/2.6', None), 'www': www, 'invoke': invoke, } # Sister-site links to WWW html_theme_options['extra_nav_links'] = { "Main website": 'http://www.fabfile.org', }
# Obtain shared config values import os, sys from os.path import abspath, join, dirname sys.path.append(abspath(join(dirname(__file__), '..'))) sys.path.append(abspath(join(dirname(__file__), '..', '..'))) from shared_conf import * # Enable autodoc, intersphinx extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']) # Autodoc settings autodoc_default_flags = ['members', 'special-members'] # Default is 'local' building, but reference the public WWW site when building # under RTD. target = join(dirname(__file__), '..', 'www', '_build') if os.environ.get('READTHEDOCS') == 'True': target = 'http://www.fabfile.org/' www = (target, None) # Ditto Invoke target = join(dirname(__file__), '..', '..', '..', 'invoke', 'docs', '_build') if os.environ.get('READTHEDOCS') == 'True': target = 'http://docs.pyinvoke.org/' invoke = (target, None) # Intersphinx connection to stdlib + www site intersphinx_mapping = { 'python': ('http://docs.python.org/2.6', None), 'www': www, 'invoke': invoke, } # Sister-site links to WWW html_theme_options['extra_nav_links'] = { "Main website": 'http://www.fabfile.org', }
Add test for commented out media rule
import { ruleTester, warningFreeBasics, } from "../../../testUtils" import rule, { ruleName, messages } from ".." const testRule = ruleTester(rule, ruleName) testRule(undefined, tr => { warningFreeBasics(tr) tr.ok("a { /* color: pink; */ }", "regular comment around declaration") tr.ok("/* a { color: pink; } */", "regular comment around rule") tr.ok("a { background: url(//foo.com/bar.png) }", "url with double slash") tr.notOk( "a { // color: pink; }", { message: messages.rejected, line: 1, column: 8, }, "before declaration" ) tr.notOk( "// a { color: pink; }", { message: messages.rejected, line: 1, column: 19, }, "before rule" ) tr.notOk( "a, // div { color: pink; }", { message: messages.rejected, line: 1, column: 19, }, "between rules" ) tr.notOk( "// @media { }", { message: messages.rejected, line: 1, column: 19, }, "before media rule" ) })
import { ruleTester, warningFreeBasics, } from "../../../testUtils" import rule, { ruleName, messages } from ".." const testRule = ruleTester(rule, ruleName) testRule(undefined, tr => { warningFreeBasics(tr) tr.ok("a { /* color: pink; */ }", "regular comment around declaration") tr.ok("/* a { color: pink; } */", "regular comment around rule") tr.ok("a { background: url(//foo.com/bar.png) }", "url with double slash") tr.notOk( "a { // color: pink; }", { message: messages.rejected, line: 1, column: 8, }, "before declaration" ) tr.notOk( "// a { color: pink; }", { message: messages.rejected, line: 1, column: 19, }, "before rule" ) tr.notOk( "a, // div { color: pink; }", { message: messages.rejected, line: 1, column: 19, }, "between rules" ) })
Add router to the behaviors lookup
import ioflo.app.run import os class Manager(object): ''' Manage the main ioflo process ''' def __init__(self): self.behaviors = ['rflo.config', 'rflo.roads', 'rflo.router'] self.floscript = os.path.join(os.path.dirname(__file__), 'raft.flo') def start(self): ioflo.app.run.start( name='rflo', period=0.01, stamp=0.0, filepath=self.floscript, behaviors=self.behaviors, verbose=2, )
import ioflo.app.run import os class Manager(object): ''' Manage the main ioflo process ''' def __init__(self): self.behaviors = ['rflo.config', 'rflo.roads'] self.floscript = os.path.join(os.path.dirname(__file__), 'raft.flo') def start(self): ioflo.app.run.start( name='rflo', period=0.01, stamp=0.0, filepath=self.floscript, behaviors=self.behaviors, verbose=2, )
:sparkles: Build script + lots of fixes - Add a build script that build a minizied presentation with all dependencies - Remove node-emojis dependency - Remove cross-spawn dependency - Refactor: Use lib directly instead of calling scripts from scripts. This way we can just use `execa`.
import React from 'react'; // For a complete API docs see https://github.com/FormidableLabs/spectacle#tag-api import { Slide, Appear, Layout, Fill, Fit, Heading, Text, Link, S, Markdown, List, ListItem, Table, TableItem, TableHeaderItem, TableRow, BlockQuote, Quote, Cite, Code, CodePane, Image } from 'spectacle'; import render, { Presentation } from 'melodrama'; // --- THEME --- // Import and create the theme you want to use. import createTheme from 'spectacle/lib/themes/default'; const theme = createTheme({}); // --- SYNTAX HIGHLIGHTING --- // import 'prismjs/components/prism-core'; // import 'prismjs/components/prism-clike'; // import 'prismjs/components/javascript'; // --- IMAGES --- // Import/require your images and add them to `images` // for easy access and preloading. const images = {}; // --- PRESENTATION --- const Root = () => ( <Presentation theme={theme}> <Slide> <Heading>Title</Heading> </Slide> </Presentation> ); render(Root, { images });
import React from 'react'; /** * For a complete API document please * refer to https://github.com/FormidableLabs/spectacle#tag-api */ import { Slide, Appear, Layout, Fill, Fit, Heading, Text, Link, S, Markdown, List, ListItem, Table, TableItem, TableHeaderItem, TableRow, BlockQuote, Quote, Cite, Code, CodePane, Image } from 'spectacle'; import render, { Presentation } from 'melodrama'; /** * Import and create the theme you want to use. */ import createTheme from 'spectacle/lib/themes/default'; const theme = createTheme({}); /** * Import/require your images and add them to `images` * for easy access and preloading. */ const images = {}; /** * Add your slides! :-) */ const Root = () => ( <Presentation theme={theme}> <Slide> <Heading>Title</Heading> </Slide> </Presentation> ); render(Root, { images });
Fix cmd test to check for tmp directory [#133220399] Signed-off-by: Kevin Kelani <efa91e710b9557b327e9f2a4990d2dbb61dce345@pivotal.io>
package terraform_test import ( "bytes" "github.com/cloudfoundry/bosh-bootloader/terraform" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cmd", func() { var ( stdout *bytes.Buffer stderr *bytes.Buffer cmd terraform.Cmd ) BeforeEach(func() { stdout = bytes.NewBuffer([]byte{}) stderr = bytes.NewBuffer([]byte{}) cmd = terraform.NewCmd(stdout, stderr) }) It("runs terraform with args", func() { err := cmd.Run("/tmp", []string{"apply", "some-arg"}) Expect(err).NotTo(HaveOccurred()) Expect(stdout).To(MatchRegexp("working directory: (.*)/tmp")) Expect(stdout).To(ContainSubstring("apply some-arg")) }) Context("failure case", func() { It("returns an error when terraform fails", func() { err := cmd.Run("", []string{"fast-fail"}) Expect(err).To(MatchError("exit status 1")) Expect(stderr).To(ContainSubstring("failed to terraform")) }) }) })
package terraform_test import ( "bytes" "github.com/cloudfoundry/bosh-bootloader/terraform" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cmd", func() { var ( stdout *bytes.Buffer stderr *bytes.Buffer cmd terraform.Cmd ) BeforeEach(func() { stdout = bytes.NewBuffer([]byte{}) stderr = bytes.NewBuffer([]byte{}) cmd = terraform.NewCmd(stdout, stderr) }) It("runs terraform with args", func() { err := cmd.Run("/tmp", []string{"apply", "some-arg"}) Expect(err).NotTo(HaveOccurred()) Expect(stdout).To(ContainSubstring("working directory: /private/tmp")) Expect(stdout).To(ContainSubstring("apply some-arg")) }) Context("failure case", func() { It("returns an error when terraform fails", func() { err := cmd.Run("", []string{"fast-fail"}) Expect(err).To(MatchError("exit status 1")) Expect(stderr).To(ContainSubstring("failed to terraform")) }) }) })
Fix karma tests in windows
var path = require('path'); var transformTools = require('browserify-transform-tools'); var constants = require('./constants'); var pathToStrictD3Module = path.join( constants.pathToImageTest, 'strict-d3.js' ); /** * Transform `require('d3')` expressions to `require(/path/to/strict-d3.js)` */ module.exports = transformTools.makeRequireTransform('requireTransform', { evaluateArguments: true, jsFilesOnly: true }, function(args, opts, cb) { var pathIn = args[0]; var pathOut; if(pathIn === 'd3' && opts.file !== pathToStrictD3Module) { pathOut = 'require(' + JSON.stringify(pathToStrictD3Module) + ')'; } if(pathOut) return cb(null, pathOut); else return cb(); });
var path = require('path'); var transformTools = require('browserify-transform-tools'); var constants = require('./constants'); var pathToStrictD3Module = path.join( constants.pathToImageTest, 'strict-d3.js' ); /** * Transform `require('d3')` expressions to `require(/path/to/strict-d3.js)` */ module.exports = transformTools.makeRequireTransform('requireTransform', { evaluateArguments: true, jsFilesOnly: true }, function(args, opts, cb) { var pathIn = args[0]; var pathOut; if(pathIn === 'd3' && opts.file !== pathToStrictD3Module) { pathOut = 'require(\'' + pathToStrictD3Module + '\')'; } if(pathOut) return cb(null, pathOut); else return cb(); });
Improve the method name testStatus to testStatusCode
<?php namespace Zap\Test; class Zapv2Test extends \PHPUnit_Framework_TestCase{ public function setUp() { parent::setUp(); $this->proxy = "tcp://localhost:8090"; $this->target_url = "https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project"; } /** * @test */ public function testVersion() { $zap = new \Zap\Zapv2($this->proxy); $version = @$zap->core->version(); $this->assertSame("2.3.1", $version); } /** * @test */ public function testStatusCode() { $zap = new \Zap\Zapv2($this->proxy); $res = $zap->statusCode($this->target_url); $this->assertSame("200", $res); } }
<?php namespace Zap\Test; class Zapv2Test extends \PHPUnit_Framework_TestCase{ public function setUp() { parent::setUp(); $this->proxy = "tcp://localhost:8090"; $this->target_url = "https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project"; } /** * @test */ public function testVersion() { $zap = new \Zap\Zapv2($this->proxy); $version = @$zap->core->version(); $this->assertSame("2.3.1", $version); } /** * @test */ public function testStatus() { $zap = new \Zap\Zapv2($this->proxy); $res = $zap->statusCode($this->target_url); $this->assertSame("200", $res); } }
[FrameworkBundle] Fix ClassCacheWarme when classes.php is already warmed
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Symfony\Component\ClassLoader\ClassCollectionLoader; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; /** * Generates the Class Cache (classes.php) file. * * @author Tugdual Saunier <tucksaun@gmail.com> */ class ClassCacheCacheWarmer implements CacheWarmerInterface { /** * Warms up the cache. * * @param string $cacheDir The cache directory */ public function warmUp($cacheDir) { $classmap = $cacheDir.'/classes.map'; if (!is_file($classmap)) { return; } if (file_exists($cacheDir.'/classes.php')) { return; } ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false); } /** * Checks whether this warmer is optional or not. * * @return bool always true */ public function isOptional() { return true; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Symfony\Component\ClassLoader\ClassCollectionLoader; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; /** * Generates the Class Cache (classes.php) file. * * @author Tugdual Saunier <tucksaun@gmail.com> */ class ClassCacheCacheWarmer implements CacheWarmerInterface { /** * Warms up the cache. * * @param string $cacheDir The cache directory */ public function warmUp($cacheDir) { $classmap = $cacheDir.'/classes.map'; if (!is_file($classmap)) { return; } ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false); } /** * Checks whether this warmer is optional or not. * * @return bool always true */ public function isOptional() { return true; } }
Switch empty value to empty string rather than None When None is used this is rendered in the HTML as a string, which then when it is returned to the CKAN server becomes 'None' not None. An empty string represents no value better.
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK def list_to_form_options(values, allow_empty=False, allow_empty_text='None'): '''Format a list of values into a list of dict suitable for use in forms: [{value: x, name: y}] :param values: list or list of tuples [(value, name)] :param allow_empty: if true, will add none option (optional, default: False) :param allow_empty_text: label for none value (optional, default: 'None') ''' options = [] if allow_empty: options.append({'value': '', 'text': allow_empty_text or None}) for value in values: if isinstance(value, str): name = value else: # If this is a tuple or list use (value, name) name = value[1] value = value[0] options.append({'value': value, 'text': name}) return options
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK def list_to_form_options(values, allow_empty=False, allow_empty_text='None'): '''Format a list of values into a list of dict suitable for use in forms: [{value: x, name: y}] :param values: list or list of tuples [(value, name)] :param allow_empty: if true, will add none option (optional, default: False) :param allow_empty_text: label for none value (optional, default: 'None') ''' options = [] if allow_empty: options.append({'value': None, 'text': allow_empty_text or None}) for value in values: if isinstance(value, str): name = value else: # If this is a tuple or list use (value, name) name = value[1] value = value[0] options.append({'value': value, 'text': name}) return options
Delete cache first before setting new value
from django.core.cache import cache def cache_get_key(*args, **kwargs): """Get the cache key for storage""" import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.append(str(key)) serialise.append(str(arg)) key = hashlib.md5("".join(serialise)).hexdigest() return key def cache_for(time): """Decorator for caching functions""" def decorator(fn): def wrapper(*args, **kwargs): key = cache_get_key(fn.__name__, *args, **kwargs) result = cache.get(key) if not result or "clear_cache" in kwargs and kwargs["clear_cache"]: cache.delete(key) result = fn(*args, **kwargs) cache.set(key, result, time) return result return wrapper return decorator
from django.core.cache import cache #get the cache key for storage def cache_get_key(*args, **kwargs): import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.append(str(key)) serialise.append(str(arg)) key = hashlib.md5("".join(serialise)).hexdigest() return key #decorator for caching functions def cache_for(time): def decorator(fn): def wrapper(*args, **kwargs): key = cache_get_key(fn.__name__, *args, **kwargs) result = cache.get(key) if not result or "clear_cache" in kwargs and kwargs["clear_cache"]: result = fn(*args, **kwargs) cache.set(key, result, time) return result return wrapper return decorator
Fix a bug in cleanup
import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args): # IF YOU DON'T DO THIS OVER HTTPS YOU WILL GET 308s to goto HTTPS scheme = 'https://' port = '' api = '/api/authorize/pair?pin={pin}&persistent=0' verb = 'POST' request_url = scheme + ip + port + api.format_map({'pin':pin}) context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE https_handler = urllib.request.HTTPSHandler(context=context) request = urllib.request.Request(url=request_url, method=verb) cookies = urllib.request.HTTPCookieProcessor(http.cookiejar.MozillaCookieJar("deployUtil.cookies")) opener = urllib.request.build_opener(https_handler, cookies) resp = opener.open(request) cookies.cookiejar.save(ignore_discard=True)
import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args): # IF YOU DON'T DO THIS OVER HTTPS YOU WILL GET 308s to goto HTTPS scheme = 'https://' port = '' api = '/api/authorize/pair?pin={pin}&persistent=0' verb = 'POST' request_url = scheme + ip + port + api.format_map({'pin':pin}) context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE https_handler = urllib.request.HTTPSHandler(context=context) request = urllib.request.Request(url=request_url, method=verb) cookies = urllib.request.HTTPCookieProcessor(http.cookiejar.MozillaCookieJar("deployUtil.cookies")) opener = urllib.request.build_opener(WDPRedirectHandler(), https_handler, cookies) resp = opener.open(request) cookies.cookiejar.save(ignore_discard=True)
Check whether image viewer widget exists before destroying it
isic.views.ImageFullscreenWidget = isic.View.extend({ render: function () { this.$el.html(isic.templates.imageFullscreenWidget({ model: this.model })).girderModal(this).on('shown.bs.modal', _.bind(function () { this.imageViewerWidget = new isic.views.ImageViewerWidget({ el: this.$('.isic-image-fullscreen-container'), model: this.model, parentView: this }); }, this)).on('hidden.bs.modal', _.bind(function () { if (this.imageViewerWidget) { this.imageViewerWidget.destroy(); delete this.imageViewerWidget; } }, this)); } });
isic.views.ImageFullscreenWidget = isic.View.extend({ render: function () { this.$el.html(isic.templates.imageFullscreenWidget({ model: this.model })).girderModal(this).on('shown.bs.modal', _.bind(function () { this.imageViewerWidget = new isic.views.ImageViewerWidget({ el: this.$('.isic-image-fullscreen-container'), model: this.model, parentView: this }); }, this)).on('hidden.bs.modal', _.bind(function () { this.imageViewerWidget.destroy(); delete this.imageViewerWidget; }, this)); } });
Return event ids as int
# -*- coding: utf-8 -*- import emarsys from django.conf import settings client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT, settings.EMARSYS_PASSWORD, settings.EMARSYS_BASE_URI) def get_events(): response = client.call('/api/v2/event', 'GET') return {event['name']: int(event['id']) for event in response} def trigger_event(event_id, email, context): client.call( '/api/v2/event/{}/trigger'.format(event_id), 'POST', { "key_id": 3, "external_id": email, "data": context } ) def create_contact(email): client.call('/api/v2/contact', 'POST', {"3": email})
# -*- coding: utf-8 -*- import emarsys from django.conf import settings client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT, settings.EMARSYS_PASSWORD, settings.EMARSYS_BASE_URI) def get_events(): response = client.call('/api/v2/event', 'GET') return {event['name']: event['id'] for event in response} def trigger_event(event_id, email, context): client.call( '/api/v2/event/{}/trigger'.format(event_id), 'POST', { "key_id": 3, "external_id": email, "data": context } ) def create_contact(email): client.call('/api/v2/contact', 'POST', {"3": email})
Fix SC.Record statusString unit test
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2009 Apple, Inc. and contributors. // License: Licened under MIT license (see license.js) // ========================================================================== /*globals module ok equals same test MyApp */ var MyApp; module("SC.Record core methods", { setup: function() { MyApp = SC.Object.create({ store: SC.Store.create() }) ; MyApp.Foo = SC.Record.extend({}); MyApp.json = { foo: "bar", number: 123, bool: YES, array: [1,2,3] }; MyApp.foo = MyApp.store.createRecord(MyApp.Foo, MyApp.json); } }); test("statusString", function() { equals(MyApp.foo.statusString(), 'READY_NEW', 'status string should be READY_NEW'); });
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2009 Apple, Inc. and contributors. // License: Licened under MIT license (see license.js) // ========================================================================== /*globals module ok equals same test MyApp */ var MyApp; module("SC.Record core methods", { setup: function() { MyApp = SC.Object.create({ store: SC.Store.create() }) ; MyApp.Foo = SC.Record.extend({}); MyApp.json = { foo: "bar", number: 123, bool: YES, array: [1,2,3] }; MyApp.foo = MyApp.store.createRecord(MyApp.Foo, MyApp.json); } }); test("statusToString", function() { var status = MyApp.store.readStatus(MyApp.foo); equals(SC.Record.statusToString(status), 'EMPTY', 'status string should be EMPTY'); });
Add the dependency to Mardown.
from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils', 'Markdown'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = 'alexis@notmyidea.org', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup import sys requires = ['feedgenerator', 'jinja2', 'pygments', 'docutils'] if sys.version_info < (2,7): requires.append('argparse') setup( name = "pelican", version = '2.3', url = 'http://alexis.notmyidea.org/pelican/', author = 'Alexis Metaireau', author_email = 'alexis@notmyidea.org', description = "A tool to generate a static blog, with restructured text (or markdown) input files.", long_description=open('README.rst').read(), packages = ['pelican'], include_package_data = True, install_requires = requires, scripts = ['bin/pelican'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add current project path to the first position of sys.modules
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Zhang ZY<http://idupx.blogspot.com/> # # 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. ''' set classpath ''' import os import sys CURRENT_PATH = os.path.dirname(os.path.realpath(__file__)) PROJECT_PATH = os.path.realpath(os.path.join(CURRENT_PATH, '..')) if PROJECT_PATH not in sys.path: sys.path.insert(0, PROJECT_PATH) def main(): print 'CURRENT_PATH:', CURRENT_PATH print 'PROJECT_PATH:', PROJECT_PATH if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Zhang ZY<http://idupx.blogspot.com/> # # 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. ''' set classpath ''' import os import sys CURRENT_PATH = os.path.dirname(os.path.realpath(__file__)) PROJECT_PATH = os.path.realpath(os.path.join(CURRENT_PATH, '..')) if PROJECT_PATH not in sys.path: sys.path.append(PROJECT_PATH) def main(): print 'CURRENT_PATH:', CURRENT_PATH print 'PROJECT_PATH:', PROJECT_PATH if __name__ == '__main__': main()
Add PublishProcessor to processors' list
""" TornWAMP user-configurable structures. """ from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc from tornwamp.messages import Code processors = { Code.HELLO: HelloProcessor, Code.GOODBYE: GoodbyeProcessor, Code.SUBSCRIBE: pubsub.SubscribeProcessor, Code.CALL: rpc.CallProcessor, Code.PUBLISH: pubsub.PublishProcessor } # 2: 'welcome', # 3: 'abort', # 4: 'challenge', # 5: 'authenticate', # 7: 'heartbeat', # 8: 'error', # 16: 'publish', # 17: 'published', # 32: 'subscribe', # 33: 'subscribed', # 34: 'unsubscribe', # 35: 'unsubscribed', # 36: 'event', # 49: 'cancel', # 50: 'result', # 64: 'register', # 65: 'registered', # 66: 'unregister', # 67: 'unregistered', # 68: 'invocation', # 69: 'interrupt', # 70: 'yield'
""" TornWAMP user-configurable structures. """ from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc from tornwamp.messages import Code processors = { Code.HELLO: HelloProcessor, Code.GOODBYE: GoodbyeProcessor, Code.SUBSCRIBE: pubsub.SubscribeProcessor, Code.CALL: rpc.CallProcessor } # 2: 'welcome', # 3: 'abort', # 4: 'challenge', # 5: 'authenticate', # 7: 'heartbeat', # 8: 'error', # 16: 'publish', # 17: 'published', # 32: 'subscribe', # 33: 'subscribed', # 34: 'unsubscribe', # 35: 'unsubscribed', # 36: 'event', # 49: 'cancel', # 50: 'result', # 64: 'register', # 65: 'registered', # 66: 'unregister', # 67: 'unregistered', # 68: 'invocation', # 69: 'interrupt', # 70: 'yield'
Sort procedures in a more efficient way.
import Ember from 'ember'; export default Ember.Controller.extend({ procedures: function() { return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, { sortProperties: ['lastModified'], sortAscending: false, content: this.get('model') }); }.property('model.@each.lastModified'), actions: { createProcedure: function() { // TODO: Deal with owner ID and user-inputted information var procedureController = this; var procedure = this.store.createRecord('procedure', { title: 'Surgery Follow-Up', author: 'Partners for Care' }); procedure.save().then(function() { procedureController.transitionToRoute('procedure', procedure); }); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ procedures: function() { return this.get('model').sortBy('lastModified').reverse(); }.property('model.@each.lastModified'), actions: { createProcedure: function() { // TODO: Deal with owner ID and user-inputted information var procedureController = this; var procedure = this.store.createRecord('procedure', { title: 'Surgery Follow-Up', author: 'Partners for Care' }); procedure.save().then(function() { procedureController.transitionToRoute('procedure', procedure); }); } } });
tests: Purge images and containers before each test Signed-off-by: Esben Haabendal <da90c138e4a9573086862393cde34fa33d74f6e5@haabendal.dk>
import pytest import io import contextlib import tempfile import shutil import os from xd.docker.client import * DOCKER_HOST = os.environ.get('DOCKER_HOST', None) @pytest.fixture(scope="function") def docker(request): os.system("for c in `docker ps -a -q`;do docker rm $c;done") os.system("for i in `docker images -q`;do docker rmi $i;done") return DockerClient(host=DOCKER_HOST) class StreamRedirector(object): def __init__(self): self.stream = io.StringIO() def redirect(self): return contextlib.redirect_stdout(self.stream) def get(self): return self.stream.getvalue() def getlines(self): return self.stream.getvalue().rstrip('\n').split('\n') def lastline(self): lines = self.getlines() if not lines: return None return lines[-1] @pytest.fixture def stdout(): return StreamRedirector() @pytest.fixture def cleandir(request): newdir = tempfile.mkdtemp() os.chdir(newdir) def remove_cleandir(): shutil.rmtree(newdir) request.addfinalizer(remove_cleandir) return newdir
import pytest import io import contextlib import tempfile import shutil import os from xd.docker.client import * DOCKER_HOST = os.environ.get('DOCKER_HOST', None) @pytest.fixture(scope="module") def docker(request): return DockerClient(host=DOCKER_HOST) class StreamRedirector(object): def __init__(self): self.stream = io.StringIO() def redirect(self): return contextlib.redirect_stdout(self.stream) def get(self): return self.stream.getvalue() def getlines(self): return self.stream.getvalue().rstrip('\n').split('\n') def lastline(self): lines = self.getlines() if not lines: return None return lines[-1] @pytest.fixture def stdout(): return StreamRedirector() @pytest.fixture def cleandir(request): newdir = tempfile.mkdtemp() os.chdir(newdir) def remove_cleandir(): shutil.rmtree(newdir) request.addfinalizer(remove_cleandir) return newdir
:art: Move function outside of class Since the endRowForSelectionRange method doesn't use any of the class's internal state, make it a function that lives outside the class.
const {Range} = require('atom') module.exports = class RangeFinder { // Public static rangesFor (editor) { return new RangeFinder(editor).ranges() } // Public constructor (editor) { this.editor = editor } // Public ranges () { const selectionRanges = this.selectionRanges() if (selectionRanges.length === 0) { return [this.sortableRangeFrom(this.sortableRangeForEntireBuffer())] } else { return selectionRanges.map((selectionRange) => { return this.sortableRangeFrom(selectionRange) }) } } // Internal selectionRanges () { return this.editor.getSelectedBufferRanges().filter((range) => !range.isEmpty()) } // Internal sortableRangeForEntireBuffer () { return this.editor.getBuffer().getRange() } // Internal sortableRangeFrom (selectionRange) { const startRow = selectionRange.start.row const startCol = 0 const endRow = endRowForSelectionRange(selectionRange) const endCol = this.editor.lineTextForBufferRow(endRow).length return new Range([startRow, startCol], [endRow, endCol]) } } function endRowForSelectionRange (selectionRange) { const row = selectionRange.end.row const column = selectionRange.end.column if (column !== 0) { return row } else { return Math.max(0, row - 1) } }
const {Range} = require('atom') module.exports = class RangeFinder { // Public static rangesFor (editor) { return new RangeFinder(editor).ranges() } // Public constructor (editor) { this.editor = editor } // Public ranges () { const selectionRanges = this.selectionRanges() if (selectionRanges.length === 0) { return [this.sortableRangeFrom(this.sortableRangeForEntireBuffer())] } else { return selectionRanges.map((selectionRange) => { return this.sortableRangeFrom(selectionRange) }) } } // Internal selectionRanges () { return this.editor.getSelectedBufferRanges().filter((range) => !range.isEmpty()) } // Internal sortableRangeForEntireBuffer () { return this.editor.getBuffer().getRange() } // Internal sortableRangeFrom (selectionRange) { const startRow = selectionRange.start.row const startCol = 0 const endRow = this.endRowForSelectionRange(selectionRange) const endCol = this.editor.lineTextForBufferRow(endRow).length return new Range([startRow, startCol], [endRow, endCol]) } // Internal endRowForSelectionRange (selectionRange) { const row = selectionRange.end.row const column = selectionRange.end.column if (column !== 0) { return row } else { return Math.max(0, row - 1) } } }
Reduce code duplication using GET params Replaced the two routes, one for http and another one for https, using GET parameter ?url=
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; // Using GET parameters in place of something like "/:url", because // with this last solution the server is fooled by the "http" in the // middle of the whole url. router.get('/', function(req, res) { var json = {}; json.original = req.param('url'); if (!isValid(json.original)) { json.err = 'invalid url'; } else { json.shorter = getShortUrl(req, random()); + req.originalUrl } res.send(json); }); var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; router.get('/http://:url', function(req, res) { var json = {}; json.original = 'http://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); router.get('/https://:url', function(req, res) { var json = {}; json.original = 'https://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); var getShortUrl = function (req, id) { var baseUrl = req.protocol + '://' + req.get('host') + '/'; return baseUrl + id; } var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
Secure that the given values loading at least.
<?php namespace CWreden\GitLog; use CWreden\GitLog\GitHub\GitHubServiceProvider; use CWreden\GitLog\GitHub\OAuthControllerProvider; use Silex\Provider\DoctrineServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Silex\Provider\SessionServiceProvider; use Silex\Provider\TwigServiceProvider; use Silex\Provider\UrlGeneratorServiceProvider; /** * Class Application * @package CWreden\GitLog */ class Application extends \Silex\Application { /** * @param array $values */ public function __construct(array $values = array()) { parent::__construct($values); $this->register(new SessionServiceProvider()); $this->register(new ServiceControllerServiceProvider()); $this->register(new TwigServiceProvider()); $this->register(new DoctrineServiceProvider()); $this->register(new UrlGeneratorServiceProvider()); $this->register(new GitHubServiceProvider()); $this->mount('', new OAuthControllerProvider()); $this->mount('', new GitLogControllerProvider()); // TODO Create ChangeLog // TODO Edit/Ignore commit messages // TODO Export Services // TODO Search Services // TODO Report Services foreach ($values as $key => $value) { $this[$key] = $value; } } }
<?php namespace CWreden\GitLog; use CWreden\GitLog\GitHub\GitHubServiceProvider; use CWreden\GitLog\GitHub\OAuthControllerProvider; use Silex\Provider\DoctrineServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Silex\Provider\SessionServiceProvider; use Silex\Provider\TwigServiceProvider; use Silex\Provider\UrlGeneratorServiceProvider; /** * Class Application * @package CWreden\GitLog */ class Application extends \Silex\Application { /** * @param array $values */ public function __construct(array $values = array()) { parent::__construct($values); $this->register(new SessionServiceProvider()); $this->register(new ServiceControllerServiceProvider()); $this->register(new TwigServiceProvider()); $this->register(new DoctrineServiceProvider()); $this->register(new UrlGeneratorServiceProvider()); $this->register(new GitHubServiceProvider()); $this->mount('', new OAuthControllerProvider()); $this->mount('', new GitLogControllerProvider()); // TODO Create ChangeLog // TODO Edit/Ignore commit messages // TODO Export Services // TODO Search Services // TODO Report Services } }
Replace 'assert session != null' with Assert.notnull(Object, String)
/* * Copyright 2010 The myBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.spring; import org.apache.ibatis.session.SqlSession; import org.springframework.transaction.support.ResourceHolderSupport; import org.springframework.util.Assert; /** * * @version $Id$ */ public final class SqlSessionHolder extends ResourceHolderSupport { private final SqlSession sqlSession; public SqlSessionHolder(SqlSession sqlSession) { Assert.notNull(sqlSession, "SqlSession must not be null"); this.sqlSession = sqlSession; } public SqlSession getSqlSession() { return sqlSession; } }
/* * Copyright 2010 The myBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.spring; import org.apache.ibatis.session.SqlSession; import org.springframework.transaction.support.ResourceHolderSupport; /** * * @version $Id$ */ public final class SqlSessionHolder extends ResourceHolderSupport { private final SqlSession session; public SqlSessionHolder(SqlSession session) { assert session != null; this.session = session; } public SqlSession getSqlSession() { return session; } }
Add auto refresh start/stop actions
import { receiveWeekNumber, fetchWeekNumber } from './weekNumber'; import { requestNewRelicErrors, receiveNewRelicErrors, fetchNewRelicErrors, } from './newRelicErrors'; import { requestBugsHistory, receiveBugsHistory, fetchBugsHistory, } from './bugsHistory'; export { receiveWeekNumber, fetchWeekNumber, requestNewRelicErrors, receiveNewRelicErrors, fetchNewRelicErrors, requestBugsHistory, receiveBugsHistory, fetchBugsHistory, }; export const refreshAll = () => dispatch => { dispatch(fetchWeekNumber()); dispatch(fetchNewRelicErrors()); dispatch(fetchBugsHistory()); }; let refresher; export const autoRefreshStart = () => dispatch => { refresher = setInterval(() => { dispatch(refreshAll()); }, 1000 * 60); }; export const autoRefreshStop = () => { clearInterval(refresher); };
import { receiveWeekNumber, fetchWeekNumber } from './weekNumber'; import { requestNewRelicErrors, receiveNewRelicErrors, fetchNewRelicErrors, } from './newRelicErrors'; import { requestBugsHistory, receiveBugsHistory, fetchBugsHistory, } from './bugsHistory'; export { receiveWeekNumber, fetchWeekNumber, requestNewRelicErrors, receiveNewRelicErrors, fetchNewRelicErrors, requestBugsHistory, receiveBugsHistory, fetchBugsHistory, }; export const refreshAll = () => dispatch => { dispatch(fetchWeekNumber()); dispatch(fetchNewRelicErrors()); dispatch(fetchBugsHistory()); }; let refresher; export const autoRefreshStart = () => dispatch => { refresher = setInterval(() => { dispatch(refreshAll()); }, 1000 * 60); // TODO: magic number -> config }; export const autoRefreshStop = () => { clearInterval(refresher); };
Load JsonPermission in LoadGameRules func. Currently using the working path for loading of users.json and groups.json
package gamerules import ( "os" "chunkymonkey/command" "chunkymonkey/permission" ) // GameRules is a container type for block, item and recipe definitions. var ( Blocks BlockTypeList Items ItemTypeMap Recipes *RecipeSet FurnaceReactions FurnaceData CommandFramework *command.CommandFramework Permissions permission.IPermissions ) func LoadGameRules(blocksDefFile, itemsDefFile, recipesDefFile, furnaceDefFile string) (err os.Error) { Blocks, err = LoadBlocksFromFile(blocksDefFile) if err != nil { return } Items, err = LoadItemTypesFromFile(itemsDefFile) if err != nil { return } Blocks.CreateBlockItemTypes(Items) Recipes, err = LoadRecipesFromFile(recipesDefFile, Items) if err != nil { return } FurnaceReactions, err = LoadFurnaceDataFromFile(furnaceDefFile) if err != nil { return } // TODO: Load the prefix from a config file CommandFramework = command.NewCommandFramework("/") Permissions, err = permission.LoadJsonPermission("./") if err != nil { return } return }
package gamerules import ( "os" "chunkymonkey/command" ) // GameRules is a container type for block, item and recipe definitions. var ( Blocks BlockTypeList Items ItemTypeMap Recipes *RecipeSet FurnaceReactions FurnaceData CommandFramework *command.CommandFramework ) func LoadGameRules(blocksDefFile, itemsDefFile, recipesDefFile, furnaceDefFile string) (err os.Error) { Blocks, err = LoadBlocksFromFile(blocksDefFile) if err != nil { return } Items, err = LoadItemTypesFromFile(itemsDefFile) if err != nil { return } Blocks.CreateBlockItemTypes(Items) Recipes, err = LoadRecipesFromFile(recipesDefFile, Items) if err != nil { return } FurnaceReactions, err = LoadFurnaceDataFromFile(furnaceDefFile) if err != nil { return } // TODO: Load the prefix from a config file CommandFramework = command.NewCommandFramework("/") return }
Add @since for escapeURI function. Co-authored-by: Evan Mattson <04b4a59aa52dbba0fe4139b6afe8885fd3fa41ec@10up.com>
/** * Escape URI components utility. * * Site Kit by Google, Copyright 2020 Google LLC * * 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 * * https://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. */ /** * A tag function that escapes URI components in a template string. * * @since n.e.x.t * * @param {string[]} strings The array of static strings in the template. * @param {...any} values The array of expressions used in the template. * @return {string} Escaped URI string. */ export function escapeURI( strings, ...values ) { return strings.reduce( ( acc, string, idx ) => { return acc + string + encodeURIComponent( values[ idx ] || '' ); }, '' ); }
/** * Escape URI components utility. * * Site Kit by Google, Copyright 2020 Google LLC * * 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 * * https://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. */ /** * A tag function that escapes URI components in a template string. * * @param {string[]} strings The array of static strings in the template. * @param {...any} values The array of expressions used in the template. * @return {string} Escaped URI string. */ export function escapeURI( strings, ...values ) { return strings.reduce( ( acc, string, idx ) => { return acc + string + encodeURIComponent( values[ idx ] || '' ); }, '' ); }
Fix more secure crypto comment
var mongoose = require('mongoose'), crypto = require('crypto'), Schema = mongoose.Schema, User = new Schema({ username: { type: String, unique: true, required: true }, hashedPassword: { type: String, required: true }, salt: { type: String, required: true }, created: { type: Date, default: Date.now } }); User.methods.encryptPassword = function(password) { return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512).toString('base64'); }; User.virtual('userId') .get(function () { return this.id; }); User.virtual('password') .set(function(password) { this._plainPassword = password; this.salt = crypto.randomBytes(32).toString('hex'); //more secure - this.salt = crypto.randomBytes(128).toString('hex'); this.hashedPassword = this.encryptPassword(password); }) .get(function() { return this._plainPassword; }); User.methods.checkPassword = function(password) { return this.encryptPassword(password) === this.hashedPassword; }; module.exports = mongoose.model('User', User);
var mongoose = require('mongoose'), crypto = require('crypto'), Schema = mongoose.Schema, User = new Schema({ username: { type: String, unique: true, required: true }, hashedPassword: { type: String, required: true }, salt: { type: String, required: true }, created: { type: Date, default: Date.now } }); User.methods.encryptPassword = function(password) { return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512); }; User.virtual('userId') .get(function () { return this.id; }); User.virtual('password') .set(function(password) { this._plainPassword = password; this.salt = crypto.randomBytes(32).toString('hex'); //more secure - this.salt = crypto.randomBytes(128).toString('hex'); this.hashedPassword = this.encryptPassword(password); }) .get(function() { return this._plainPassword; }); User.methods.checkPassword = function(password) { return this.encryptPassword(password) === this.hashedPassword; }; module.exports = mongoose.model('User', User);
Update gas costs for EC mult precompile
const utils = require('ethereumjs-util') const BN = utils.BN const bn128_module = require('rustbn.js') const ecMul_precompile = bn128_module.cwrap('ec_mul', 'string', ['string']) module.exports = function (opts) { let results = {} let data = opts.data let inputHexStr = data.toString('hex') try { let returnData = ecMul_precompile(inputHexStr) results.return = Buffer.from(returnData, 'hex') results.exception = 1 } catch (e) { console.log('exception in ecMul precompile is expected. ignore previous panic...') // console.log(e) results.return = Buffer.alloc(0) results.exception = 0 } // Temporary, replace with finalized gas cost from EIP spec (via ethereum-common) results.gasUsed = new BN(40000) return results }
const utils = require('ethereumjs-util') const BN = utils.BN const bn128_module = require('rustbn.js') const ecMul_precompile = bn128_module.cwrap('ec_mul', 'string', ['string']) module.exports = function (opts) { let results = {} let data = opts.data let inputHexStr = data.toString('hex') try { let returnData = ecMul_precompile(inputHexStr) results.return = Buffer.from(returnData, 'hex') results.exception = 1 } catch (e) { console.log('exception in ecMul precompile is expected. ignore previous panic...') // console.log(e) results.return = Buffer.alloc(0) results.exception = 0 } // Temporary, replace with finalized gas cost from EIP spec (via ethereum-common) results.gasUsed = new BN(2000) return results }
Remove hardsource caching for build testing
/* eslint import/no-extraneous-dependencies: 0 */ const path = require('path'); const merge = require('webpack-merge'); // const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); const baseConfig = require('./webpack.base.config'); // many of the webpack directives need an absolute path const basedir = path.resolve(__dirname, '../'); const devConfig = { // tells Webpack to do some stuff, including setting NODE_ENV mode: 'development', // generate source maps to help debug in browser // devtool: 'source-map', // where to build dev files to for webpack-serve to work output: { path: path.resolve(basedir, 'build', 'public'), pathinfo: true, filename: '[name].[hash].js', chunkFilename: '[id].[hash].js', publicPath: 'http://localhost:2992/', // needed to get correct path in dev manifest file }, plugins: [ // add an intermediate caching step to speed up builds (expect the first one) // new HardSourceWebpackPlugin(), ], }; module.exports = merge.smart(baseConfig, devConfig);
/* eslint import/no-extraneous-dependencies: 0 */ const path = require('path'); const merge = require('webpack-merge'); const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); const baseConfig = require('./webpack.base.config'); // many of the webpack directives need an absolute path const basedir = path.resolve(__dirname, '../'); const devConfig = { // tells Webpack to do some stuff, including setting NODE_ENV mode: 'development', // generate source maps to help debug in browser // devtool: 'source-map', // where to build dev files to for webpack-serve to work output: { path: path.resolve(basedir, 'build', 'public'), pathinfo: true, filename: '[name].[hash].js', chunkFilename: '[id].[hash].js', publicPath: 'http://localhost:2992/', // needed to get correct path in dev manifest file }, plugins: [ // add an intermediate caching step to speed up builds (expect the first one) new HardSourceWebpackPlugin(), ], }; module.exports = merge.smart(baseConfig, devConfig);
Convert integration tests to testng
package net.kencochrane.raven.log4j2; import net.kencochrane.raven.stub.SentryStub; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class SentryAppenderIT { private static final Logger logger = LogManager.getLogger(SentryAppenderIT.class); private SentryStub sentryStub; @BeforeMethod public void setUp() { sentryStub = new SentryStub(); sentryStub.removeEvents(); } @AfterMethod public void tearDown() { sentryStub.removeEvents(); } @Test public void testInfoLog() { assertThat(sentryStub.getEventCount(), is(0)); logger.info("This is a test"); assertThat(sentryStub.getEventCount(), is(1)); } @Test public void testChainedExceptions() { assertThat(sentryStub.getEventCount(), is(0)); logger.error("This is an exception", new UnsupportedOperationException("Test", new UnsupportedOperationException())); assertThat(sentryStub.getEventCount(), is(1)); } }
package net.kencochrane.raven.log4j2; import net.kencochrane.raven.stub.SentryStub; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class SentryAppenderIT { private static final Logger logger = LogManager.getLogger(SentryAppenderIT.class); private SentryStub sentryStub; @Before public void setUp() { sentryStub = new SentryStub(); sentryStub.removeEvents(); } @After public void tearDown() { sentryStub.removeEvents(); } @Test public void testInfoLog() { assertThat(sentryStub.getEventCount(), is(0)); logger.info("This is a test"); assertThat(sentryStub.getEventCount(), is(1)); } @Test public void testChainedExceptions() { assertThat(sentryStub.getEventCount(), is(0)); logger.error("This is an exception", new UnsupportedOperationException("Test", new UnsupportedOperationException())); assertThat(sentryStub.getEventCount(), is(1)); } }
Use page:load event again since this wasn't working
var conversations = { onRespondLaterClick: function() { var $listItem = $(this).parents('.conversation-row').parent(); var path = $(this).attr('data-account-conversation-path'); var pushToEndOfQueue = function() { var $list = $listItem.parent(); $listItem.remove().appendTo($list); } $.post(path, { conversation: { respond_later: true }, _method: 'patch' }, pushToEndOfQueue); return false; }, onArchiveClick: function() { var $listItem = $(this).parents('.conversation-row').parent(); var path = $(this).attr('data-account-conversation-path'); var removeFromQueue = function() { if ($listItem.siblings().length == 0) { $('.empty-state').show(); } $listItem.remove(); } $.post(path, { conversation: { archive: true }, _method: 'patch' }, removeFromQueue); return false; } } $(document).on('ready page:load', function() { $('.list').on('click', '.respond-later', conversations.onRespondLaterClick); $('.list').on('click', '.archive', conversations.onArchiveClick); $("textarea[data-autosize]").autosize(); $('.participants-expand-icon').click(function () { $('.participants-list', $(this).closest('.detail')).toggle(); $(this).toggleClass('expanded'); }); });
var conversations = { onRespondLaterClick: function() { var $listItem = $(this).parents('.conversation-row').parent(); var path = $(this).attr('data-account-conversation-path'); var pushToEndOfQueue = function() { var $list = $listItem.parent(); $listItem.remove().appendTo($list); } $.post(path, { conversation: { respond_later: true }, _method: 'patch' }, pushToEndOfQueue); return false; }, onArchiveClick: function() { var $listItem = $(this).parents('.conversation-row').parent(); var path = $(this).attr('data-account-conversation-path'); var removeFromQueue = function() { if ($listItem.siblings().length == 0) { $('.empty-state').show(); } $listItem.remove(); } $.post(path, { conversation: { archive: true }, _method: 'patch' }, removeFromQueue); return false; } } $(document).on("ready", function() { $('.list').delegate('.respond-later', 'click', conversations.onRespondLaterClick); $('.list').delegate('.archive', 'click', conversations.onArchiveClick); }); $(document).on('ready page:load', function() { $("textarea[data-autosize]").autosize(); $('.participants-expand-icon').click(function () { $('.participants-list', $(this).closest('.detail')).toggle(); $(this).toggleClass('expanded'); }); });
Allow elements to be cast to strings This returns their nodeValue, and is useful to avoid checking that an element exists before attempting to get it's nodeValue
<?php namespace duncan3dc\DomParser; trait Element { public function __toString() { return $this->nodeValue; } public function __get($key) { $value = $this->dom->$key; switch ($key) { case "parentNode": return $this->newElement($value); case "nodeValue": return trim($value); } return $value; } public function nodeValue($value) { $this->dom->nodeValue = ""; $node = $this->dom->ownerDocument->createTextNode($value); $this->dom->appendChild($node); } public function getAttribute($name) { return $this->dom->getAttribute($name); } public function setAttribute($name, $value) { return $this->dom->setAttribute($name, $value); } public function getAttributes() { $attributes = []; foreach ($this->dom->attributes as $attr) { $attributes[$attr->name] = $attr->value; } return $attributes; } }
<?php namespace duncan3dc\DomParser; trait Element { public function __get($key) { $value = $this->dom->$key; switch ($key) { case "parentNode": return $this->newElement($value); case "nodeValue": return trim($value); } return $value; } public function nodeValue($value) { $this->dom->nodeValue = ""; $node = $this->dom->ownerDocument->createTextNode($value); $this->dom->appendChild($node); } public function getAttribute($name) { return $this->dom->getAttribute($name); } public function setAttribute($name, $value) { return $this->dom->setAttribute($name, $value); } public function getAttributes() { $attributes = []; foreach ($this->dom->attributes as $attr) { $attributes[$attr->name] = $attr->value; } return $attributes; } }
Add underline to wysiwyg tool bar
CKEDITOR.editorConfig = function (config) { config.filebrowserImageBrowseLinkUrl = '/ckeditor/pictures'; config.filebrowserImageBrowseUrl = '/ckeditor/pictures'; config.filebrowserImageUploadUrl = '/ckeditor/pictures'; config.toolbar = [ { name: 'styles', items: ['Format'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['Image'] } ]; };
CKEDITOR.editorConfig = function (config) { config.filebrowserImageBrowseLinkUrl = '/ckeditor/pictures'; config.filebrowserImageBrowseUrl = '/ckeditor/pictures'; config.filebrowserImageUploadUrl = '/ckeditor/pictures'; config.toolbar = [ { name: 'styles', items: ['Format'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Strike', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['Image'] } ]; };
Upgrade to Flask 0.12.3 to fix CVE-2018-1000656
from setuptools import setup with open('README.md') as file: long_description = file.read() setup( name="guacamole-files", version="0.1.0", author="Antonin Messinger", author_email="antonin.messinger@gmail.com", description=" Upload any file, get a URL back", long_description=long_description, license="MIT License", url="https://github.com/Antojitos/guacamole", download_url="https://github.com/Antojitos/guacamole/archive/0.1.0.tar.gz", keywords=["guacamole", "url", "files"], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], packages=['guacamole'], install_requires=[ 'Flask==0.12.3', 'Flask-PyMongo==0.4.0', ], test_suite='tests.main' )
from setuptools import setup with open('README.md') as file: long_description = file.read() setup( name="guacamole-files", version="0.1.0", author="Antonin Messinger", author_email="antonin.messinger@gmail.com", description=" Upload any file, get a URL back", long_description=long_description, license="MIT License", url="https://github.com/Antojitos/guacamole", download_url="https://github.com/Antojitos/guacamole/archive/0.1.0.tar.gz", keywords=["guacamole", "url", "files"], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Flask', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ], packages=['guacamole'], install_requires=[ 'Flask==0.10.1', 'Flask-PyMongo==0.4.0', ], test_suite='tests.main' )
Add viewport meta for a little mobile friendliness Without this, the viewer would appear "zoomed out" on mobile devices.
<html> <head> <!-- https://github.com/LeoWinterDE/TS3SSV --> <title>TeamSpeak Server Status Viewer</title> <link rel="stylesheet" type="text/css" href="/ts3ssv.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script type="text/javascript" src="/ts3ssv.js"></script> </head> <body> <?php require_once("ts3ssv.php"); $ts3ssv = new ts3ssv("s1.ts.5g5.net", 10011); $ts3ssv->useServerPort(9987); $ts3ssv->imagePath = "/img/default/"; $ts3ssv->timeout = 2; $ts3ssv->setCache(180); $ts3ssv->hideEmptyChannels = false; $ts3ssv->hideParentChannels = false; $ts3ssv->showNicknameBox = true; $ts3ssv->showPasswordBox = false; echo $ts3ssv->render(); ?> </body> </html>
<html> <head> <!-- https://github.com/LeoWinterDE/TS3SSV --> <title>TeamSpeak Server Status Viewer</title> <link rel="stylesheet" type="text/css" href="/ts3ssv.css" /> <script type="text/javascript" src="/ts3ssv.js"></script> </head> <body> <?php require_once("ts3ssv.php"); $ts3ssv = new ts3ssv("s1.ts.5g5.net", 10011); $ts3ssv->useServerPort(9987); $ts3ssv->imagePath = "/img/default/"; $ts3ssv->timeout = 2; $ts3ssv->setCache(180); $ts3ssv->hideEmptyChannels = false; $ts3ssv->hideParentChannels = false; $ts3ssv->showNicknameBox = true; $ts3ssv->showPasswordBox = false; echo $ts3ssv->render(); ?> </body> </html>
Bump version to v3.0.0 - ready for release
#!/usr/bin/env python import sys import os if "publish" in sys.argv[-1]: os.system("python setup.py sdist upload") sys.exit() try: from setuptools import setup setup except ImportError: from distutils.core import setup setup # Command-line tools entry_points = {'console_scripts': [ 'K2onSilicon = K2fov.K2onSilicon:K2onSilicon_main', 'K2inMicrolensRegion = K2fov.c9:inMicrolensRegion_main', 'K2findCampaigns = K2fov.K2findCampaigns:K2findCampaigns_main', 'K2findCampaigns-csv = K2fov.K2findCampaigns:K2findCampaigns_csv_main' ]} setup(name='K2fov', version='3.0.0', description='Find which targets are in the field of view of K2', author='Tom Barclay', author_email='tom@tombarclay.com', url='https://github.com/mrtommyb/K2fov', packages=['K2fov'], package_data={'K2fov': ['data/*.json']}, install_requires=["numpy>=1.8"], entry_points=entry_points, )
#!/usr/bin/env python import sys import os if "publish" in sys.argv[-1]: os.system("python setup.py sdist upload") sys.exit() try: from setuptools import setup setup except ImportError: from distutils.core import setup setup # Command-line tools entry_points = {'console_scripts': [ 'K2onSilicon = K2fov.K2onSilicon:K2onSilicon_main', 'K2inMicrolensRegion = K2fov.c9:inMicrolensRegion_main', 'K2findCampaigns = K2fov.K2findCampaigns:K2findCampaigns_main', 'K2findCampaigns-csv = K2fov.K2findCampaigns:K2findCampaigns_csv_main' ]} setup(name='K2fov', version='2.1.dev', description='Find which targets are in the field of view of K2', author='Tom Barclay', author_email='tom@tombarclay.com', url='https://github.com/mrtommyb/K2fov', packages=['K2fov'], package_data={'K2fov': ['data/*.json']}, install_requires=["numpy>=1.8"], entry_points=entry_points, )
Fix for not needing to specify gravity
"use strict"; function Particle(x, y, speed, direction, gravity) { this.position = vector.create(x, y); this.velocity = vector.create(0, 0); this.gravity = vector.create(0, gravity || 0); this.velocity.setLength(speed); this.velocity.setAngle(direction); this.color = 'rgb(' + (Math.random() * 255 | 0) + ', ' + (Math.random() * 255 | 0) + ', ' + (Math.random() * 255 | 0) + ')'; this.radius = 10; }; Particle.prototype = { update: function() { this.accelerate(this.gravity); this.position = this.position.add(this.velocity); }, accelerate: function(acceleration) { this.velocity.addTo(acceleration); }, render: function() { context.save(); context.fillStyle = this.color; context.beginPath(); context.arc(this.position.getX(), this.position.getY(), this.radius, 0, Math.PI * 2, false); context.fill(); context.restore(); } };
"use strict"; function Particle(x, y, speed, direction, gravity) { this.position = vector.create(x, y); this.velocity = vector.create(0, 0); this.gravity = vector.create(0, gravity); this.velocity.setLength(speed); this.velocity.setAngle(direction); this.color = 'rgb(' + (Math.random() * 255 | 0) + ', ' + (Math.random() * 255 | 0) + ', ' + (Math.random() * 255 | 0) + ')'; this.radius = 10; }; Particle.prototype = { update: function() { this.accelerate(this.gravity); this.position = this.position.add(this.velocity); }, accelerate: function(acceleration) { this.velocity.addTo(acceleration); }, render: function() { context.save(); context.fillStyle = this.color; context.beginPath(); context.arc(this.position.getX(), this.position.getY(), this.radius, 0, Math.PI * 2, false); context.fill(); context.restore(); } };
Set primary site ID as default site ID for existing menus
<?php namespace olivestudio\olivemenus\migrations; use Craft; use craft\db\Migration; /** * Migration: Add site_id field to olivemenus table migration. * @since 1.1.7 */ class m200228_124859_olivemenus_addSiteIdFieldToMenusTable extends Migration { /** * @inheritdoc */ public function safeUp() { if (!$this->db->columnExists('{{%olivemenus}}', 'site_id')) { $this->addColumn('{{%olivemenus}}', 'site_id', $this->integer(11)->after('handle')); $this->update('{{%olivemenus}}', ['site_id' => Craft::$app->sites->primarySite->id]); } } /** * @inheritdoc */ public function safeDown() { $this->dropColumn('{{%olivemenus}}', 'site_id'); } }
<?php namespace olivestudio\olivemenus\migrations; use craft\db\Migration; /** * Migration: Add site_id field to olivemenus table migration. * @since 1.1.7 */ class m200228_124859_olivemenus_addSiteIdFieldToMenusTable extends Migration { /** * @inheritdoc */ public function safeUp() { // Place migration code here... if (!$this->db->columnExists('{{%olivemenus}}', 'site_id')) { $this->addColumn('{{%olivemenus}}', 'site_id', $this->integer(11)->after('handle')); } } /** * @inheritdoc */ public function safeDown() { $this->dropColumn('{{%olivemenus}}', 'site_id'); } }
Add upper bound on PyMongo version for future compatibility
import setuptools setuptools.setup( name="Monufacture", version="2.0.0", author="Tom Leach", author_email="tom@gc.io", description="A lightweight factory framework for easily generating test data in MongoDB", license="BSD", keywords="mongo mongodb database testing factory pymongo", url="http://github.com/gamechanger/monufacture", packages=["monufacture"], long_description="Monufacture is a factory framework with an API designed to make " + "it as easy as possible to generate valid test data in MongoDB. " + "Inspired by the excellent factory_girl Ruby Gem.", install_requires=['pymongo>=3.0.0,<4.0.0', 'pytz'], tests_require=['mock', 'nose', 'freezegun'] )
import setuptools setuptools.setup( name="Monufacture", version="2.0.0", author="Tom Leach", author_email="tom@gc.io", description="A lightweight factory framework for easily generating test data in MongoDB", license="BSD", keywords="mongo mongodb database testing factory pymongo", url="http://github.com/gamechanger/monufacture", packages=["monufacture"], long_description="Monufacture is a factory framework with an API designed to make " + "it as easy as possible to generate valid test data in MongoDB. " + "Inspired by the excellent factory_girl Ruby Gem.", install_requires=['pymongo>=3.0.0', 'pytz'], tests_require=['mock', 'nose', 'freezegun'] )
Adjust selector to hit correct part of state
import { createSelector } from 'reselect' import events from '../../core/events' const documentCaptures = state => state.captures.document const faceCaptures = state => state.captures.face export const documentCaptured = createSelector( documentCaptures, documents => documents.some(i => i.valid) ) export const documentSelector = createSelector( documentCaptures, documents => documents.filter(i => i.valid) ) export const faceCaptured = createSelector( faceCaptures, faces => faces.some(i => i.valid) ) export const faceSelector = createSelector( faceCaptures, faces => faces.filter(i => i.valid) ) export const allCaptured = createSelector( documentCaptured, faceCaptured, (a, b) => [a, b].every(i => i) ) export const captureSelector = createSelector( documentSelector, faceSelector, (documentCapture, faceCapture) => ({ documentCapture: documentCapture[0], faceCapture: faceCapture[0] }) )
import { createSelector } from 'reselect' import events from '../../core/events' const documentCaptures = state => state.documentCaptures const faceCaptures = state => state.faceCaptures export const documentCaptured = createSelector( documentCaptures, documents => documents.some(i => i.isValid) ) export const documentSelector = createSelector( documentCaptures, documents => documents.filter(i => i.isValid) ) export const faceCaptured = createSelector( faceCaptures, faces => faces.some(i => i.isValid) ) export const faceSelector = createSelector( faceCaptures, faces => faces.filter(i => i.isValid) ) export const allCaptured = createSelector( documentCaptured, faceCaptured, (a, b) => [a, b].every(i => i) ) export const captureSelector = createSelector( documentSelector, faceSelector, (documentCapture, faceCapture) => ({ documentCapture: documentCapture[0], faceCapture: faceCapture[0] }) )
Fix error on /ticks command with invalid parameters. Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>
package me.nallar.tickthreading.minecraft.commands; import java.util.List; import me.nallar.tickthreading.minecraft.TickThreading; import me.nallar.tickthreading.util.TableFormatter; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class TicksCommand extends Command { public static String name = "ticks"; @Override public String getCommandName() { return name; } @Override public boolean canCommandSenderUseCommand(ICommandSender commandSender) { return !TickThreading.instance.requireOpForTicksCommand || super.canCommandSenderUseCommand(commandSender); } @Override public void processCommand(ICommandSender commandSender, List<String> arguments) { World world = null; if (!arguments.isEmpty()) { try { world = DimensionManager.getWorld(Integer.valueOf(arguments.get(0))); } catch(Exception ignored) { } } else if (commandSender instanceof Entity) { world = ((Entity) commandSender).worldObj; } if (world == null) { sendChat(commandSender, "Usage: /ticks [dimensionid]"); return; } sendChat(commandSender, String.valueOf(TickThreading.instance.getManager(world).writeDetailedStats(new TableFormatter(commandSender)))); } }
package me.nallar.tickthreading.minecraft.commands; import java.util.List; import me.nallar.tickthreading.minecraft.TickThreading; import me.nallar.tickthreading.util.TableFormatter; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class TicksCommand extends Command { public static String name = "ticks"; @Override public String getCommandName() { return name; } @Override public boolean canCommandSenderUseCommand(ICommandSender commandSender) { return !TickThreading.instance.requireOpForTicksCommand || super.canCommandSenderUseCommand(commandSender); } @Override public void processCommand(ICommandSender commandSender, List<String> arguments) { World world = null; if (!arguments.isEmpty()) { world = DimensionManager.getWorld(Integer.valueOf(arguments.get(0))); } else if (commandSender instanceof Entity) { world = ((Entity) commandSender).worldObj; } if (world == null) { sendChat(commandSender, "Usage: /ticks [dimensionid]"); return; } sendChat(commandSender, String.valueOf(TickThreading.instance.getManager(world).writeDetailedStats(new TableFormatter(commandSender)))); } }
Add return types - batch 6/n
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * ExtensionInterface is the interface implemented by container extension classes. * * @author Fabien Potencier <fabien@symfony.com> */ interface ExtensionInterface { /** * Loads a specific configuration. * * @throws \InvalidArgumentException When provided tag is not defined in this extension */ public function load(array $configs, ContainerBuilder $container); /** * Returns the namespace to be used for this extension (XML namespace). * * @return string The XML namespace */ public function getNamespace(); /** * Returns the base path for the XSD files. * * @return string|false */ public function getXsdValidationBasePath(); /** * Returns the recommended alias to use in XML. * * This alias is also the mandatory prefix to use when using YAML. * * @return string The alias */ public function getAlias(); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * ExtensionInterface is the interface implemented by container extension classes. * * @author Fabien Potencier <fabien@symfony.com> */ interface ExtensionInterface { /** * Loads a specific configuration. * * @throws \InvalidArgumentException When provided tag is not defined in this extension */ public function load(array $configs, ContainerBuilder $container); /** * Returns the namespace to be used for this extension (XML namespace). * * @return string The XML namespace */ public function getNamespace(); /** * Returns the base path for the XSD files. * * @return string|false */ public function getXsdValidationBasePath(); /** * Returns the recommended alias to use in XML. * * This alias is also the mandatory prefix to use when using YAML. * * @return string The alias */ public function getAlias(): string; }
Fix reference to static var
#! usr/bin/env python3 from docopt import docopt from matplotlib import pyplot import re class Schema: """ Wraps the SQL source code for a schema and provides methods to get information about that schema. """ table_def = re.compile(r"CREATE TABLE|create table") def __init__(self, source): """ Creates a new instance of Schema for the specified source code string. """ self.source = source def n_tables(self): """ Returns the number of tables defined in the schema """ return len(Schema.table_def.findall(source)) def n_keys(self): """ Returns the number of keys defined in the schema """ pass #TODO: not yet implementend def n_datatypes(self): """ Returns the number of each data type in the schema. """ pass #TODO: not yet implementend def lengths(self): """ Returns a dictionary mapping each data type in the schema to a list of the lengths of those data types. """ pass #TODO: not yet implementend
#! usr/bin/env python3 from docopt import docopt from matplotlib import pyplot import re class Schema: """ Wraps the SQL source code for a schema and provides methods to get information about that schema. """ table_def = re.compile(r"CREATE TABLE|create table") def __init__(self, source): """ Creates a new instance of Schema for the specified source code string. """ self.source = source def n_tables(self): """ Returns the number of tables defined in the schema """ return len(table_def.findall(source)) def n_keys(self): """ Returns the number of keys defined in the schema """ pass #TODO: not yet implementend def n_datatypes(self): """ Returns the number of each data type in the schema. """ pass #TODO: not yet implementend def lengths(self): """ Returns a dictionary mapping each data type in the schema to a list of the lengths of those data types. """ pass #TODO: not yet implementend
Make sure the logger class is process aware even when running Python >= 2.6
import logging import sys def _check_logger_class(): """Make sure process name is recorded when loggers are used.""" from multiprocessing.process import current_process logging._acquireLock() try: OldLoggerClass = logging.getLoggerClass() if not getattr(OldLoggerClass, '_process_aware', False): class ProcessAwareLogger(OldLoggerClass): _process_aware = True def makeRecord(self, *args, **kwds): record = OldLoggerClass.makeRecord(self, *args, **kwds) record.processName = current_process()._name return record logging.setLoggerClass(ProcessAwareLogger) finally: logging._releaseLock() def monkeypatch(): _check_logger_class()
import logging import sys def _check_logger_class(): """Make sure process name is recorded when loggers are used.""" from multiprocessing.process import current_process logging._acquireLock() try: OldLoggerClass = logging.getLoggerClass() if not getattr(OldLoggerClass, '_process_aware', False): class ProcessAwareLogger(OldLoggerClass): _process_aware = True def makeRecord(self, *args, **kwds): record = OldLoggerClass.makeRecord(self, *args, **kwds) record.processName = current_process()._name return record logging.setLoggerClass(ProcessAwareLogger) finally: logging._releaseLock() def monkeypatch(): major, minor = sys.version_info[:2] if major == 2 and minor < 6: # python < 2.6 _check_logger_class()
Call `aperture.main.init()` before the window is created
const {app, BrowserWindow, ipcMain} = require('electron'); const aperture = require('../aperture').main; let win; function createWindow() { win = new BrowserWindow({width: 800, height: 600}); win.loadURL(`file://${__dirname}/index.html`); win.webContents.openDevTools(); win.on('closed', () => { win = null; }); ipcMain.on('renderer-ready', (event, arg) => { console.log(arg); event.sender.send('start-capturing', Date.now()); }); } app.on('ready', () => { aperture.init(); createWindow(); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (win === null) { createWindow(); } });
const {app, BrowserWindow, ipcMain} = require('electron'); const aperture = require('../aperture').main; let win; function createWindow() { win = new BrowserWindow({width: 800, height: 600}); win.loadURL(`file://${__dirname}/index.html`); win.webContents.openDevTools(); win.on('closed', () => { win = null; }); ipcMain.on('renderer-ready', (event, arg) => { console.log(arg); event.sender.send('start-capturing', Date.now()); }); aperture.init(app, win); } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (win === null) { createWindow(); } });
Disable Spring parsing of CLI arguments as properties
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Genie Agent application. * * @author mprimi * @since 4.0.0 */ @SpringBootApplication public class GenieAgentApplication { /** * Main method, actual execution is delegated to GenieAgentRunner. * * @param args command-line arguments */ public static void main(final String[] args) { System.exit(new GenieAgentApplication().run(args)); } private int run(final String[] args) { final SpringApplication app = new SpringApplication(GenieAgentApplication.class); // Disable parsing of command-line arguments into properties. app.setAddCommandLineProperties(false); return SpringApplication.exit(app.run(args)); } }
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Genie Agent application. * * @author mprimi * @since 4.0.0 */ @SpringBootApplication public class GenieAgentApplication { /** * Main method, actual execution is delegated to GenieAgentRunner. * * @param args command-line arguments */ public static void main(final String[] args) { System.exit(new GenieAgentApplication().run(args)); } private int run(final String[] args) { return SpringApplication.exit( SpringApplication.run( GenieAgentApplication.class, args ) ); } }
Remove logging, no usefull info
package org.lodder.subtools.subsort.lib.control; import java.io.File; import java.util.List; import org.lodder.subtools.sublibrary.Manager; import org.lodder.subtools.sublibrary.exception.ControlFactoryException; import org.lodder.subtools.sublibrary.exception.ReleaseControlException; import org.lodder.subtools.sublibrary.exception.ReleaseParseException; import org.lodder.subtools.sublibrary.model.Release; import org.lodder.subtools.sublibrary.settings.model.MappingTvdbScene; public class VideoFileFactory { public static Release get(final File file, List<MappingTvdbScene> dict, Manager manager) throws ControlFactoryException, ReleaseParseException, ReleaseControlException { VideoFileControl vfc = VideoFileControlFactory.getController(file, manager); Release release = null; if (vfc instanceof EpisodeFileControl) { release = vfc.process(dict); } else if (vfc instanceof MovieFileControl) { release = vfc.process(dict); } return release; } }
package org.lodder.subtools.subsort.lib.control; import java.io.File; import java.util.List; import org.lodder.subtools.sublibrary.Manager; import org.lodder.subtools.sublibrary.exception.ControlFactoryException; import org.lodder.subtools.sublibrary.exception.ReleaseControlException; import org.lodder.subtools.sublibrary.exception.ReleaseParseException; import org.lodder.subtools.sublibrary.logging.Logger; import org.lodder.subtools.sublibrary.model.Release; import org.lodder.subtools.sublibrary.settings.model.MappingTvdbScene; public class VideoFileFactory { public static Release get(final File file, List<MappingTvdbScene> dict, Manager manager) throws ControlFactoryException, ReleaseParseException, ReleaseControlException { Logger.instance.trace("VideoFileFactory", "get", ""); VideoFileControl vfc = VideoFileControlFactory.getController(file, manager); Release release = null; if (vfc instanceof EpisodeFileControl) { release = vfc.process(dict); } else if (vfc instanceof MovieFileControl) { release = vfc.process(dict); } return release; } }
Fix problems identified by broken test
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from cairis.core.ARM import * from cairis.daemon.CairisHTTPError import CairisHTTPError, ARMHTTPError from cairis.data.CairisDAO import CairisDAO from cairis.bin.cimport import file_import __author__ = 'Shamal Faily' class ImportDAO(CairisDAO): def __init__(self, session_id): CairisDAO.__init__(self, session_id) def file_import(self,importFile,mFormat,overwriteFlag): try: return file_import(importFile,mFormat,overwriteFlag,self.session_id) except DatabaseProxyException as ex: self.close() raise ARMHTTPError(ex)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from cairis.core.ARM import * from cairis.daemon.CairisHTTPError import CairisHTTPError, ARMHTTPError from cairis.data.CairisDAO import CairisDAO from cairis.bin.cimport import file_import __author__ = 'Shamal Faily' class ImportDAO(CairisDAO): def __init__(self, session_id): CairisDAO.__init__(self, session_id) def file_import(self,importFile,mFormat,overwriteFlag): try: file_import(importFile,mFormat,overwriteFlag,self.session_id) except DatabaseProxyException as ex: self.close() raise ARMHTTPError(ex)
Use log.Fatalln to guarantee the final gasp is written to the log file
package bot // LogLevel for determining when to output a log entry type LogLevel int // Definitions of log levels in order from most to least verbose const ( Trace LogLevel = iota Debug Info Warn Error Fatal ) // Log logs messages whenever the connector log level is // less than the given level func (b *robot) Log(l LogLevel, v ...interface{}) { if l >= b.level { var prefix string switch l { case Trace: prefix = "Trace:" case Debug: prefix = "Debug:" case Info: prefix = "Info:" case Warn: prefix = "Warning:" case Error: prefix = "Error:" case Fatal: prefix = "Fatal:" } if l == Fatal { b.logger.Fatalln(prefix, v) } else { b.logger.Println(prefix, v) } } } // SetLogLevel updates the connector log level func (b *robot) setLogLevel(l LogLevel) { b.lock.Lock() b.level = l b.lock.Unlock() }
package bot import ( "os" "time" ) // LogLevel for determining when to output a log entry type LogLevel int // Definitions of log levels in order from most to least verbose const ( Trace LogLevel = iota Debug Info Warn Error Fatal ) // Log logs messages whenever the connector log level is // less than the given level func (b *robot) Log(l LogLevel, v ...interface{}) { if l >= b.level { var prefix string switch l { case Trace: prefix = "Trace:" case Debug: prefix = "Debug:" case Info: prefix = "Info:" case Warn: prefix = "Warning:" case Error: prefix = "Error:" case Fatal: prefix = "Fatal:" } b.logger.Println(prefix, v) if l == Fatal { time.Sleep(time.Second) // ample time for the log message to reach the file os.Exit(1) } } } // SetLogLevel updates the connector log level func (b *robot) setLogLevel(l LogLevel) { b.lock.Lock() b.level = l b.lock.Unlock() }
Add missing package data for flickering
# Licensed under a 3-clause BSD style license - see LICENSE.rst from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='jconnelly@cfa.harvard.edu', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/*.fits.gz', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, )
# Licensed under a 3-clause BSD style license - see LICENSE.rst from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='jconnelly@cfa.harvard.edu', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, )
Add Jacoco to list of valid formats
(function (Joi, util, logger) { 'use strict'; var validFormats = ['lcov','jacoco']; var formatValidation = Joi.string().valid(validFormats).required(); module.exports = { getParser: function getParser(coverageFormat) { var validFormat = Joi.validate(coverageFormat, formatValidation); if (validFormat.error) { logger.error(validFormat.error); throw new Error(util.format('Expected one of the following supported formats: %j, but got [%s]', validFormats, coverageFormat)); } logger.debug('Creating coverage parser for: ' + coverageFormat); return require('./impl/' + coverageFormat); } }; }(require('joi'), require('util'), require('./logger')()));
(function (Joi, util, logger) { 'use strict'; var validFormats = ['lcov']; var formatValidation = Joi.string().valid(validFormats).required(); module.exports = { getParser: function getParser(coverageFormat) { var validFormat = Joi.validate(coverageFormat, formatValidation); if (validFormat.error) { logger.error(validFormat.error); throw new Error(util.format('Expected one of the following supported formats: %j, but got [%s]', validFormats, coverageFormat)); } logger.debug('Creating coverage parser for: ' + coverageFormat); return require('./impl/' + coverageFormat); } }; }(require('joi'), require('util'), require('./logger')()));
Resolve issue with running plugin on multiple rules.
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { css.walkRules(rule => { let abort = false; processors.forEach(p => { const res = p.explode(rule); if (typeof res === 'boolean') { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { let abort = false; css.walkRules(rule => { processors.forEach(p => { const res = p.explode(rule); if (res === false) { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
Check that an app able to handle the Intent exists Prevents the app from crashing if an intent is send with no app able to handle it
package com.ivanph.webintent; import android.content.Intent; import android.net.Uri; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.common.MapBuilder; /** * {@link NativeModule} that allows JS to open the default browser for an url. */ public class RNWebIntentModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; public RNWebIntentModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "WebIntent"; } @ReactMethod public void open(String url) { if (Uri.parse(url).getScheme() == null) { //if URL is missing scheme default to http Uri.Builder builder = new Uri.Builder(); url = builder.scheme("http").authority(url).build().toString(); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Check that an app exists to receive the intent if (intent.resolveActivity(this.reactContext.getPackageManager()) != null) { this.reactContext.startActivity(intent); } } }
package com.ivanph.webintent; import android.content.Intent; import android.net.Uri; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.common.MapBuilder; /** * {@link NativeModule} that allows JS to open the default browser for an url. */ public class RNWebIntentModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; public RNWebIntentModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "WebIntent"; } @ReactMethod public void open(String url) { if (Uri.parse(url).getScheme() == null) { //if URL is missing scheme default to http Uri.Builder builder = new Uri.Builder(); url = builder.scheme("http").authority(url).build().toString(); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.reactContext.startActivity(intent); } }
[YouTrack] Tweak button rendering on agile board
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; /* the first selector is required for youtrack-5 and the second for youtrack-6 */ togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) { var link, description, numElem = $('a.issueId'), titleElem = $(".issue-summary"), projectElem = $('.fsi-properties .disabled.bold'); description = titleElem.textContent; description = numElem.firstChild.textContent.trim() + " " + description.trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectElem ? projectElem.textContent : '' }); elem.insertBefore(link, titleElem); }); // Agile board togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) { var link, container = $('.sb-task-details', elem), description = $('.sb-task-summary', elem).textContent, projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim(); link = togglbutton.createTimerLink({ className: 'youtrack', buttonType: 'minimal', description: description, projectName: projectName }); container.appendChild(link); });
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; /* the first selector is required for youtrack-5 and the second for youtrack-6 */ togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) { var link, description, numElem = $('a.issueId'), titleElem = $(".issue-summary"), projectElem = $('.fsi-properties .disabled.bold'); description = titleElem.textContent; description = numElem.firstChild.textContent.trim() + " " + description.trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectElem ? projectElem.textContent : '' }); elem.insertBefore(link, titleElem); }); // Agile board togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) { var link, container = $('.sb-task-title', elem), description = $('.sb-task-summary', elem).textContent, projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectName }); container.appendChild(link); });
Use __file__ instead of __name__
"""Originally from funfactory (funfactory/path_utils.py) on a380a54""" import os from os.path import abspath, dirname def path(*a): return os.path.join(ROOT, *a) def import_mod_by_name(target): # stolen from mock :) components = target.split('.') import_path = components.pop(0) thing = __import__(import_path) for comp in components: import_path += ".%s" % comp thing = _dot_lookup(thing, comp, import_path) return thing def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: __import__(import_path) return getattr(thing, comp) ROOT = dirname(dirname(abspath(__file__)))
"""Originally from funfactory (funfactory/path_utils.py) on a380a54""" import os from os.path import abspath, dirname def path(*a): return os.path.join(ROOT, *a) def import_mod_by_name(target): # stolen from mock :) components = target.split('.') import_path = components.pop(0) thing = __import__(import_path) for comp in components: import_path += ".%s" % comp thing = _dot_lookup(thing, comp, import_path) return thing def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: __import__(import_path) return getattr(thing, comp) ROOT = dirname(abspath(__name__))
Fix changed done callback, missing typeof.
import Server from './server'; import Client from './client'; const debug = require('debug')('tinylr'); // Need to keep track of LR servers when notifying const servers = []; export default tinylr; // Expose Server / Client objects tinylr.Server = Server; tinylr.Client = Client; // and the middleware helpers tinylr.middleware = middleware; tinylr.changed = changed; // Main entry point function tinylr (opts) { const srv = new Server(opts); servers.push(srv); return srv; } // A facade to Server#handle function middleware (opts) { const srv = new Server(opts); servers.push(srv); return function tinylr (req, res, next) { srv.handler(req, res, next); }; } // Changed helper, helps with notifying the server of a file change function changed (done) { const files = [].slice.call(arguments); if (typeof files[files.length - 1] === 'function') done = files.pop(); done = typeof done === 'function' ? done : () => {}; debug('Notifying %d servers - Files: ', servers.length, files); servers.forEach(srv => { const params = { params: { files: files } }; srv && srv.changed(params); }); done(); }
import Server from './server'; import Client from './client'; const debug = require('debug')('tinylr'); // Need to keep track of LR servers when notifying const servers = []; export default tinylr; // Expose Server / Client objects tinylr.Server = Server; tinylr.Client = Client; // and the middleware helpers tinylr.middleware = middleware; tinylr.changed = changed; // Main entry point function tinylr (opts) { const srv = new Server(opts); servers.push(srv); return srv; } // A facade to Server#handle function middleware (opts) { const srv = new Server(opts); servers.push(srv); return function tinylr (req, res, next) { srv.handler(req, res, next); }; } // Changed helper, helps with notifying the server of a file change function changed (done) { const files = [].slice.call(arguments); if (files[files.length - 1] === 'function') done = files.pop(); done = typeof done === 'function' ? done : () => {}; debug('Notifying %d servers - Files: ', servers.length, files); servers.forEach(srv => { const params = { params: { files: files } }; srv && srv.changed(params); }); done(); }
Refactor two listeners into one
// # Place all the behaviors and hooks related to the matching controller here. // # All this logic will automatically be available in application.js. // # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).ready(function(){ // bindSearchBySubmit(); bindSearch(); }) var bindSearch = function(){ $('form.navbar-form').on('click','submit, .glyphicon-search', function(event){ event.preventDefault(); var data = $("#peopleSearchBar").val(); searchServer(data); }) } var searchServer = function(data){ $.ajax({ url: 'search', method: 'post', dataType: 'html', data: {search_input: data} }).done(function(responseData){ displayResults(responseData); unendorseListener(); }) } var displayResults = function(responseData){ $('.tab-content').html(responseData) }
// # Place all the behaviors and hooks related to the matching controller here. // # All this logic will automatically be available in application.js. // # You can use CoffeeScript in this file: http://coffeescript.org/ $(document).ready(function(){ bindSearchBySubmit(); bindSearchByButton(); }) var bindSearchBySubmit = function(){ $('form.navbar-form').on('submit', function(event){ event.preventDefault(); var data = $("#peopleSearchBar").val(); searchServer(data); }) } var bindSearchByButton = function(){ $('form.navbar-form').on('click','.glyphicon-search', function(event){ event.preventDefault(); var data = $("#peopleSearchBar").val(); searchServer(data); }) } var searchServer = function(data){ $.ajax({ url: 'search', method: 'post', dataType: 'html', data: {search_input: data} }).done(function(responseData){ displayResults(responseData); unendorseListener(); }) } var displayResults = function(responseData){ $('.tab-content').html(responseData) }
Add support IAM Role credentials
package myaws import ( "net/http" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/spf13/viper" ) func NewConfig() *aws.Config { return &aws.Config{ Credentials: newCredentials(viper.GetString("profile")), Region: getRegion(viper.GetString("region")), } } func newCredentials(profile string) *credentials.Credentials { return credentials.NewChainCredentials( []credentials.Provider{ &credentials.SharedCredentialsProvider{ Profile: profile, }, &credentials.EnvProvider{}, &ec2rolecreds.EC2RoleProvider{ Client: ec2metadata.New(session.New(&aws.Config{ HTTPClient: &http.Client{Timeout: 3000 * time.Millisecond}, }, )), }, }) } func getRegion(region string) *string { if region != "" { return aws.String(region) } else { return aws.String(os.Getenv("AWS_DEFAULT_REGION")) } }
package myaws import ( "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/spf13/viper" ) func NewConfig() *aws.Config { return &aws.Config{ Credentials: newCredentials(viper.GetString("profile")), Region: getRegion(viper.GetString("region")), } } func newCredentials(profile string) *credentials.Credentials { if profile != "" { return credentials.NewSharedCredentials("", profile) } else { return credentials.NewEnvCredentials() } } func getRegion(region string) *string { if region != "" { return aws.String(region) } else { return aws.String(os.Getenv("AWS_DEFAULT_REGION")) } }
Add Core Views import to the application
import os from flask import Flask from flask.ext.assets import Bundle, Environment app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) assets.load_path = [ os.path.join(os.path.dirname(__file__), 'static'), os.path.join(os.path.dirname(__file__), 'static', 'bower_components') ] assets.register( 'js_all', Bundle( 'jquery/dist/jquery.min.js', 'bootstrap/dist/js/bootstrap.min.js', output='js_all.js' ) ) assets.register( 'css_all', Bundle( 'bootstrap/dist/css/bootstrap.css', 'bootstrap/dist/css/bootstrap-theme.css', 'css/ignition.css', output='css_all.css' ) ) from manager.views import core
import os from flask import Flask from flask.ext.assets import Bundle, Environment app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) assets.load_path = [ os.path.join(os.path.dirname(__file__), 'static'), os.path.join(os.path.dirname(__file__), 'static', 'bower_components') ] assets.register( 'js_all', Bundle( 'jquery/dist/jquery.min.js', 'bootstrap/dist/js/bootstrap.min.js', output='js_all.js' ) ) assets.register( 'css_all', Bundle( 'bootstrap/dist/css/bootstrap.css', 'bootstrap/dist/css/bootstrap-theme.css', 'css/ignition.css', output='css_all.css' ) )
Bring version number up to date.
#!/usr/bin/env python3.8 # Copyright (C) 2017-2019 Andrew Hamilton. All rights reserved. # Licensed under the Artistic License 2.0. try: from setuptools import setup except ImportError: from distutils.core import setup setup(name="eris", version="20.04", description=("Eris maintains an up-to-date set of reports for every" " file in a codebase."), url="https://github.com/ahamilton/eris", author="Andrew Hamilton", license="Artistic 2.0", packages=["eris", "eris.urwid"], package_data={"eris": ["LS_COLORS.sh", "tools.toml"]}, entry_points={"console_scripts": ["eris=eris.__main__:entry_point", "eris-worker=eris.worker:main", "eris-webserver=eris.webserver:main", "pydoc_color=eris.pydoc_color:main"]})
#!/usr/bin/env python3.8 # Copyright (C) 2017-2019 Andrew Hamilton. All rights reserved. # Licensed under the Artistic License 2.0. try: from setuptools import setup except ImportError: from distutils.core import setup setup(name="eris", version="18.12", description=("Eris maintains an up-to-date set of reports for every" " file in a codebase."), url="https://github.com/ahamilton/eris", author="Andrew Hamilton", license="Artistic 2.0", packages=["eris", "eris.urwid"], package_data={"eris": ["LS_COLORS.sh", "tools.toml"]}, entry_points={"console_scripts": ["eris=eris.__main__:entry_point", "eris-worker=eris.worker:main", "eris-webserver=eris.webserver:main", "pydoc_color=eris.pydoc_color:main"]})
Update virtool.caches docstrings and typing
""" Utilities used for working with cache files within analysis workflows. """ import os from typing import Union import virtool.samples.utils def join_cache_path(settings: dict, cache_id: str): """ Create a cache path string given the application settings and cache id. :param settings: the application settings :param cache_id: the id of the cache :return: a cache path """ return os.path.join(settings["data_path"], "caches", cache_id) def join_cache_read_paths(settings: dict, cache: dict) -> Union[list, None]: """ Return a list of read paths for a cache given the application settings and the cache document. The path list will contain two paths if paired, and one if not. :param settings: the application settings :param cache: a cache document :return: a list of read paths """ if not cache: return None cache_path = join_cache_path(settings, cache["id"]) return virtool.samples.utils.join_read_paths(cache_path, cache["paired"])
import os from typing import Union import virtool.samples.utils def join_cache_path(settings: dict, cache_id: str): """ Create a cache path string given the application settings and cache id. :param settings: the application settings :param cache_id: the id of the cache :return: a cache path """ return os.path.join(settings["data_path"], "caches", cache_id) def join_cache_read_paths(settings: dict, cache: dict) -> Union[list, None]: """ Return a list of read paths for a cache given the application settings and the cache document. The path list will contain two paths if paired, and one if not. :param settings: the application settings :param cache: a cache document :return: a list of read paths """ if not cache: return None cache_path = join_cache_path(settings, cache["id"]) return virtool.samples.utils.join_read_paths(cache_path, cache["paired"])
Tidy up code a little
package uploader import ( "errors" "github.com/matthew-andrews/s3up/objects" "sync" ) type s3ClientInterface interface { UploadFile(string, objects.File) error } func Upload(service s3ClientInterface, bucket string, files []objects.File, concurrency int) []error { if len(files) < 1 { return []error{errors.New("No files found for upload to S3. (Directories are ignored)")} } ec := make(chan error, len(files)) sem := make(chan bool, concurrency) var wg sync.WaitGroup for _, file := range files { wg.Add(1) sem <- true go func(file objects.File) { defer wg.Done() defer func() { <-sem }() if err := service.UploadFile(bucket, file); err != nil { ec <- err } }(file) } wg.Wait() close(ec) var errs []error if len(ec) > 0 { for err := range ec { errs = append(errs, err) } } return errs }
package uploader import ( "errors" "github.com/matthew-andrews/s3up/objects" "sync" ) type s3ClientInterface interface { UploadFile(string, objects.File) error } func Upload(service s3ClientInterface, bucket string, files []objects.File, concurrency int) []error { ec := make(chan error, len(files)) if len(files) < 1 { return []error{errors.New("No files found for upload to S3. (Directories are ignored)")} } var sem = make(chan bool, concurrency) var wg sync.WaitGroup for _, file := range files { wg.Add(1) sem <- true go func(file objects.File) { defer wg.Done() defer func() { <-sem }() if err := service.UploadFile(bucket, file); err != nil { ec <- err } }(file) } wg.Wait() close(ec) var errs []error if len(ec) > 0 { for err := range ec { errs = append(errs, err) } } return errs }
Make year range arguments optional in search
import scholarly import requests _EXACT_SEARCH = '/scholar?q="{}"' _START_YEAR = '&as_ylo={}' _END_YEAR = '&as_yhi={}' def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" url = _EXACT_SEARCH.format(requests.utils.quote(query)) if start_year: url += _START_YEAR.format(start_year) if end_year: url += _END_YEAR.format(end_year) soup = scholarly._get_soup(url) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
import scholarly import requests _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' def search(query, start_year, end_year): """Search by scholar query and return a generator of Publication objects""" soup = scholarly._get_soup( _SEARCH.format(requests.utils.quote(query), str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", 2015, 2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
Add github3.py to the requirements
from setuptools import setup, find_packages import inbox requirements = [ "click", "github3.py", ] setup( name="inbox", version=inbox.__version__, url='TODO', description=inbox.__doc__, author=inbox.__author__, license=inbox.__license__, long_description="TODO", packages=find_packages(), install_requires=requirements, entry_points={ 'console_scripts': [ 'inbox = inbox.__main__:inbox' ] }, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Customer Service", "Intended Audience :: End Users/Desktop", "Intended Audience :: Information Technology", "Intended Audience :: Other Audience", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet", "Topic :: Office/Business", "Topic :: Utilities", ], keywords='inbox github notifications', )
from setuptools import setup, find_packages import inbox requirements = [ "click", ] setup( name="inbox", version=inbox.__version__, url='TODO', description=inbox.__doc__, author=inbox.__author__, license=inbox.__license__, long_description="TODO", packages=find_packages(), install_requires=requirements, entry_points={ 'console_scripts': [ 'inbox = inbox.__main__:inbox' ] }, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Customer Service", "Intended Audience :: End Users/Desktop", "Intended Audience :: Information Technology", "Intended Audience :: Other Audience", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet", "Topic :: Office/Business", "Topic :: Utilities", ], keywords='inbox github notifications', )
Change some errors to go to stderr. These non-fatal errors violated GTP protocol.
# Copyright 2018 Google LLC # # 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 google.cloud.logging as glog import logging import contextlib import io import sys import os LOGGING_PROJECT = os.environ.get('LOGGING_PROJECT', '') def configure(project=LOGGING_PROJECT): if not project: sys.stderr.write('!! Error: The $LOGGING_PROJECT enviroment ' 'variable is required in order to set up cloud logging. ' 'Cloud logging is disabled.\n') return logging.basicConfig(level=logging.INFO) try: # if this fails, redirect stderr to /dev/null so no startup spam. with contextlib.redirect_stderr(io.StringIO()): client = glog.Client(project) client.setup_logging(logging.INFO) except: sys.stderr.write('!! Cloud logging disabled\n')
# Copyright 2018 Google LLC # # 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 google.cloud.logging as glog import logging import contextlib import io import sys import os LOGGING_PROJECT = os.environ.get('LOGGING_PROJECT', '') def configure(project=LOGGING_PROJECT): if not project: print('!! Error: The $LOGGING_PROJECT enviroment ' 'variable is required in order to set up cloud logging. ' 'Cloud logging is disabled.') return logging.basicConfig(level=logging.INFO) try: # if this fails, redirect stderr to /dev/null so no startup spam. with contextlib.redirect_stderr(io.StringIO()): client = glog.Client(project) client.setup_logging(logging.INFO) except: print('!! Cloud logging disabled')
Implement platformAppName() and platformHideApp(), panic on use of platformHideOtherApps() or platformShowAllApps().
// Copyright (c) 2016 by Richard A. Wilkes. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, version 2.0. If a copy of the MPL was not distributed with // this file, You can obtain one at http://mozilla.org/MPL/2.0/. // // This Source Code Form is "Incompatible With Secondary Licenses", as // defined by the Mozilla Public License, version 2.0. package app import ( "github.com/richardwilkes/ui/menu/custom" "os" "path/filepath" ) func platformStartUserInterface() { custom.Install() // RAW: Implement for Windows } func platformAppName() string { return filepath.Base(os.Args[0]) } func platformHideApp() { for _, wnd := range window.Windows() { wnd.Minimize() } } func platformHideOtherApps() { panic("platformHideOtherApps() is not implemented") } func platformShowAllApps() { panic("platformShowAllApps() is not implemented") }
// Copyright (c) 2016 by Richard A. Wilkes. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, version 2.0. If a copy of the MPL was not distributed with // this file, You can obtain one at http://mozilla.org/MPL/2.0/. // // This Source Code Form is "Incompatible With Secondary Licenses", as // defined by the Mozilla Public License, version 2.0. package app import ( "github.com/richardwilkes/ui/menu/custom" ) func platformStartUserInterface() { custom.Install() // RAW: Implement for Windows } func platformAppName() string { // RAW: Implement platformAppName for Windows return "<unknown>" } func platformHideApp() { // RAW: Implement for Windows } func platformHideOtherApps() { // RAW: Implement for Windows } func platformShowAllApps() { // RAW: Implement for Windows } func platformAttemptQuit() { // RAW: Implement for Windows } func platformAppMayQuitNow(quit bool) { // RAW: Implement for Windows }
Update the sort arrow heads.
/** * @fileoverview DatatableHeader.js * Pure component that renders the header of the table. */ import React from 'react'; import { DatatableHeaderPropTypes } from '../PropTypes.js'; const DatatableHeader = ({ columns, onSort, sort }) => <thead> <tr> {columns.map(c => <th key={c.key} onClick={c.sort ? (e) => onSort(e, c) : undefined} style={{ cursor: c.sort ? 'pointer' : 'default' }} > {sort.sortColumn === c.key ? <span style={{ fontSize: '0.6rem' }}>{sort.sortOrder ? '▼ ' : '▲ '}</span> : '' } {c.label} </th> )} </tr> </thead> DatatableHeader.propTypes = DatatableHeaderPropTypes; export default DatatableHeader;
/** * @fileoverview DatatableHeader.js * Pure component that renders the header of the table. */ import React from 'react'; import { DatatableHeaderPropTypes } from '../PropTypes.js'; const DatatableHeader = ({ columns, onSort, sort }) => <thead> <tr> {columns.map(c => <th key={c.key} onClick={c.sort ? (e) => onSort(e, c) : undefined} style={{ cursor: c.sort ? 'pointer' : 'default' }} > {sort.sortColumn === c.key ? (sort.sortOrder ? '▾ ' : '▴ ') : ''}{c.label} </th> )} </tr> </thead> DatatableHeader.propTypes = DatatableHeaderPropTypes; export default DatatableHeader;
Make ORG_TITLE the complete pre-existing title.
# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY. # The app name will be used in several places. APP_NAME = 'Yelp Love' APP_BASE_URL = 'https://PROJECT_ID.appspot.com/' LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>' # Flask's secret key, used to encrypt the session cookie. # Set this to any random string and make sure not to share this! SECRET_KEY = 'YOUR_SECRET_HERE' # Use default theme THEME = 'default' # Every employee needs a reference to a Google Account. This reference is based on the users # Google Account email address and created when employee data is imported: we take the *username* # and this DOMAIN DOMAIN = 'example.com' # Name of the S3 bucket used to import employee data from a file named employees.json # Check out /import/employees.json.example to see how this file should look like. S3_BUCKET = 'employees' # When do we use Gravatar? Options are: # * 'always' - prefers Gravatar over the Employee.photo_url # * 'backup' - use Gravatar when photo_url is empty # * anything else - disabled GRAVATAR = 'backup' ORG_TITLE = "All Company"
# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY. # The app name will be used in several places. APP_NAME = 'Yelp Love' APP_BASE_URL = 'https://PROJECT_ID.appspot.com/' LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>' # Flask's secret key, used to encrypt the session cookie. # Set this to any random string and make sure not to share this! SECRET_KEY = 'YOUR_SECRET_HERE' # Use default theme THEME = 'default' # Every employee needs a reference to a Google Account. This reference is based on the users # Google Account email address and created when employee data is imported: we take the *username* # and this DOMAIN DOMAIN = 'example.com' # Name of the S3 bucket used to import employee data from a file named employees.json # Check out /import/employees.json.example to see how this file should look like. S3_BUCKET = 'employees' # When do we use Gravatar? Options are: # * 'always' - prefers Gravatar over the Employee.photo_url # * 'backup' - use Gravatar when photo_url is empty # * anything else - disabled GRAVATAR = 'backup' ORG_TITLE = "Company"
Disable Vue.cong.strict until all views are fixed for it
'use strict'; /** * Styles */ require('../less/admin.less'); // Ensure Babel/ES6 polyfills are loaded require('babel-core/polyfill'); // Catch all errors require('raven'); var $ = require('jquery'); require('bootstrap'); var Vue = require('vue'), config = require('config'); // Ensure retrocompatibily for 0.12.2 replace behavior Vue.options.replace = false; Vue.config.debug = config.debug; Vue.use(require('plugins/util')); Vue.use(require('plugins/text')); Vue.use(require('plugins/jquery')); Vue.use(require('plugins/i18next')); Vue.use(require('plugins/markdown')); Vue.use(require('plugins/scroll-to')); Vue.use(require('plugins/router'), {prefix: config.root}); $(require('api')).on('built', function() { var app = new Vue(require('app.vue')); app.$mount('#app'); });
'use strict'; /** * Styles */ require('../less/admin.less'); // Ensure Babel/ES6 polyfills are loaded require('babel-core/polyfill'); // Catch all errors require('raven'); var $ = require('jquery'); require('bootstrap'); var Vue = require('vue'), config = require('config'); // Ensure retrocompatibily for 0.12.2 replace behavior Vue.options.replace = false; Vue.config.strict = true; Vue.config.debug = config.debug; Vue.use(require('plugins/util')); Vue.use(require('plugins/text')); Vue.use(require('plugins/jquery')); Vue.use(require('plugins/i18next')); Vue.use(require('plugins/markdown')); Vue.use(require('plugins/scroll-to')); Vue.use(require('plugins/router'), {prefix: config.root}); $(require('api')).on('built', function() { var app = new Vue(require('app.vue')); app.$mount('#app'); });
Update clean method to ensure that meal end_time is not same as or less than meal start_time
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.')) super().clean() def __str__(self): return self.name
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) def __str__(self): return self.name class Meal(ForceCapitalizeMixin, models.Model): """ Model representing food occasions. This represents an occasion during the day that food is scheduled to be served. E.g breakfast, lunch, etc. """ name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() capitalized_field_names = ('name',) def __str__(self): return self.name
Make travis happy & make my need for semicolons happy ;)
var util = require("util") , EventEmitter = require("events").EventEmitter; module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter); CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct); return this; } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct); return this; } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }); return this; } return CustomEventEmitter; })();
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
Add checks for buggy goprotobuf.
// Copyright (c) 2010 The Grumble Authors // The use of this source code is goverened by a BSD-style // license that can be found in the LICENSE-file. package main import ( "flag" "fmt" "os" "log" "mumbleproto" "goprotobuf.googlecode.com/hg/proto" ) var help *bool = flag.Bool("help", false, "Show this help") var port *int = flag.Int("port", 64738, "Default port to listen on") var host *string = flag.String("host", "0.0.0.0", "Default host to listen on") func usage() { fmt.Fprintf(os.Stderr, "usage: grumble [options]\n") flag.PrintDefaults() } // Check that we're using a version of goprotobuf that is able to // correctly encode empty byte slices. func checkProtoLib() { us := &mumbleproto.UserState{} us.Texture = []byte{} d, _ := proto.Marshal(us) nus := &mumbleproto.UserState{} proto.Unmarshal(d, nus) if nus.Texture == nil { log.Exitf("Unpatched version of goprotobuf. Grumble is refusing to run.") } } func main() { flag.Parse() if *help == true { usage() return } checkProtoLib() // Create our default server m, err := NewServer(*host, *port) if err != nil { return } // And launch it. go m.ListenAndMurmur() // Listen forever sleeper := make(chan int) zzz := <-sleeper if zzz > 0 { } }
// Copyright (c) 2010 The Grumble Authors // The use of this source code is goverened by a BSD-style // license that can be found in the LICENSE-file. package main import ( "flag" "fmt" "os" ) var help *bool = flag.Bool("help", false, "Show this help") var port *int = flag.Int("port", 64738, "Default port to listen on") var host *string = flag.String("host", "0.0.0.0", "Default host to listen on") func usage() { fmt.Fprintf(os.Stderr, "usage: grumble [options]\n") flag.PrintDefaults() } func main() { flag.Parse() if *help == true { usage() return } // Create our default server m, err := NewServer(*host, *port) if err != nil { return } // And launch it. go m.ListenAndMurmur() // Listen forever sleeper := make(chan int) zzz := <-sleeper if zzz > 0 { } }
Remove space between flag and password
#!/usr/bin/env node var exec = require('child_process').exec; var dbconfig = require(process.cwd() + '/config/database'); var envconfig = dbconfig[process.env.FP_NODE_ENV]; if (!envconfig) throw('invalid environment variable'); function parse (value) { if (typeof(value) == 'object') { return process.env[value.ENV]; } else { return value; } } var user = parse(envconfig.user), host = parse(envconfig.host), port = parse(envconfig.port), pass = parse(envconfig.password), db = parse(envconfig.database); if (!db) throw('Database name must be specified in an environment variable.'); var query = 'psql -c "CREATE DATABASE ' + db + ';"'; if (user) query += ' -U ' + user; if (host) query += ' -h ' + host; if (port) query += ' -p ' + port; if (pass) query += ' -w' + pass; exec(query, function (err, res) { if (err) throw(err); console.log(res); console.log(db + ' database created successfully!'); });
#!/usr/bin/env node var exec = require('child_process').exec; var dbconfig = require(process.cwd() + '/config/database'); var envconfig = dbconfig[process.env.FP_NODE_ENV]; if (!envconfig) throw('invalid environment variable'); function parse (value) { if (typeof(value) == 'object') { return process.env[value.ENV]; } else { return value; } } var user = parse(envconfig.user), host = parse(envconfig.host), port = parse(envconfig.port), pass = parse(envconfig.password), db = parse(envconfig.database); if (!db) throw('Database name must be specified in an environment variable.'); var query = 'psql -c "CREATE DATABASE ' + db + ';"'; if (user) query += ' -U ' + user; if (host) query += ' -h ' + host; if (port) query += ' -p ' + port; if (pass) query += ' -w ' + pass; exec(query, function (err, res) { if (err) throw(err); console.log(res); console.log(db + ' database created successfully!'); });
TAPESTRY-1828: Convert uses of @InjectService to be @Inject plus a marker annotation git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@589400 13f79535-47bb-0310-9956-ffa450edef68
// Copyright 2007 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.ioc.annotations; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.apache.tapestry.ioc.services.ChainBuilder; import org.apache.tapestry.ioc.services.StrategyBuilder; /** * Marker annotation used to denote a service that is the primary instance of some common interface. * This is often used when a service is a {@linkplain ChainBuilder chain of command} or * {@linkplain StrategyBuilder strategy-based} and, therefore, many services will implement the same * interface. */ @Target( { PARAMETER, FIELD }) @Retention(RUNTIME) @Documented public @interface Primary { }
// Copyright 2007 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.ioc.annotations; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.apache.tapestry.ioc.services.ChainBuilder; import apple.awt.StrategyBufferImage; /** * Marker annotation used to denote a service that is the primary instance of some common interface. * This is often used when a service is a {@linkplain ChainBuilder chain of command} or * {@linkplain StrategyBufferImage strategy-based} and, therefore, many services will implement the * same interface. */ @Target( { PARAMETER, FIELD }) @Retention(RUNTIME) @Documented public @interface Primary { }
Use verbose method name to avoid conflict with implementing class. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Orchestra\Support\Str; trait UploadableTrait { /** * Save uploaded file into directory. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string $path * @return string */ protected function saveUploadedFile(UploadedFile $file, $path) { $file->move($path, $filename = $this->getUploadedFilename($file)); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function deleteUploadedFile($file) { return File::delete($file); } /** * Get uploaded filename. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return string */ protected function getUploadedFilename(UploadedFile $file) { $extension = $file->getClientOriginalExtension(); return Str::random(10).".{$extension}"; } }
<?php namespace Orchestra\Support\Traits; use Orchestra\Support\Str; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; trait UploadableTrait { /** * Save uploaded file into directory * * @param use Symfony\Component\HttpFoundation\File\UploadedFile * @param string $path * @return string */ protected function save(UploadedFile $file, $path) { $extension = $file->getClientOriginalExtension(); $filename = Str::random(10).".{$extension}"; $file->move($path, $filename); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function delete($file) { return File::delete($file); } }
Make search indexer a command line application svn commit r12184
<?php require_once 'Site/SiteCommandLineApplication.php'; require_once 'Site/SiteDatabaseModule.php'; require_once 'Site/SiteConfigModule.php'; require_once 'SwatDB/SwatDB.php'; /** * Abstract base class for a search indexer applications * * @package Site * @copyright 2006 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ abstract class SiteSearchIndexer extends SiteCommandLineApplication { // {{{ public properties /** * A convenience reference to the database object * * @var MDB2_Driver */ public $db; // }}} // {{{ protected function getDefaultModuleList() /** * Gets the list of modules to load for this search indexer * * @return array the list of modules to load for this application. * * @see SiteApplication::getDefaultModuleList() */ protected function getDefaultModuleList() { return array( 'config' => 'SiteConfigModule', 'database' => 'SiteDatabaseModule', ); } // }}} } ?>
<?php require_once 'Site/SiteApplication.php'; require_once 'Site/SiteDatabaseModule.php'; require_once 'Site/SiteConfigModule.php'; require_once 'SwatDB/SwatDB.php'; /** * Abstract base class for a search indexer applications * * @package Site * @copyright 2006 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ abstract class SiteSearchIndexer extends SiteApplication { // {{{ public properties /** * A convenience reference to the database object * * @var MDB2_Driver */ public $db; // }}} // {{{ public function init() /** * Initializes the modules of this application and sets up the database * convenience reference */ public function init() { $this->initModules(); $this->db = $this->database->getConnection(); } // }}} // {{{ public abstract function index() /** * Indexes search data intended to be indexed by this indexer */ public abstract function index(); // }}} // {{{ protected function getDefaultModuleList() /** * Gets the list of modules to load for this search indexer * * @return array the list of modules to load for this application. * * @see SiteApplication::getDefaultModuleList() */ protected function getDefaultModuleList() { return array( 'config' => 'SiteConfigModule', 'database' => 'SiteDatabaseModule', ); } // }}} } ?>
Add search by name to dicts
# coding: utf-8 from django.forms.models import modelform_factory from django.http import Http404 from dartcms import get_model from dartcms.views import GridView, InsertObjectView, UpdateObjectView, DeleteObjectView class DictsFormMixin(object): def get_form_class(self): return modelform_factory(self.model, exclude=[]) def get_model(self): app_label = self.kwargs['app_label'] model_name = self.kwargs['model_name'].replace('_', ' ').title().replace(' ', '') try: return get_model(app_label, model_name) except: raise Http404('Model %s not found' % model_name) def dispatch(self, request, *args, **kwargs): self.model = self.get_model() return super(DictsFormMixin, self).dispatch(request, *args, **kwargs) class GridDictsView(DictsFormMixin, GridView): search = ['name'] class InsertDictsView(DictsFormMixin, InsertObjectView): pass class UpdateDictsView(DictsFormMixin, UpdateObjectView): pass class DeleteDictsView(DictsFormMixin, DeleteObjectView): pass
# coding: utf-8 from django.forms.models import modelform_factory from django.http import Http404 from dartcms import get_model from dartcms.views import GridView, InsertObjectView, UpdateObjectView, DeleteObjectView class DictsFormMixin(object): def get_form_class(self): return modelform_factory(self.model, exclude=[]) def get_model(self): app_label = self.kwargs['app_label'] model_name = self.kwargs['model_name'].replace('_', ' ').title().replace(' ', '') try: return get_model(app_label, model_name) except: raise Http404('Model %s not found' % model_name) def dispatch(self, request, *args, **kwargs): self.model = self.get_model() return super(DictsFormMixin, self).dispatch(request, *args, **kwargs) class GridDictsView(DictsFormMixin, GridView): pass class InsertDictsView(DictsFormMixin, InsertObjectView): pass class UpdateDictsView(DictsFormMixin, UpdateObjectView): pass class DeleteDictsView(DictsFormMixin, DeleteObjectView): pass
Tidy up missing message util linting issues
import Ember from 'ember'; import Locale from 'ember-i18n/utils/locale'; import config from '../../config/environment'; const DEFAULT_LOCALE = config.i18n.defaultLocale; let missingMessage = function(locale, key, data) { if (locale === DEFAULT_LOCALE || window.env === 'development') { return `Missing translation: ${key}`; } else { Ember.Logger.warn(`Missing translation: ${key}`); // NOTE This relies on internal APIs and is brittle. // Emulating the internals of ember-i18n's translate method let i18n = this; let count = Ember.get(data, 'count'); let defaults = Ember.makeArray(Ember.get(data, 'default')); defaults.unshift(key); let localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n)); let template = localeObj.getCompiledTemplate(defaults, count); return template(data); } }; export default missingMessage;
import Ember from 'ember'; import Locale from 'ember-i18n/utils/locale'; import config from '../../config/environment'; const DEFAULT_LOCALE = config.i18n.defaultLocale; let missingMessage = function(locale, key, data) { console.log(locale) if (locale === DEFAULT_LOCALE || window.env === 'development') { return `Missing translation: ${key}`; } else { Ember.Logger.warn("Missing translation: " + key); // NOTE This relies on internal APIs and is brittle. // Emulating the internals of ember-i18n's translate method const i18n = this; const count = Ember.get(data, 'count'); const defaults = Ember.makeArray(Ember.get(data, 'default')); defaults.unshift(key); const localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n)); const template = localeObj.getCompiledTemplate(defaults, count); return template(data); } }; export default missingMessage;
Cut down version of the full test suite pending scanning and configured support
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.mockwire.guice2; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import net.stickycode.mockwire.FieldBlessingTest; import net.stickycode.mockwire.FieldMockingTest; import net.stickycode.mockwire.UnblessableTypesTest; @RunWith(Suite.class) @SuiteClasses({ FieldBlessingTest.class, FieldMockingTest.class, UnblessableTypesTest.class }) public class MockwireTckTest { /** * This is an anchor for Infinitest to rerun this suite if its changes */ GuiceIsolatedTestManifest anchor; }
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.mockwire.guice2; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import net.stickycode.mockwire.MockwireTck; import net.stickycode.mockwire.direct.MockwireDirectTck; import net.stickycode.mockwire.junit4.MockwireRunnerTck; @RunWith(Suite.class) @SuiteClasses({ MockwireTck.class, MockwireDirectTck.class, MockwireRunnerTck.class }) public class MockwireTckTest { }
Modify toString method for board array format
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { this.board.forEach(function(row) { console.log(row.join('')); }); }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { for( var i = 0; i < 16; i += 4){ this.array = this.board.slice(0 + i, 4 + i) console.log(this.array) } }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
Remove redundant @ExtendWith(SpringExtension.class) for sample See gh-32476
/* * Copyright 2012-2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.testing.springbootapplications.jmx; import javax.management.MBeanServer; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(properties = "spring.jmx.enabled=true") @DirtiesContext class MyJmxTests { @Autowired private MBeanServer mBeanServer; @Test void exampleTest() { assertThat(this.mBeanServer.getDomains()).contains("java.lang"); // ... } }
/* * Copyright 2012-2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.testing.springbootapplications.jmx; import javax.management.MBeanServer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @SpringBootTest(properties = "spring.jmx.enabled=true") @DirtiesContext class MyJmxTests { @Autowired private MBeanServer mBeanServer; @Test void exampleTest() { assertThat(this.mBeanServer.getDomains()).contains("java.lang"); // ... } }
Set maxBuffer when spawning child process
var path = require('path') var exec = require('child_process').exec var chdir = require('chdir') module.exports = function (config, cb) { if (!config.source) { cb(new Error('Source folder not provided')) return null } config.source = path.resolve(config.source) if (!config.dest) { config.dest = config.source } else { config.dest = path.resolve(config.dest) } if (!config.name) { config.name = path.basename(config.source) } chdir(config.source, function () { var zip_name = path.join(config.dest, config.name + '.zip') exec('zip -r ' + zip_name + ' ./', { maxBuffer: 1024 * 500 }, function (err, result) { if (err) { cb(err) return null } cb(null, zip_name) }) }) }
var path = require('path') var exec = require('child_process').exec var chdir = require('chdir') module.exports = function (config, cb) { if (!config.source) { cb(new Error('Source folder not provided')) return null } config.source = path.resolve(config.source) if (!config.dest) { config.dest = config.source } else { config.dest = path.resolve(config.dest) } if (!config.name) { config.name = path.basename(config.source) } chdir(config.source, function () { var zip_name = path.join(config.dest, config.name + '.zip') exec('zip -r ' + zip_name + ' ./', function(err, result) { if (err) { cb(err) return null } cb(null, zip_name) }) }) }
Allow configuration of the WebSocket constructor
var boombox = require('boombox'); var test = boombox(require('tape')); var signaller = require('rtc-signaller'); var reTrailingSlash = /\/$/; module.exports = function(opts) { // initialise the server var server = (opts || {}).server || 'http://rtc.io/switchboard'; // determine the WebSocket constructor var WS = (opts || {}).WebSocket || (typeof WebSocket != 'undefined' ? WebSocket : require('ws')); // initialise the ws endpoint var endpoint = (opts || {}).endpoint || '/primus'; var socket; test('create the socket connection', function(t) { t.plan(1); // create a websocket connection to the target server socket = new WS(server.replace(reTrailingSlash, '') + endpoint); t.ok(socket instanceof WS, 'websocket instance created'); }); test('socket opened', function(t) { t.plan(1); socket.once('open', t.pass.bind(t, 'socket open')); }); test('close connection', function(t) { t.plan(1); socket.close(); t.pass('closed'); }); };
var boombox = require('boombox'); var test = boombox(require('tape')); var signaller = require('rtc-signaller'); var WebSocket = require('ws'); var reTrailingSlash = /\/$/; module.exports = function(opts) { // initialise the server var server = (opts || {}).server || 'http://rtc.io/switchboard'; // initialise the ws endpoint var endpoint = (opts || {}).endpoint || '/primus'; var socket; test('create the socket connection', function(t) { t.plan(1); // create a websocket connection to the target server socket = new WebSocket(server.replace(reTrailingSlash, '') + endpoint); t.ok(socket instanceof WebSocket, 'websocket instance created'); }); test('socket opened', function(t) { t.plan(1); socket.once('open', t.pass.bind(t, 'socket open')); }); test('close connection', function(t) { t.plan(1); socket.close(); t.pass('closed'); }); };
Add mixing percentage to display
Handlebars.registerHelper('color', function(color) { var nameText = ''; var hex = color.hex; var colorPickerLink = 'https://duckduckgo.com/?q=color+picker+' + encodeURIComponent(hex); if (color.name !== '') { nameText = ' (' + color.name + ')'; } var amountText = ''; if (color.amount !== undefined) { var pct = Number(sprintf('%.2f', color.amount * 100)). toLocaleString(); amountText = '<span>(' + pct + '%)</span> '; } var href = 'href="' + colorPickerLink + '"'; var hexBody = '<a class="rgb_color--link" ' + href + '>' + hex + nameText + '</a>'; var boxBody = '<a class="rgb_color--link rgb_color--color-box" ' + href + ' style="color:' + hex + '">&#9632</a>'; var body = '<span>' + amountText + hexBody + ' ' + boxBody + '</span>'; return body; });
Handlebars.registerHelper('color', function(color) { var nameText = ''; var hex = color.hex; var colorPickerLink = 'https://duckduckgo.com/?q=color+picker+' + encodeURIComponent(hex); if (color.name !== '') { nameText = ' (' + color.name + ')'; } var href = 'href="' + colorPickerLink + '"'; var hexBody = '<a class="rgb_color--link" ' + href + '>' + hex + nameText + '</a>'; var boxBody = '<a class="rgb_color--link rgb_color--color-box" ' + href + ' style="color:' + hex + '">&#9632</a>'; var body = '<span>' + hexBody + ' ' + boxBody + '</span>'; return body; });
Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') parser.add_argument('--max-empty-rows', dest="max_empty_rows") args = parser.parse_args() if False == os.path.isfile(args.file): print("File does not exist") sys.exit(1) workbook = xlrd.open_workbook(args.file) sheet = workbook.sheet_by_index(0) if args.action == "count": print(sheet.nrows) elif args.action == "read": reached_end = False rows = [] while len(rows) < int(args.size) and reached_end == False: try: rows.append(sheet.row_values(int(args.start) + len(rows) - 1)) except IndexError: reached_end = True print(json.dumps(rows)) else: print("Unknown command") sys.exit(1) if __name__ == "__main__": run(sys.argv[1:])
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') args = parser.parse_args() if False == os.path.isfile(args.file): print("File does not exist") sys.exit(1) workbook = xlrd.open_workbook(args.file) sheet = workbook.sheet_by_index(0) if args.action == "count": print(sheet.nrows) elif args.action == "read": reached_end = False rows = [] while len(rows) < int(args.size) and reached_end == False: try: rows.append(sheet.row_values(int(args.start) + len(rows) - 1)) except IndexError: reached_end = True print(json.dumps(rows)) else: print("Unknown command") sys.exit(1) if __name__ == "__main__": run(sys.argv[1:])
Remove the DoctrineBundle from the testing embeded kernel.
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Leg\GoogleChartsBundle\LegGoogleChartsBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Leg\GoogleChartsBundle\LegGoogleChartsBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
Use DIC to get home route from config
<?php namespace Libs; use \Core\App; use \Core\Config; use \Libs\interfaces\SessionInterface; class Redirect { protected $session; public function __construct(SessionInterface $session) { $this->session = $session; } public function back() { if(array_key_exists('HTTP_REFERER', $_SERVER)) { header('Location: ' . $_SERVER['HTTP_REFERER']); } else { $this->home(); } } public function backWithInput($input) { $this->session->set('input', $input); $this->back(); } public function to($url) { header('Location: ' . WEBROOT. $url); } public function home() { $config = App::get('Core\Config'); $this->to($config->get('home_route')); } }
<?php namespace Libs; use \Core\Config; use \Libs\interfaces\SessionInterface; class Redirect { protected $session; public function __construct(SessionInterface $session) { $this->session = $session; } public function back() { if(array_key_exists('HTTP_REFERER', $_SERVER)) { header('Location: ' . $_SERVER['HTTP_REFERER']); } else { $this->home(); } } public function backWithInput($input) { $this->session->set('input', $input); $this->back(); } public function to($url) { header('Location: ' . WEBROOT. $url); } public function home() { $config = Config::getInstance(); $this->to($config->get('default_controller') . '/' . $config->get('default_method')); } }
Fix regex for registration url
from project.api.views import ChannelViewSet, MessageViewSet, UserViewSet from django.conf.urls import url, include from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from rest_framework.schemas import get_schema_view from rest_framework.authtoken import views schema_view = get_schema_view(title='Grailed API') # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'channels', ChannelViewSet) router.register(r'messages', MessageViewSet) # The API URLs are now determined automatically by the router. # Additionally, we include the login URLs for the browsable API. urlpatterns = [ url(r'^schema/$', schema_view), url(r'^', include(router.urls)), url(r'^', include('rest_auth.urls')), url(r'^registration/', include('rest_auth.registration.urls')), url(r'^api-token-auth/', views.obtain_auth_token), # fet token with username and password ]
from project.api.views import ChannelViewSet, MessageViewSet, UserViewSet from django.conf.urls import url, include from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from rest_framework.schemas import get_schema_view from rest_framework.authtoken import views schema_view = get_schema_view(title='Grailed API') # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'channels', ChannelViewSet) router.register(r'messages', MessageViewSet) # The API URLs are now determined automatically by the router. # Additionally, we include the login URLs for the browsable API. urlpatterns = [ url(r'^schema/$', schema_view), url(r'^', include(router.urls)), url(r'^', include('rest_auth.urls')), url(r'^registration/$', include('rest_auth.registration.urls')), url(r'^api-token-auth/', views.obtain_auth_token), # fet token with username and password ]
Add Janeus settings to local_settings example
DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.sqlite3", # DB name or path to database file if using sqlite3. "NAME": "dev.db", # Not used with sqlite3. "USER": "", # Not used with sqlite3. "PASSWORD": "", # Set to empty string for localhost. Not used with sqlite3. "HOST": "", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } ################# # LDAP SETTINGS # ################# LDAP_NAME = 'ldap://127.0.0.1:389/' LDAP_DN = 'cn=writeall,ou=sysUsers,dc=jd,dc=nl' LDAP_PASSWORD = '' ################### # JANEUS SETTINGS # ################### JANEUS_SERVER = "ldap://127.0.0.1:389/" JANEUS_DN = "cn=readall,ou=sysUsers,dc=jd,dc=nl" JANEUS_PASS = ""
LDAP_NAME = 'ldap://' LDAP_PASSWORD = '' LDAP_DN = 'cn=writeuser,ou=sysUsers,dc=jd,dc=nl' SECRET_KEY = '' DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.sqlite3", # DB name or path to database file if using sqlite3. "NAME": "dev.db", # Not used with sqlite3. "USER": "", # Not used with sqlite3. "PASSWORD": "", # Set to empty string for localhost. Not used with sqlite3. "HOST": "", # Set to empty string for default. Not used with sqlite3. "PORT": "", } }
Add compressed style to sass build
var gulp = require('gulp'); var gulpUtil = require('gulp-util'); var gulpIf = require('gulp-if'); var browserSync = require('browser-sync').create(); var uglify = require('gulp-uglify'); var sass = require('gulp-ruby-sass'); var sourcemaps = require('gulp-sourcemaps'); var jshint = require('gulp-jshint'); var jshintStylish = require('jshint-stylish'); var useref = require('gulp-useref'); var imagemin = require('gulp-imagemin'); var del = require('del'); // Tasks gulp.task('build:sass', function () { return sass('scss/main.scss', { sourcemap: true }) .on('error', sass.logError) .pipe(sourcemaps.write()) .pipe(sourcemaps.write('maps', { includeContent: false, sourceRoot: 'source' })) .pipe(gulp.dest('_site/css')); });
var gulp = require('gulp'); var gulpUtil = require('gulp-util'); var gulpIf = require('gulp-if'); var browserSync = require('browser-sync').create(); var uglify = require('gulp-uglify'); var sass = require('gulp-ruby-sass'); var jshint = require('gulp-jshint'); var jshintStylish = require('jshint-stylish'); var useref = require('gulp-useref'); var imagemin = require('gulp-imagemin'); var del = require('del'); // Tasks gulp.task('build:sass', function () { return sass('scss/main.scss', { sourcemap: true }) .on('error', sass.logError) .pipe(gulp.dest('_site/css')); .pipe(sourcemaps.write('maps', { includeContent: false, sourceRoot: 'source' })) });
Remove leading slash from page filenames
'use strict'; const ArchivePlugin = require('webpack-archive-plugin'); const DashboardPlugin = require('webpack-dashboard/plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const extractText = require('./extract-text'); const { rules } = require('./module'); const pages = require('./pages'); function createPagePlugin(page) { const filename = pages.hash.templatePages[page].replace(/^\//, ''); const template = `${pages.path}/${page}`; return new HtmlWebpackPlugin({ filename, inject: true, template, }); } module.exports = function configurePlugins(env = {}, argv) { const envPlugins = env.production ? [ new ArchivePlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new webpack.optimize.UglifyJsPlugin(), ] : [ new DashboardPlugin() ]; return [ extractText.plugin, extractText.workaround(rules), ] .concat(pages.map(createPagePlugin)) .concat(envPlugins) ; };
'use strict'; const ArchivePlugin = require('webpack-archive-plugin'); const DashboardPlugin = require('webpack-dashboard/plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const extractText = require('./extract-text'); const { rules } = require('./module'); const pages = require('./pages'); function createPagePlugin(page) { const filename = pages.hash.templatePages[page]; const template = `${pages.path}/${page}`; return new HtmlWebpackPlugin({ filename, inject: true, template, }); } module.exports = function configurePlugins(env = {}, argv) { const envPlugins = env.production ? [ new ArchivePlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new webpack.optimize.UglifyJsPlugin(), ] : [ new DashboardPlugin() ]; return [ extractText.plugin, extractText.workaround(rules), ] .concat(pages.map(createPagePlugin)) .concat(envPlugins) ; };
Add empty alt tag to slack logo. As per http://webaim.org/techniques/alttext/#decorative Decorative images should have empty alt tags, which indicates that the image is decorative and should not be read aloud by assistive technologies.
@extends('layouts.master') @section('title', 'Home') @section('content') <div class="row"> <div class="col-md-12 text-center"> <h1 class="slack-callout">Join our slack <img src="/img/slack_rgb.png" alt="" class="img-responsive"/> channel!</h1> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="/slack-invite" method="post"> {!! csrf_field() !!} <div class="input-group input-group-lg"> <input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" aria-label="Email to invite"> <span class="input-group-btn"> <button type="submit" class="btn btn-primary btn-lg">Join</button> </span> </div> </form> </div> </div> @endsection
@extends('layouts.master') @section('title', 'Home') @section('content') <div class="row"> <div class="col-md-12 text-center"> <h1 class="slack-callout">Join our slack <img src="/img/slack_rgb.png" class="img-responsive"/> channel!</h1> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="/slack-invite" method="post"> {!! csrf_field() !!} <div class="input-group input-group-lg"> <input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" aria-label="Email to invite"> <span class="input-group-btn"> <button type="submit" class="btn btn-primary btn-lg">Join</button> </span> </div> </form> </div> </div> @endsection
Fix user notification settings fetch
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { dispatched } from '@webkom/react-prepare'; import UserSettingsNotifications from './components/UserSettingsNotifications'; import { fetchNotificationAlternatives, fetchNotificationSettings, updateNotificationSetting } from 'app/actions/NotificationSettingsActions'; import { selectNotificationSettingsAlternatives, selectNotificationSettings } from 'app/reducers/notificationSettings'; const loadData = (props, dispatch) => { return Promise.all([ dispatch(fetchNotificationAlternatives()), dispatch(fetchNotificationSettings()) ]); }; const mapStateToProps = state => { return { alternatives: selectNotificationSettingsAlternatives(state), settings: selectNotificationSettings(state) }; }; const mapDispatchToProps = { updateNotificationSetting }; export default compose( dispatched(loadData, { componentWillReceiveProps: false }), connect(mapStateToProps, mapDispatchToProps) )(UserSettingsNotifications);
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { dispatched } from '@webkom/react-prepare'; import UserSettingsNotifications from './components/UserSettingsNotifications'; import { fetchNotificationAlternatives, fetchNotificationSettings, updateNotificationSetting } from 'app/actions/NotificationSettingsActions'; import { selectNotificationSettingsAlternatives, selectNotificationSettings } from 'app/reducers/notificationSettings'; const loadData = (props, dispatch) => { return Promise.all([ dispatch(fetchNotificationAlternatives()), dispatch(fetchNotificationSettings()) ]); }; const mapStateToProps = state => { return { alternatives: selectNotificationSettingsAlternatives(state), settings: selectNotificationSettings(state) }; }; const mapDispatchToProps = { updateNotificationSetting }; export default compose( dispatched(loadData), connect(mapStateToProps, mapDispatchToProps) )(UserSettingsNotifications);
Check if the git repo already exists before cloning it again
from subprocess import check_call import urllib import json import os import os.path def install(): if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')): return with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) if not os.path.isdir(bowerrc['directory']): os.makedirs(bowerrc['directory']) registry = 'https://bower.herokuapp.com' topdir = os.path.abspath(os.curdir) for pkg in bower_json['dependencies'].keys(): req = urllib.urlopen('%s/packages/%s' % (registry, pkg)) info = json.load(req) os.chdir(bowerrc['directory']) if not os.path.isdir(os.path.join(pkg, '.git')): check_call(['git', 'clone', info['url'], pkg]) os.chdir(pkg) install() os.chdir(topdir)
from subprocess import check_call import urllib import json import os import os.path def install(): if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')): return with open('.bowerrc') as f: bowerrc = json.load(f) with open('bower.json') as f: bower_json = json.load(f) if not os.path.isdir(bowerrc['directory']): os.makedirs(bowerrc['directory']) registry = 'https://bower.herokuapp.com' topdir = os.path.abspath(os.curdir) for pkg in bower_json['dependencies'].keys(): req = urllib.urlopen('%s/packages/%s' % (registry, pkg)) info = json.load(req) os.chdir(bowerrc['directory']) check_call(['git', 'clone', info['url']]) os.chdir(pkg) install() os.chdir(topdir)
Handle case for auto assigned ID is a number
require('raptor-polyfill/string/endsWith'); var repeatedId = require('../lib/repeated-id'); function WidgetDef(config, endFunc, out) { this.module = config.module; this.id = config.id; this.config = config.config; this.state = config.state; this.scope = config.scope; this.domEvents = config.domEvents; this.customEvents = config.customEvents; this.children = []; this.end = endFunc; this.extend = config.extend; this.existingWidget = config.existingWidget; this.out = out; } WidgetDef.prototype = { addChild: function (widgetDef) { this.children.push(widgetDef); }, elId: function (nestedId) { if (nestedId == null) { return this.id; } else { if (typeof nestedId === 'string' && nestedId.endsWith('[]')) { nestedId = repeatedId.nextId(this.out, this.id, nestedId); } return this.id + '-' + nestedId; } } }; module.exports = WidgetDef;
require('raptor-polyfill/string/endsWith'); var repeatedId = require('../lib/repeated-id'); function WidgetDef(config, endFunc, out) { this.module = config.module; this.id = config.id; this.config = config.config; this.state = config.state; this.scope = config.scope; this.domEvents = config.domEvents; this.customEvents = config.customEvents; this.children = []; this.end = endFunc; this.extend = config.extend; this.existingWidget = config.existingWidget; this.out = out; } WidgetDef.prototype = { addChild: function (widgetDef) { this.children.push(widgetDef); }, elId: function (nestedId) { if (nestedId == null) { return this.id; } else { if (nestedId.endsWith('[]')) { nestedId = repeatedId.nextId(this.out, this.id, nestedId); } return this.id + '-' + nestedId; } } }; module.exports = WidgetDef;
Use sqlalchemy to generate query
from sqlalchemy import create_engine from sqlalchemy import MetaData, Table, Column, DateTime, Float, between from sqlalchemy.sql import select, text import arrow metadata = MetaData() meter_readings = Table('interval_readings', metadata, Column('reading_date', DateTime, primary_key=True), Column('ch1', Float, nullable=False), ) def get_energy_chart_data(meterId, start_date="2016-09-01", end_date="2016-10-01"): """ Return json object for flot chart """ engine = create_engine('sqlite:///../data/'+ str(meterId) + '.db', echo=True) conn = engine.connect() s = select([meter_readings]).where(between(meter_readings.c.reading_date, start_date, end_date)) data = conn.execute(s).fetchall() chartdata = {} chartdata['label'] = 'Energy Profile' chartdata['consumption'] = [] for row in data: dTime = arrow.get(row[0]) ts = int(dTime.timestamp * 1000) chartdata['consumption'].append([ts, row[1]]) return chartdata
from sqlalchemy import create_engine from sqlalchemy.sql import text import arrow def get_energy_chart_data(meterId, start_date="2016-09-01", end_date="2016-10-01"): """ Return json object for flot chart """ engine = create_engine('sqlite:///../data/'+ str(meterId) + '.db', echo=True) conn = engine.connect() query = """SELECT DATE_M, Ch1 FROM INTERVAL_READINGS WHERE DATE_M >= DATE(:x) AND DATE_M < DATE(:y) ORDER BY DATE_M ASC """ s = text(query) data = conn.execute(s, x=start_date, y=end_date).fetchall() chartdata = {} chartdata['label'] = 'Energy Profile' chartdata['consumption'] = [] for row in data: dTime = arrow.get(row[0]) ts = int(dTime.timestamp * 1000) chartdata['consumption'].append([ts, row[1]]) return chartdata
Fix bad working directory bug.
#!/usr/bin/env node 'use strict'; let isRoot = require('is-root'); if(isRoot()) { console.error("I refuse to run as root."); process.exit(-1); } let path = require('path'); let dirName = path.dirname; let fm = require('front-matter'); let hbs = require('handlebars'); let glob = require('glob'); let registerHelpers = require('./registerHelpers'); let registerPartials = require('./registerPartials'); let registerAllUpwardsOf = require('./registerAllUpwardsOf'); let readFileSync = require('./readFileSync'); let templPath = process.argv[2]; let workDir; if(!templPath) { templPath = '/dev/stdin'; workDir = process.cwd(); } else { workDir = dirName(templPath); } registerHelpers(glob.sync(__dirname + '/builtin/*.helper.js')); registerPartials(glob.sync(__dirname + '/builtin/*.partial.hbs')); registerAllUpwardsOf(workDir); let { attributes: templFm, body: templSrc } = fm(readFileSync(templPath)); process.chdir(workDir); let templ = hbs.compile(templSrc); process.stdout.write(templ(templFm));
#!/usr/bin/env node 'use strict'; let isRoot = require('is-root'); if(isRoot()) { console.error("I refuse to run as root."); process.exit(-1); } let path = require('path'); let dirName = path.dirname; let fm = require('front-matter'); let hbs = require('handlebars'); let glob = require('glob'); let registerHelpers = require('./registerHelpers'); let registerPartials = require('./registerPartials'); let registerAllUpwardsOf = require('./registerAllUpwardsOf'); let readFileSync = require('./readFileSync'); let templPath = process.argv[2]; if(!templPath) { templPath = '/dev/stdin'; } registerHelpers(glob.sync(__dirname + '/builtin/*.helper.js')); registerPartials(glob.sync(__dirname + '/builtin/*.partial.hbs')); registerAllUpwardsOf(dirName(templPath)); let { attributes: templFm, body: templSrc } = fm(readFileSync(templPath)); let templ = hbs.compile(templSrc); process.stdout.write(templ(templFm));
Update version number to 0.2.0b16
from __future__ import print_function try: from setuptools import setup # try first in case it's already there. except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='vpython', packages=['vpython'], version='0.2.0b16', description='VPython for Jupyter Notebook', long_description=open('README.md').read(), author='John Coady / Ruth Chabay / Bruce Sherwood / Steve Spicklemire', author_email='bruce.sherwood@gmail.com', url='http://pypi.python.org/pypi/vpython/', license='LICENSE.txt', keywords='vpython', classifiers=[ 'Framework :: IPython', 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'Topic :: Multimedia :: Graphics :: 3D Rendering', 'Topic :: Scientific/Engineering :: Visualization', ], install_requires=['jupyter', 'vpnotebook'], package_data={'vpython': ['data/*']}, )
from __future__ import print_function try: from setuptools import setup # try first in case it's already there. except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='vpython', packages=['vpython'], version='0.2.0b15', description='VPython for Jupyter Notebook', long_description=open('README.md').read(), author='John Coady / Ruth Chabay / Bruce Sherwood / Steve Spicklemire', author_email='bruce.sherwood@gmail.com', url='http://pypi.python.org/pypi/vpython/', license='LICENSE.txt', keywords='vpython', classifiers=[ 'Framework :: IPython', 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'Topic :: Multimedia :: Graphics :: 3D Rendering', 'Topic :: Scientific/Engineering :: Visualization', ], install_requires=['jupyter', 'vpnotebook'], package_data={'vpython': ['data/*']}, )