text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add path for sqlite file
import os import platform from hatarake.version import __version__ ISSUES_LINK = 'https://github.com/kfdm/hatarake/issues' ISSUES_API = 'https://api.github.com/repos/kfdm/hatarake/issues?state=open' USER_AGENT = 'Hatarake/%s https://github.com/kfdm/hatarake' % __version__ GROWL_INTERVAL = 30 if 'Darwin' in platform.uname(): CONFIG_PATH = os.path.join( os.path.expanduser("~"), 'Library', 'Application Support', 'Hatarake', 'config.ini' ) DB_PATH = os.path.join( os.path.expanduser("~"), 'Library', 'Application Support', 'Hatarake', 'history.db' ) else: CONFIG_PATH = os.path.join( os.path.expanduser("~"), '.config', 'Hatarake', 'config.ini', ) DB_PATH = os.path.join( os.path.expanduser("~"), '.config', 'Hatarake', 'history.db', )
import os import platform from hatarake.version import __version__ ISSUES_LINK = 'https://github.com/kfdm/hatarake/issues' ISSUES_API = 'https://api.github.com/repos/kfdm/hatarake/issues?state=open' USER_AGENT = 'Hatarake/%s https://github.com/kfdm/hatarake' % __version__ GROWL_INTERVAL = 30 if 'Darwin' in platform.uname(): CONFIG_PATH = os.path.join( os.path.expanduser("~"), 'Library', 'Application Support', 'Hatarake', 'config.ini' ) else: CONFIG_PATH = os.path.join( os.path.expanduser("~"), '.config', 'Hatarake', 'config.ini', )
Update classifiers for supported Python versions [ci skip]
from setuptools import find_packages, setup from virtualenvapi import __version__ setup( name='virtualenv-api', version=__version__, license='BSD', author='Sam Kingston and AUTHORS', author_email='sam@sjkwi.com.au', description='An API for virtualenv/pip', long_description=open('README.rst', 'r').read(), url='https://github.com/sjkingo/virtualenv-api', install_requires=['six'], packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import find_packages, setup from virtualenvapi import __version__ setup( name='virtualenv-api', version=__version__, license='BSD', author='Sam Kingston and AUTHORS', author_email='sam@sjkwi.com.au', description='An API for virtualenv/pip', long_description=open('README.rst', 'r').read(), url='https://github.com/sjkingo/virtualenv-api', install_requires=['six'], packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Correct the translation domain for loading messages Change-Id: If7fa8fd1915378bda3fc6e361049c2d90cdec8af
# Copyright 2012 Red Hat, Inc. # Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Translation support for messages in this library. """ from oslo_i18n import _factory # Create the global translation functions. _translators = _factory.TranslatorFactory('oslo.i18n') # The primary translation function using the well-known name "_" _ = _translators.primary
# Copyright 2012 Red Hat, Inc. # Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Translation support for messages in this library. """ from oslo_i18n import _factory # Create the global translation functions. _translators = _factory.TranslatorFactory('oslo_i18n') # The primary translation function using the well-known name "_" _ = _translators.primary
Convert generateCourseKey to use randomstring module Signed-off-by: samgoldman <06cb9b47f702e929df8a0a808508cab59f4c50c4@gmail.com>
// app/models/course.js // load the things we need const mongoose = require('mongoose'); const randomstring = require("randomstring"); // define the schema for our user model const courseSchema = mongoose.Schema({ courseName: String, courseKey: String, teacher: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, valid: {type: Boolean, default: true}, timestamp: {type: Date, default: Date.now} }); courseSchema.pre('save', function (next) { this.timestamp = new Date(); next(); }); courseSchema.statics.taughtBy = function taughtBy(uid) { let Course = this; return Course.find({teacher: uid, valid: true}).sort('courseName'); }; courseSchema.statics.verifyCourseTaughtBy = function verifyCourseTaughtBy(cid, uid) { return this.find({_id: cid, teacher: uid, valid: true}) .countDocuments() .then(function(count) { if (count <= 0) throw new Error('Teacher does not teach class!'); }); }; // Generate a random 6 character key courseSchema.statics.generateCourseKey = () => randomstring.generate(6); // create the model for users and expose it to our app module.exports = { model: mongoose.model('Course', courseSchema) };
// app/models/course.js // load the things we need let mongoose = require('mongoose'); let User = require('./user'); // define the schema for our user model let courseSchema = mongoose.Schema({ courseName: String, courseKey: String, teacher: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, valid: {type: Boolean, default: true}, timestamp: {type: Date, default: Date.now} }); courseSchema.pre('save', function (next) { this.timestamp = new Date(); next(); }); courseSchema.statics.taughtBy = function taughtBy(uid) { let Course = this; return Course.find({teacher: uid, valid: true}).sort('courseName'); }; courseSchema.statics.verifyCourseTaughtBy = function verifyCourseTaughtBy(cid, uid) { return this.find({_id: cid, teacher: uid, valid: true}) .countDocuments() .then(function(count) { if (count <= 0) throw new Error('Teacher does not teach class!'); }); }; // Generate a random 6-7 character key courseSchema.statics.generateCourseKey = function generateCourseKey() { return (Math.floor(Math.random() * 1000000000) + parseInt(Date.now() / 1000)).toString(36).toUpperCase().substring(0, 6); }; // create the model for users and expose it to our app module.exports = { model: mongoose.model('Course', courseSchema) };
Convert hidden message to lower case JFF
'use strict'; var parseConcat = require('..'); var stread = require('stread'); it('should concat-stream and JSON.parse', function (done) { var data = { name: null, version: "1.1.1", tags: [true, "awesomeness", [{}]] }; stread(JSON.stringify(data, null, 2)) .pipe(parseConcat(function (err, result) { (err == null).should.be.true; result.should.eql(data); done(); })); }); it('should propagate the error', function (done) { stread('{') .pipe(parseConcat(function (err) { err.should.be.an.Error; done(); })); }); it('should accept custom parsers', function (done) { var caps = function (string) { return (string.match(/[A-Z]/g) || []).join('').toLowerCase(); }; stread(' {\nMEdiS]]\n} SorAs \tGEt') .pipe(parseConcat({ parse: caps }, function (err, result) { (err == null).should.be.true; result.should.equal('message'); done(); })); });
'use strict'; var parseConcat = require('..'); var stread = require('stread'); it('should concat-stream and JSON.parse', function (done) { var data = { name: null, version: "1.1.1", tags: [true, "awesomeness", [{}]] }; stread(JSON.stringify(data, null, 2)) .pipe(parseConcat(function (err, result) { (err == null).should.be.true; result.should.eql(data); done(); })); }); it('should propagate the error', function (done) { stread('{') .pipe(parseConcat(function (err) { err.should.be.an.Error; done(); })); }); it('should accept custom parsers', function (done) { var caps = function (string) { return (string.match(/[A-Z]/g) || []).join(''); }; stread(' {\nMEdiS]]\n} SorAs \tGEt') .pipe(parseConcat({ parse: caps }, function (err, result) { (err == null).should.be.true; result.should.equal('MESSAGE'); done(); })); });
Exclude volunteers from the event admin Showing many-to-many relationships in the admin can cause a page to take a while to load. Plus the event admin isn't really the place to manage volunteers. Closes #198
"""Admin for event-related models.""" import wtforms from pygotham.admin.utils import model_view from pygotham.events import models __all__ = ('EventModelView',) CATEGORY = 'Events' EventModelView = model_view( models.Event, 'Events', CATEGORY, column_list=('name', 'slug', 'begins', 'ends', 'active'), form_excluded_columns=( 'about_pages', 'announcements', 'calls_to_action', 'days', 'sponsor_levels', 'talks', 'volunteers', ), form_overrides={ 'activity_begins': wtforms.DateTimeField, 'activity_ends': wtforms.DateTimeField, 'proposals_begin': wtforms.DateTimeField, 'proposals_end': wtforms.DateTimeField, 'registration_begins': wtforms.DateTimeField, 'registration_ends': wtforms.DateTimeField, 'talk_list_begins': wtforms.DateTimeField, }, ) VolunteerModelView = model_view( models.Volunteer, 'Volunteers', CATEGORY, column_filters=('event.slug', 'event.name'), column_list=('event', 'user'), )
"""Admin for event-related models.""" import wtforms from pygotham.admin.utils import model_view from pygotham.events import models __all__ = ('EventModelView',) CATEGORY = 'Events' EventModelView = model_view( models.Event, 'Events', CATEGORY, column_list=('name', 'slug', 'begins', 'ends', 'active'), form_excluded_columns=( 'about_pages', 'announcements', 'calls_to_action', 'days', 'sponsor_levels', 'talks', ), form_overrides={ 'activity_begins': wtforms.DateTimeField, 'activity_ends': wtforms.DateTimeField, 'proposals_begin': wtforms.DateTimeField, 'proposals_end': wtforms.DateTimeField, 'registration_begins': wtforms.DateTimeField, 'registration_ends': wtforms.DateTimeField, 'talk_list_begins': wtforms.DateTimeField, }, ) VolunteerModelView = model_view( models.Volunteer, 'Volunteers', CATEGORY, column_filters=('event.slug', 'event.name'), column_list=('event', 'user'), )
Add test for learners help link
from unittest import skipUnless from bok_choy.web_app_test import WebAppTest from acceptance_tests import ENABLE_LEARNER_ANALYTICS from acceptance_tests.mixins import CoursePageTestsMixin from acceptance_tests.pages import CourseLearnersPage @skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled to run CourseLearnersTests') class CourseLearnersTests(CoursePageTestsMixin, WebAppTest): help_path = 'engagement/learners.html' def setUp(self): super(CourseLearnersTests, self).setUp() self.page = CourseLearnersPage(self.browser) def _test_data_update_message(self): # Don't test the update message for now, since it won't exist # until the SPA adds it to the page in AN-6205. pass def _get_data_update_message(self): # Don't test the update message for now, since it won't exist # until the SPA adds it to the page in AN-6205. return ''
from unittest import skipUnless from bok_choy.web_app_test import WebAppTest from acceptance_tests import ENABLE_LEARNER_ANALYTICS from acceptance_tests.mixins import CoursePageTestsMixin from acceptance_tests.pages import CourseLearnersPage @skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled to run CourseLearnersTests') class CourseLearnersTests(CoursePageTestsMixin, WebAppTest): def setUp(self): super(CourseLearnersTests, self).setUp() self.page = CourseLearnersPage(self.browser) def _test_data_update_message(self): # Don't test the update message for now, since it won't exist # until the SPA adds it to the page in AN-6205. pass def _get_data_update_message(self): # Don't test the update message for now, since it won't exist # until the SPA adds it to the page in AN-6205. return ''
Update test bootstrap to work with latest ZF2 master
<?php use Zend\ServiceManager\ServiceManager; use Zend\Mvc\Service\ServiceManagerConfig; use CdliTwoStageSignupTest\Framework\TestCase; use CdliTwoStageSignupTest\Framework\TestCaseOptions; chdir(__DIR__); $previousDir = '.'; while (!file_exists('config/application.config.php')) { $dir = dirname(getcwd()); if($previousDir === $dir) { throw new RuntimeException( 'Unable to locate "config/application.config.php":' . ' is CdliTwoStageSignup in a subdir of your application skeleton?' ); } $previousDir = $dir; chdir($dir); } if (!include('vendor/autoload.php')) { throw new RuntimeException( 'vendor/autoload.php could not be found. ' . 'Did you run php composer.phar install in your application skeleton?' ); } // Get application stack configuration $configuration = include 'config/application.config.php'; $configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php'; // Setup service manager $serviceManager = new ServiceManager(new ServiceManagerConfig(@$configuration['service_manager'] ?: array())); $serviceManager->setService('ApplicationConfig', $configuration); $serviceManager->get('ModuleManager')->loadModules(); TestCase::setServiceLocator($serviceManager); $config = $serviceManager->get('Configuration'); TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));
<?php use Zend\ServiceManager\ServiceManager; use Zend\Mvc\Service\ServiceManagerConfiguration; use CdliTwoStageSignupTest\Framework\TestCase; use CdliTwoStageSignupTest\Framework\TestCaseOptions; chdir(__DIR__); $previousDir = '.'; while (!file_exists('config/application.config.php')) { $dir = dirname(getcwd()); if($previousDir === $dir) { throw new RuntimeException( 'Unable to locate "config/application.config.php":' . ' is CdliTwoStageSignup in a subdir of your application skeleton?' ); } $previousDir = $dir; chdir($dir); } if (!include('vendor/autoload.php')) { throw new RuntimeException( 'vendor/autoload.php could not be found. ' . 'Did you run php composer.phar install in your application skeleton?' ); } // Get application stack configuration $configuration = include 'config/application.config.php'; $configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php'; // Setup service manager $serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager'])); $serviceManager->setService('ApplicationConfiguration', $configuration); $serviceManager->get('ModuleManager')->loadModules(); #$serviceManager->get('Application')->bootstrap(); TestCase::setServiceLocator($serviceManager); $config = $serviceManager->get('Configuration'); TestCase::setOptions(new TestCaseOptions($config['cdli-twostagesignup-test']));
Add message when input-checkboxes has no values
<ul class="checkboxes"> <?php foreach ($values as $v => $l) { ?> <li class="checkboxes_i"> <input type="hidden" name="<?= "{$name}[{$this->escape($v)}]" ?>" value="0"> <input type="checkbox" name="<?= "{$name}[{$this->escape($v)}]" ?>" id="<?= "{$id}[{$this->escape($v)}]" ?>" value="1" <?= isset($disabled) && $disabled ? "disabled" : null ?> <?= isset($readOnly) && $readOnly ? "readonly" : null ?> <?= in_array($v, $value) ? 'checked' : null ?> <?= isset($class) ? "class=\"{$class}\"" : null ?>> <label for="<?= "{$id}[{$this->escape($v)}]" ?>" class="checkbox"> <?= $l ?> </label> </li> <?php } ?> </ul> <?php if (!count($values)) { ?> <small>No options available.</small> <?php } ?>
<ul class="checkboxes"> <?php foreach ($values as $v => $l) { ?> <li class="checkboxes_i"> <input type="hidden" name="<?= "{$name}[{$this->escape($v)}]" ?>" value="0"> <input type="checkbox" name="<?= "{$name}[{$this->escape($v)}]" ?>" id="<?= "{$id}[{$this->escape($v)}]" ?>" value="1" <?= isset($disabled) && $disabled ? "disabled" : null ?> <?= isset($readOnly) && $readOnly ? "readonly" : null ?> <?= in_array($v, $value) ? 'checked' : null ?> <?= isset($class) ? "class=\"{$class}\"" : null ?>> <label for="<?= "{$id}[{$this->escape($v)}]" ?>" class="checkbox"> <?= $l ?> </label> </li> <?php } ?> </ul>
Handle non-ascii characters when generating fuzzing dictionary This caused a failure when generating the dictionary for `tree-sitter-agda`.
import json import sys def find_literals(literals, node): '''Recursively find STRING literals in the grammar definition''' if type(node) is dict: if 'type' in node and node['type'] == 'STRING' and 'value' in node: literals.add(node['value']) for key, value in node.iteritems(): find_literals(literals, value) elif type(node) is list: for item in node: find_literals(literals, item) def main(): '''Generate a libFuzzer / AFL dictionary from a tree-sitter grammar.json''' with open(sys.argv[1]) as f: grammar = json.load(f) literals = set() find_literals(literals, grammar) for lit in sorted(literals): if lit: print '"%s"' % ''.join(['\\x%02x' % ord(b) for b in lit.encode('utf-8')]) if __name__ == '__main__': main()
import json import sys def find_literals(literals, node): '''Recursively find STRING literals in the grammar definition''' if type(node) is dict: if 'type' in node and node['type'] == 'STRING' and 'value' in node: literals.add(node['value']) for key, value in node.iteritems(): find_literals(literals, value) elif type(node) is list: for item in node: find_literals(literals, item) def main(): '''Generate a libFuzzer / AFL dictionary from a tree-sitter grammar.json''' with open(sys.argv[1]) as f: grammar = json.load(f) literals = set() find_literals(literals, grammar) for lit in sorted(literals): if lit: print '"%s"' % ''.join([(c if c.isalnum() else '\\x%02x' % ord(c)) for c in lit]) if __name__ == '__main__': main()
Rename GH token env var GitHub disallows user set GITHUB_ prefixed ones.
import os from pathlib import Path from string import Template from dotenv import load_dotenv load_dotenv() # helps with local dev TEMPLATE_PATH = Path.cwd() / "email.md" STARMINDER_COUNT = int(os.getenv("STARMINDER_COUNT")) STARMINDER_RECIPIENT = os.getenv("STARMINDER_RECIPIENT") STARMINDER_SUBJECT = Template("[Starminder] Reminders for $today") AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_FROM = os.getenv("AWS_FROM") GITHUB_TOKEN = os.getenv("GH_TOKEN") GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL") GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY") GITHUB_FORK_URL = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}"
import os from pathlib import Path from string import Template from dotenv import load_dotenv load_dotenv() # helps with local dev TEMPLATE_PATH = Path.cwd() / "email.md" STARMINDER_COUNT = int(os.getenv("STARMINDER_COUNT")) STARMINDER_RECIPIENT = os.getenv("STARMINDER_RECIPIENT") STARMINDER_SUBJECT = Template("[Starminder] Reminders for $today") AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_FROM = os.getenv("AWS_FROM") GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL") GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY") GITHUB_FORK_URL = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}"
Add a test for list comprehensions with more than two ifs
from ..utils import TranspileTestCase class ListComprehensionTests(TranspileTestCase): def test_syntax(self): self.assertCodeExecution(""" x = [1, 2, 3, 4, 5] print([v**2 for v in x]) print([v for v in x]) """) def test_list_comprehension_with_if_condition(self): self.assertCodeExecution(""" print([v for v in range(100) if v % 2 == 0]) print([v for v in range(100) if v % 2 == 0 if v % 3 == 0]) print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80]) """) def test_method(self): self.assertCodeExecution(""" x = [1, 2, 3, 4, 5] print(list(v**2 for v in x)) """)
from ..utils import TranspileTestCase class ListComprehensionTests(TranspileTestCase): def test_syntax(self): self.assertCodeExecution(""" x = [1, 2, 3, 4, 5] print([v**2 for v in x]) print([v for v in x]) """) def test_list_comprehension_with_if_condition(self): self.assertCodeExecution(""" print([v for v in range(100) if v % 2 == 0]) print([v for v in range(100) if v % 2 == 0 if v % 3 == 0]) """) def test_method(self): self.assertCodeExecution(""" x = [1, 2, 3, 4, 5] print(list(v**2 for v in x)) """)
Use exception if the image is not Ultrasound image.
package gov.nih.nci.ncia.util; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Util class for Ultrasound process * * @author zhoujim * */ public class UltrasoundUtil { public static final int[] MASKS = {0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020,0x0040, 0x0100, 0x0200}; public static String getMultiModalityByCode(String code) throws Exception { NumberFormat nf = new DecimalFormat("#0000"); int intCode = Integer.valueOf(code, 16); StringBuffer buff = new StringBuffer(); for(int i=0; i< MASKS.length;i++) { if((MASKS[i] & intCode) > 0) { String s = Integer.toString(MASKS[i],16); long l = Long.parseLong(s); buff.append(nf.format(l)); buff.append(','); } } String result = buff.toString(); return result.substring(0,result.length()-1); } public static void main(String[] args) { String result = getMultiModalityByCode("Utltr"); System.out.println("result: " + result ); } }
package gov.nih.nci.ncia.util; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Util class for Ultrasound process * * @author zhoujim * */ public class UltrasoundUtil { public static final int[] MASKS = {0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020,0x0040, 0x0100, 0x0200}; public static String getMultiModalityByCode(String code) { NumberFormat nf = new DecimalFormat("#0000"); int intCode = Integer.valueOf(code, 16); StringBuffer buff = new StringBuffer(); for(int i=0; i< MASKS.length;i++) { if((MASKS[i] & intCode) > 0) { String s = Integer.toString(MASKS[i],16); long l = Long.parseLong(s); buff.append(nf.format(l)); buff.append(','); } } String result = buff.toString(); return result.substring(0,result.length()-1); } public static void main(String[] args) { String result = getMultiModalityByCode("0011"); System.out.println("result: " + result ); } }
Use var instead of let for now
"use strict"; import Dispatcher from "../dispatcher"; import Constants from "../constants"; import StoreCommon from "./store_common"; import assign from "object-assign"; var _user = {}; // log the user in function login(email, password){ return true; } // Register function register(user){ return true; } // Extend User Store with EventEmitter to add eventing capabilities var UserStore = assign({}, StoreCommon, { // Return current user current(){ return _user; }, loggedIn(){ return _user.email !== undefined; }, token(){ return _user.token; } }); // Register callback with Dispatcher Dispatcher.register(function(payload) { var action = payload.action; switch(action){ // Respond to LOGIN action case Constants.LOGIN: login(payload.email, payload.password); break; // Respond to REGISTER action case Constants.REGISTER: register(payload.user); break; default: return true; } // If action was responded to, emit change event UserStore.emitChange(); return true; }); export default UserStore;
"use strict"; import Dispatcher from "../dispatcher"; import Constants from "../constants"; import StoreCommon from "./store_common"; import assign from "object-assign"; let _user = {}; // log the user in function login(email, password){ return true; } // Register function register(user){ return true; } // Extend User Store with EventEmitter to add eventing capabilities let UserStore = assign({}, StoreCommon, { // Return current user current(){ return _user; }, loggedIn(){ return _user.email !== undefined; }, token(){ return _user.token; } }); // Register callback with Dispatcher Dispatcher.register(function(payload) { let action = payload.action; switch(action){ // Respond to LOGIN action case Constants.LOGIN: login(payload.email, payload.password); break; // Respond to REGISTER action case Constants.REGISTER: register(payload.user); break; default: return true; } // If action was responded to, emit change event UserStore.emitChange(); return true; }); export default UserStore;
Repair the regex for the homepage.
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='landing.html')), url(r'^admin/', admin.site.urls), url(r'^moons/', include('moon_tracker.urls')) ]
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^/', TemplateView.as_view(template_name='landing.html')), url(r'^admin/', admin.site.urls), url(r'^moons/', include('moon_tracker.urls')) ]
Change name of the package from admin_tools_zinnia to admin-tools-zinnia
"""Setup script for admin-tools-zinnia""" from setuptools import setup from setuptools import find_packages import admin_tools_zinnia setup( name='admin-tools-zinnia', version=admin_tools_zinnia.__version__, description='Admin tools for django-blog-zinnia', long_description=open('README.rst').read(), keywords='django, blog, weblog, zinnia, admin, dashboard', author=admin_tools_zinnia.__author__, author_email=admin_tools_zinnia.__email__, url=admin_tools_zinnia.__url__, packages=find_packages(exclude=['demo_admin_tools_zinnia']), classifiers=[ 'Framework :: Django', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules'], license=admin_tools_zinnia.__license__, include_package_data=True, zip_safe=False )
"""Setup script for admin-tools-zinnia""" from setuptools import setup from setuptools import find_packages import admin_tools_zinnia setup( name='admin_tools_zinnia', version=admin_tools_zinnia.__version__, description='Admin tools for django-blog-zinnia', long_description=open('README.rst').read(), keywords='django, blog, weblog, zinnia, admin, dashboard', author=admin_tools_zinnia.__author__, author_email=admin_tools_zinnia.__email__, url=admin_tools_zinnia.__url__, packages=find_packages(exclude=['demo_admin_tools_zinnia']), classifiers=[ 'Framework :: Django', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules'], license=admin_tools_zinnia.__license__, include_package_data=True, zip_safe=False )
Fix typo in test class name
<?php namespace CodeZero\BrowserLocale\Tests\Filters; use CodeZero\BrowserLocale\Filters\LocaleFilter; use CodeZero\BrowserLocale\Locale; use PHPUnit\Framework\TestCase; class LocaleFilterwTest extends TestCase { /** @test */ public function it_filters_a_simple_array_of_locales() { $locales = (new LocaleFilter)->filter([ new Locale('en-US', 'en', 'US', 1.0), new Locale('en', 'en', '', 0.8), new Locale('nl-NL', 'nl', 'NL', 0.6), ]); $this->assertEquals(['en-US', 'en', 'nl-NL'], $locales); } /** @test */ public function it_returns_an_empty_array_if_no_locales_exist() { $locales = (new LocaleFilter)->filter([]); $this->assertEquals([], $locales); } }
<?php namespace CodeZero\BrowserLocale\Tests\Filters; use CodeZero\BrowserLocale\Filters\LocaleFilter; use CodeZero\BrowserLocale\Locale; use PHPUnit\Framework\TestCase; class BrowserLocaleTest extends TestCase { /** @test */ public function it_filters_a_simple_array_of_locales() { $locales = (new LocaleFilter)->filter([ new Locale('en-US', 'en', 'US', 1.0), new Locale('en', 'en', '', 0.8), new Locale('nl-NL', 'nl', 'NL', 0.6), ]); $this->assertEquals(['en-US', 'en', 'nl-NL'], $locales); } /** @test */ public function it_returns_an_empty_array_if_no_locales_exist() { $locales = (new LocaleFilter)->filter([]); $this->assertEquals([], $locales); } }
Introduce scope_types in FIP pools Appropriate scope_type for nova case: - https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope This commit introduce scope_type for FIP pools policies as 'system' and 'project' Partial implement blueprint policy-defaults-refresh-deprecated-apis Change-Id: Ica29330ac8c22a40bbf5e88ef554bbc44e1ac293
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-floating-ip-pools' floating_ip_pools_policies = [ policy.DocumentedRuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER, description="List floating IP pools. This API is deprecated.", operations=[ { 'method': 'GET', 'path': '/os-floating-ip-pools' } ], scope_types=['system', 'project']), ] def list_rules(): return floating_ip_pools_policies
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-floating-ip-pools' floating_ip_pools_policies = [ policy.DocumentedRuleDefault( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, "List floating IP pools. This API is deprecated.", [ { 'method': 'GET', 'path': '/os-floating-ip-pools' } ]), ] def list_rules(): return floating_ip_pools_policies
Remove duplicated key from dict in Semantic Scholar
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
Handle exceptions without app instantiated
<?php /* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. --- Initially developed on PHP version: 5.3.3-7+squeeze */ try { require_once 'pwm.php'; $pwm = new pwm(); if( $pwm->authentication() ) { $pwm->passwordManager(); } } catch ( Exception $e ) { if( is_object( $pwm ) ) { $pwm->alert( $e->getMessage(), ALERT_ERROR ); } else { die( 'Error: ' . $e->getMessage() ); } } $pwm->render();
<?php /* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. --- Initially developed on PHP version: 5.3.3-7+squeeze */ try { require_once 'pwm.php'; $pwm = new pwm(); if( $pwm->authentication() ) { $pwm->passwordManager(); } } catch ( Exception $e ) { $pwm->alert( $e->getMessage(), ALERT_ERROR ); # die( 'Error: ' . $e->getMessage() ); } $pwm->render();
Set webpack mode to production always
const path = require('path'); module.exports = { entry: './src/index.ts', output: { path: path.resolve(__dirname + '/dist'), filename: 'index.js', library: 'ReactWhiteboard', libraryTarget: 'umd' }, module: { rules: [{ test: /\.tsx?$/, exclude: /node_modules/, use: { loader: 'ts-loader' } }] }, resolve: { extensions: [ '.tsx', '.ts', '.js' ] }, externals: { 'react': 'react', 'react-dom': 'react-dom' }, mode: 'production', devtool: 'source-map' };
const path = require('path'); module.exports = { entry: './src/index.ts', output: { path: path.resolve(__dirname + '/dist'), filename: 'index.js', library: 'ReactWhiteboard', libraryTarget: 'umd' }, module: { rules: [{ test: /\.tsx?$/, exclude: /node_modules/, use: { loader: 'ts-loader' } }] }, resolve: { extensions: [ '.tsx', '.ts', '.js' ] }, externals: { 'react': 'react', 'react-dom': 'react-dom' }, mode: process.env.WEBPACK_SERVE ? 'development' : 'production', devtool: 'source-map' };
Revert "Fixed error in test package." This reverts commit 39bacc609f4a1ffd64f5469f32b1384cf56f9610.
package test; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; import play.mvc.Content; import static play.test.Helpers.contentType; import static play.test.Helpers.contentAsString; /** * * Simple (JUnit) tests that can call all parts of a play app. If you are interested in mocking a whole application, see * the wiki for more details. * */ public class ApplicationTest { /** * Illustrates a simple test. */ @Test public void simpleCheck() { int a = 1 + 1; assertThat(a).isEqualTo(2); } /** * Illustrates how to render a template for testing. */ @Test public void renderTemplate() { Content html = views.html.Index.render("Welcome to the home page."); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)).contains("home page"); } }
package test; import models.ContactDB; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; import play.mvc.Content; import static play.test.Helpers.contentType; import static play.test.Helpers.contentAsString; /** * * Simple (JUnit) tests that can call all parts of a play app. If you are interested in mocking a whole application, see * the wiki for more details. * */ public class ApplicationTest { /** * Illustrates a simple test. */ @Test public void simpleCheck() { int a = 1 + 1; assertThat(a).isEqualTo(2); } /** * Illustrates how to render a template for testing. */ @Test public void renderTemplate() { Content html = views.html.Index.render(ContactDB.getContacts()); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)).contains("home page"); } }
Fix the collection used for retrieving survey reports
<?php namespace App\View\Components; use App\Models\TestDate; use Illuminate\View\Component; class SurveyReportLink extends Component { /** * Survey ID. * * @int $surveyID */ public $surveyID; /** * Survey report link. * * @string $surveyLink */ public $surveyLink; /** * Create a new component instance. * * * @param int $surveyID * * @return void */ public function __construct(?int $surveyID) { $this->surveyID = $surveyID; $survey = TestDate::find($this->surveyID); if (!is_null($survey) && $survey->hasMedia('survey_reports')) { $this->surveyLink = $survey->getFirstMediaUrl('survey_reports'); } else { $this->surveyLink = null; } } /** * Get the view / contents that represent the component. * * @return \Illuminate\Contracts\View\View|\Closure|string */ public function render() { return view('components.survey-report-link'); } }
<?php namespace App\View\Components; use App\Models\TestDate; use Illuminate\View\Component; class SurveyReportLink extends Component { /** * Survey ID. * * @int $surveyID */ public $surveyID; /** * Survey report link. * * @string $surveyLink */ public $surveyLink; /** * Create a new component instance. * * * @param int $surveyID * * @return void */ public function __construct(?int $surveyID) { $this->surveyID = $surveyID; $survey = TestDate::find($this->surveyID); if (!is_null($survey) && $survey->hasMedia('survey_report')) { $this->surveyLink = $survey->getFirstMediaUrl('survey_report'); } else { $this->surveyLink = null; } } /** * Get the view / contents that represent the component. * * @return \Illuminate\Contracts\View\View|\Closure|string */ public function render() { return view('components.survey-report-link'); } }
Use current host name for redirect url
<?php use TOL\PhotoHack\Youtube; function hostName() { $protocol = $_SERVER['HTTPS'] ? 'https://' : 'http://'; $serverName = $_SERVER['SERVER_NAME']; return $protocol . $serverName; } return function($app) { $twigView = new \Slim\Views\Twig(); $twigView->parserOptions = ['autoescape' => false]; $app->config('templates.path', __DIR__ . '/templates'); $view = $app->view($twigView); $view->parserExtensions = [new \Slim\Views\TwigExtension()]; $app->container->singleton('youtube', function() use($app) { return new Youtube($app->client); }); $app->container->singleton('client', function() use($app) { $client = new Google_Client(); $client->setClientId(getenv('YOUTUBE_CLIENT_ID')); $client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET')); $client->setScopes('https://www.googleapis.com/auth/youtube'); $serverName = hostName(); $client->setRedirectUri("{$serverName}/share"); $token = $app->getCookie('token'); if ($token) { $client->setAccessToken($token); } return $client; }); };
<?php use TOL\PhotoHack\Youtube; return function($app) { $twigView = new \Slim\Views\Twig(); $twigView->parserOptions = ['autoescape' => false]; $app->config('templates.path', __DIR__ . '/templates'); $view = $app->view($twigView); $view->parserExtensions = [new \Slim\Views\TwigExtension()]; $app->container->singleton('youtube', function() use($app) { return new Youtube($app->client); }); $app->container->singleton('client', function() use($app) { $client = new Google_Client(); $client->setClientId(getenv('YOUTUBE_CLIENT_ID')); $client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET')); $client->setScopes('https://www.googleapis.com/auth/youtube'); $client->setRedirectUri('http://local.photohack.com/share'); $token = $app->getCookie('token'); if ($token) { $client->setAccessToken($token); } return $client; }); };
Update to core start button button colour
/* Copyright 2016 Paul Bevis 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. */ 'use strict'; import React, {Component, PropTypes} from 'react' import FoundWords from './found-words' import SubmittedLetters from './submitted-letters' import RaisedButton from 'material-ui/lib/raised-button'; export default class PlayArea extends Component { render() { return ( <div style={{display:'flex',flexDirection:'column', height:'100%'}}> <div className='button-controls' style={{marginTop:'10px'}}> <RaisedButton label="Start" primary={true} onClick={this.props.onStartGame}/> </div> <div style={{display:'flex', flexGrow:'1'}}> <SubmittedLetters foundLetters={this.props.game.foundLetters} status={this.props.game.status}/> <FoundWords foundWords={this.props.game.foundWords} status={this.props.game.status} onPlayWord={this.props.onPlayWord}/> </div> </div> ) } }
/* Copyright 2016 Paul Bevis 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. */ 'use strict'; import React, {Component, PropTypes} from 'react' import FoundWords from './found-words' import SubmittedLetters from './submitted-letters' import RaisedButton from 'material-ui/lib/raised-button'; export default class PlayArea extends Component { render() { return ( <div style={{display:'flex',flexDirection:'column', height:'100%'}}> <div className='button-controls' style={{marginTop:'10px'}}> <RaisedButton label="Start" secondary={true} onClick={this.props.onStartGame}/> </div> <div style={{display:'flex', flexGrow:'1'}}> <SubmittedLetters foundLetters={this.props.game.foundLetters} status={this.props.game.status}/> <FoundWords foundWords={this.props.game.foundWords} status={this.props.game.status} onPlayWord={this.props.onPlayWord}/> </div> </div> ) } }
Add enabled key, and if all other keys are empty use default vals
const mongoose = require('mongoose') const middleware = require('./middleware/Feed.js') const path = require('path') const fs = require('fs') const packageVersion = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'))).version const schema = new mongoose.Schema({ title: { type: String, required: true }, url: { type: String, required: true }, guild: { type: String, required: true }, channel: { type: String, required: true }, webhook: { id: String, name: String, avatar: String }, split: { enabled: Boolean, char: String, prepend: String, append: String, maxLength: Number }, disabled: String, checkTitles: Boolean, checkDates: Boolean, imgPreviews: Boolean, imgLinksExistence: Boolean, formatTables: Boolean, toggleRoleMentions: Boolean, version: { type: String, default: packageVersion }, addedAt: { type: Date, default: Date.now } }) schema.pre('findOneAndUpdate', middleware.findOneAndUpdate) schema.pre('remove', middleware.remove) schema.pre('save', middleware.save) exports.schema = schema exports.model = mongoose.model('Feed', schema)
const mongoose = require('mongoose') const middleware = require('./middleware/Feed.js') const path = require('path') const fs = require('fs') const packageVersion = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'))).version const schema = new mongoose.Schema({ title: { type: String, required: true }, url: { type: String, required: true }, guild: { type: String, required: true }, channel: { type: String, required: true }, webhook: { id: String, name: String, avatar: String }, split: { char: String, prepend: String, append: String, maxLength: Number }, disabled: String, checkTitles: Boolean, checkDates: Boolean, imgPreviews: Boolean, imgLinksExistence: Boolean, formatTables: Boolean, toggleRoleMentions: Boolean, version: { type: String, default: packageVersion }, addedAt: { type: Date, default: Date.now } }) schema.pre('findOneAndUpdate', middleware.findOneAndUpdate) schema.pre('remove', middleware.remove) schema.pre('save', middleware.save) exports.schema = schema exports.model = mongoose.model('Feed', schema)
Return emoji object in search results
import lunr from 'lunr' import data from '../../data' var emoticonsList = [] var index = lunr(function() { this.pipeline.reset() this.field('short_name', { boost: 2 }) this.field('emoticons') this.field('name') this.ref('id') }) for (let emoji in data.emojis) { let emojiData = data.emojis[emoji], { short_name, name, emoticons } = emojiData for (let emoticon of emoticons) { if (emoticonsList.indexOf(emoticon) == -1) { emoticonsList.push(emoticon) } } index.add({ id: short_name, emoticons: emoticons, short_name: tokenize(short_name), name: tokenize(name), }) } function search(value, maxResults = 75) { var results = null if (value.length) { results = index.search(tokenize(value)).map((result) => data.emojis[result.ref] ) results = results.slice(0, maxResults) } return results } function tokenize (string = '') { if (string[0] == '-' || string[0] == '+') { return string.split('') } if (/(:|;|=)-/.test(string)) { return [string] } return string.split(/[-|_|\s]+/) } export default { search, emoticons: emoticonsList }
import lunr from 'lunr' import data from '../../data' var emoticonsList = [] var index = lunr(function() { this.pipeline.reset() this.field('short_name', { boost: 2 }) this.field('emoticons') this.field('name') this.ref('id') }) for (let emoji in data.emojis) { let emojiData = data.emojis[emoji], { short_name, name, emoticons } = emojiData for (let emoticon of emoticons) { if (emoticonsList.indexOf(emoticon) == -1) { emoticonsList.push(emoticon) } } index.add({ id: short_name, emoticons: emoticons, short_name: tokenize(short_name), name: tokenize(name), }) } function search(value, maxResults = 75) { var results = null if (value.length) { results = index.search(tokenize(value)).map((result) => result.ref ) results = results.slice(0, maxResults) } return results } function tokenize (string = '') { if (string[0] == '-' || string[0] == '+') { return string.split('') } if (/(:|;|=)-/.test(string)) { return [string] } return string.split(/[-|_|\s]+/) } export default { search, emoticons: emoticonsList }
Change euler integrator to return list, not array The state of the system is a heterogeneous data type for some applications, so the array isn't appropriate.
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' return A @ B - B @ A def D(c, rho): '''Calculate the application of the diffusion superoperator D[c] to rho ''' c_dag = c.conjugate().T return c @ rho @ c_dag - (c_dag @ c @ rho + rho @ c_dag @ c) / 2 def euler_integrate(rho_0, rho_dot_fn, times): rhos = [rho_0] dts = np.diff(times) for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) return rhos
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' return A @ B - B @ A def D(c, rho): '''Calculate the application of the diffusion superoperator D[c] to rho ''' c_dag = c.conjugate().T return c @ rho @ c_dag - (c_dag @ c @ rho + rho @ c_dag @ c) / 2 def euler_integrate(rho_0, rho_dot_fn, times): rhos = [rho_0] dts = np.diff(times) for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) return np.array(rhos)
Raise not Found on schema item_type error.
from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32) config.add_route('schema', '/profiles/{item_type}.json') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] try: collection = context.by_item_type[item_type] except KeyError: raise HTTPNotFound(item_type) return collection.schema
from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32) config.add_route('schema', '/profiles/{item_type}.json') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] collection = context.by_item_type[item_type] return collection.schema
Disable generating favicons for discontinued Opera Coast and Firefox OS
const offsetIcon = { offset: 15, background: '#fff', }; module.exports = { developerName: 'Proton AG', developerURL: 'https://github.com/ProtonMail/WebClients', background: '#fff', theme_color: '#1b1340', appleStatusBarStyle: 'default', display: 'standalone', start_url: '/', loadManifestWithCredentials: true, icons: { android: offsetIcon, appleIcon: offsetIcon, appleStartup: false, // Only interested in the .ico file, not the custom 16x16, 32x32 pngs it generates // because we default to a .svg favicon (with our own custom implementation because // the favicons library (6.x) doesn't support it by default) favicons: ['favicon.ico'], coast: false, firefox: false, windows: offsetIcon, yandex: offsetIcon, }, };
const offsetIcon = { offset: 15, background: '#fff', }; module.exports = { developerName: 'Proton AG', developerURL: 'https://github.com/ProtonMail/WebClients', background: '#fff', theme_color: '#1b1340', appleStatusBarStyle: 'default', display: 'standalone', start_url: '/', loadManifestWithCredentials: true, icons: { android: offsetIcon, appleIcon: offsetIcon, appleStartup: false, // Only interested in the .ico file, not the custom 16x16, 32x32 pngs it generates // because we default to a .svg favicon (with our own custom implementation because // the favicons library (6.x) doesn't support it by default) favicons: ['favicon.ico'], windows: offsetIcon, yandex: offsetIcon, }, };
Fix typo in 'mach cargo --help'
from __future__ import print_function, unicode_literals import json import os import os.path as path import shutil import subprocess import sys import tarfile from time import time import urllib from mach.registrar import Registrar from mach.decorators import ( CommandArgument, CommandProvider, Command, ) from servo.command_base import CommandBase @CommandProvider class MachCommands(CommandBase): @Command('cargo', description='Run Cargo', category='devenv', allow_all_args=True) @CommandArgument('params', default=None, nargs='...', help="Command-line arguments to be passed through to Cargo") def run(self, params): return subprocess.call(["cargo"] + params, env=self.build_env())
from __future__ import print_function, unicode_literals import json import os import os.path as path import shutil import subprocess import sys import tarfile from time import time import urllib from mach.registrar import Registrar from mach.decorators import ( CommandArgument, CommandProvider, Command, ) from servo.command_base import CommandBase @CommandProvider class MachCommands(CommandBase): @Command('cargo', description='Run Cargo', category='devenv', allow_all_args=True) @CommandArgument('params', default=None, nargs='...', help="Command-line arguments to be passed through to Cervo") def run(self, params): return subprocess.call(["cargo"] + params, env=self.build_env())
Add message_age property to ParsedMessage
# # 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 time from typing import List from rpe.resources import Resource from pydantic import BaseModel, Field # Parser-supplied metadata is arbitrary, but some fields are required # currently just `src` class MessageMetadata(BaseModel): src: str class Config: extra = 'allow' class EnforcerControlData(BaseModel): enforce: bool = True delay_enforcement: bool = True class Config: extra = 'forbid' class ParsedMessage(BaseModel): metadata: MessageMetadata resources: List[Resource] control_data: EnforcerControlData = EnforcerControlData() timestamp: int = Field(default_factory=time.time) class Config: arbitrary_types_allowed = True extra = 'forbid' @property def age(self): return int(time.time()) - self.timestamp
# # 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 time from typing import List from rpe.resources import Resource from pydantic import BaseModel, Field # Parser-supplied metadata is arbitrary, but some fields are required # currently just `src` class MessageMetadata(BaseModel): src: str class Config: extra = 'allow' class EnforcerControlData(BaseModel): enforce: bool = True delay_enforcement: bool = True class Config: extra = 'forbid' class ParsedMessage(BaseModel): metadata: MessageMetadata resources: List[Resource] control_data: EnforcerControlData = EnforcerControlData() timestamp: int = Field(default_factory=time.time) class Config: arbitrary_types_allowed = True extra = 'forbid'
Throw exceptions properly when running tests
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if (\App::environment() == 'testing') { throw $e; } else { return parent::render($request, $e); } } }
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
Fix single word command parsing
//Start up scheduled tasks require('./cronjobs.js'); require('dotenv').config(); var login = require('facebook-chat-api'); var commandDescriptions = require('./modules.json'); var prefixLen = 1; var commands = commandDescriptions .map(function(cmd) { return require('./' + cmd['path']); }); login({email: process.env.BOT_USERNAME, password: process.env.BOT_PASSWORD}, loginCallback); function loginCallback(err, api) { if(err) return console.error(err); api.listen(function callback(err, message) { if(isCommand(message)) { var commandString = message.body.slice(prefixLen); var trigger = commandString.substring(0, endOfCmd(commandString)); commands.forEach(function(cmd, index) { if(trigger == commandDescriptions[index]['trigger']) { cmd.trigger(commandString.slice(trigger.length+1), message.threadID, api); } }); } }); } function endOfCmd(cmd) { if(cmd.indexOf(' ') > 0) { return cmd.indexOf(' '); } else { return cmd.length; } } function isCommand(message) { if(!(message && message.body)) { return false; } else if(process.env.USE_PREFIX == 'true') { prefixLen = process.env.BOT_PREFIX.length + 1; return message.body.startsWith(process.env.BOT_PREFIX); } else { return message.body.startsWith('/'); } }
//Start up scheduled tasks require('./cronjobs.js'); require('dotenv').config(); var login = require('facebook-chat-api'); var commandDescriptions = require('./modules.json'); var prefixLen = 1; var commands = commandDescriptions .map(function(cmd) { return require('./' + cmd['path']); }); login({email: process.env.BOT_USERNAME, password: process.env.BOT_PASSWORD}, loginCallback); function loginCallback(err, api) { if(err) return console.error(err); api.listen(function callback(err, message) { if(isCommand(message)) { var commandString = message.body.slice(prefixLen); var trigger = commandString.substring(0, commandString.indexOf(' ')); commands.forEach(function(cmd, index) { if(trigger == commandDescriptions[index]['trigger']) { cmd.trigger(commandString.slice(trigger.length+1), message.threadID, api); } }); } }); } function isCommand(message) { if(!(message && message.body)) { return false; } else if(process.env.USE_PREFIX == 'true') { prefixLen = process.env.BOT_PREFIX.length + 1; return message.body.startsWith(process.env.BOT_PREFIX); } else { return message.body.startsWith('/'); } }
Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything.
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = path + '/' + f if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) else: if f.endswith('.lua'): files.append(path + '/' + f) return files def generate_bundle_map(module_name, path, is_base=False): t = [] for os_filename in file_list(path): bundle_filename = (os_filename.replace(path, '')[1:]) if is_base: bundle_filename = 'modules/' + bundle_filename else: bundle_filename = module_name + '/' + bundle_filename t.append({ 'os_filename': os_filename, 'bundle_filename': bundle_filename }) return t try: opts, args = getopt.getopt(sys.argv[1:], 'lb', []) except: sys.exit(2) if __name__ == '__main__': module_path = args[0] module_name = os.path.basename(module_path) for o, a in opts: if o == '-l': for path in args: print('\n'.join(file_list(path))) elif o == '-b': for path in args: print(generate_bundle_map(module_name, path))
#!/usr/bin/env python import os import sys import glob import getopt def file_list(path): files = [] if os.path.isfile(path): return [path] for f in os.listdir(path): new_dir = os.path.join(path, f) if os.path.isdir(new_dir) and not os.path.islink(new_dir): files.extend(file_list(new_dir)) else: if f.endswith('.lua'): files.append(path + '/' + f) return files def generate_bundle_map(module_name, path, is_base=False): t = [] for os_filename in file_list(path): bundle_filename = (os_filename.replace(path, '')[1:]) if is_base: bundle_filename = 'modules/' + bundle_filename else: bundle_filename = module_name + '/' + bundle_filename t.append({ 'os_filename': os_filename, 'bundle_filename': bundle_filename }) return t try: opts, args = getopt.getopt(sys.argv[1:], 'lb', []) except: sys.exit(2) if __name__ == '__main__': module_path = args[0] module_name = os.path.basename(module_path) for o, a in opts: if o == '-l': for path in args: print('\n'.join(file_list(path))) elif o == '-b': for path in args: print(generate_bundle_map(module_name, path))
Move from old to new array notation in one file StyleCI complained about that....
<?php namespace Form\Listener; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Form\Shared\UrlResolver; /** * Follows a submitted URL to find the actual protocol and final address * */ class GetResolvedUrlListener implements EventSubscriberInterface { public function onSubmit(FormEvent $event) { $data = $event->getData(); if ($data === '') { return; } if ($data === null) { return; } $resolver = new UrlResolver(); try { $redirectURL = $resolver->resolve($data); $event->setData($redirectURL); } catch (\Exception $e) { // We can do nothing with this now, this will be caught by the constraint } } public static function getSubscribedEvents() { return [FormEvents::SUBMIT => 'onSubmit']; } }
<?php namespace Form\Listener; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Form\Shared\UrlResolver; /** * Follows a submitted URL to find the actual protocol and final address * */ class GetResolvedUrlListener implements EventSubscriberInterface { public function onSubmit(FormEvent $event) { $data = $event->getData(); if ($data === '') { return; } if ($data === null) { return; } $resolver = new UrlResolver(); try { $redirectURL = $resolver->resolve($data); $event->setData($redirectURL); } catch (\Exception $e) { // We can do nothing with this now, this will be caught by the constraint } } public static function getSubscribedEvents() { return array(FormEvents::SUBMIT => 'onSubmit'); } }
Test the constructor with initial value.
package com.github.platinumrondo.clickcount.model; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.Random; public class SingleIncrementCountModelTest { private SingleIncrementCountModel model; @Before public void setUp() { model = new SingleIncrementCountModel(); } @Test public void testConstructorWithInitialValue() { Random r = new Random(); int initialValue = r.nextInt(); model = new SingleIncrementCountModel(initialValue); assertEquals(initialValue, model.get()); } @Test public void testIncrement() { model.increment(); assertEquals(1, model.get()); } @Test public void testGet() { assertEquals(0, model.get()); } @Test public void testReset() { model.reset(); assertEquals(0, model.get()); } }
package com.github.platinumrondo.clickcount.model; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SingleIncrementCountModelTest { private SingleIncrementCountModel model; @Before public void setUp() { model = new SingleIncrementCountModel(); } @Test public void testIncrement() { model.increment(); assertEquals(1, model.get()); } @Test public void testGet() { assertEquals(0, model.get()); } @Test public void testReset() { model.reset(); assertEquals(0, model.get()); } }
Rename basicParser variable to pegParser
(function () { /* jshint maxstatements: 1000 */ 'use strict'; var pegParser; pegParser = require('./parser.peg.js'); /** * [newpage] * [chapter:.*] * [pixivimage:\d*(-\d*)?] * [jump:\d*] * [[jumpuri:.* > URL]] * * [ruby: rb > rt] * [emoji:.*] * [strong:.*] */ function Parser() { this.tree = []; } /** * @param {string} novel * @return {Object.<string,Object>[]} */ Parser.parse = function (novel) { try { novel = novel.replace(/\r?\n/g, '\n'). replace(/[\s\u200c]/g, function (c) { if (c === '\n' || c === '\u3000') { return c; } return ' '; }); return pegParser.parse(novel); } catch (err) { console.error(err); return [{ type: 'text', val: novel }]; } }; /** * @param {string} novel * @return {Parser} */ Parser.prototype.parse = function (novel) { this.tree = Parser.parse(novel); return this; }; /** * @return {string} */ Parser.prototype.toJSON = function () { return JSON.stringify(this.tree); }; module.exports = { Parser: Parser }; }());
(function () { /* jshint maxstatements: 1000 */ 'use strict'; var basicParser; basicParser = require('./parser.peg.js'); /** * [newpage] * [chapter:.*] * [pixivimage:\d*(-\d*)?] * [jump:\d*] * [[jumpuri:.* > URL]] * * [ruby: rb > rt] * [emoji:.*] * [strong:.*] */ function Parser() { this.tree = []; } /** * @param {string} novel * @return {Object.<string,Object>[]} */ Parser.parse = function (novel) { try { novel = novel.replace(/\r?\n/g, '\n'). replace(/[\s\u200c]/g, function (c) { if (c === '\n' || c === '\u3000') { return c; } return ' '; }); return basicParser.parse(novel); } catch (err) { console.error(err); return [{ type: 'text', val: novel }]; } }; /** * @param {string} novel * @return {Parser} */ Parser.prototype.parse = function (novel) { this.tree = Parser.parse(novel); return this; }; /** * @return {string} */ Parser.prototype.toJSON = function () { return JSON.stringify(this.tree); }; module.exports = { Parser: Parser }; }());
Replace \n by <br/> when we use text as html
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text.replace(/\n/g, '<br/>\n'); } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } if(changes.metadata.text) { config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text; } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } if(changes.metadata.text) { config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); } finalCb(null, changes); };
Debug sending data w/ boto.
import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
Add hashing in build HMTL
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true, hash: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
:rocket: Add Symptoms and ObservedSymptoms to Admin
from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 2 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom)
from django.contrib import admin from .models import Patient, PatientRegister, FluVaccine, Sample, CollectionType class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ] admin.site.register(Patient) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(PatientRegister, PatientRegisterAdmin)
Hide draft events from public event list
module.exports = () => (hook) => { const sequelize = hook.app.get('sequelize'); hook.params.sequelize = { attributes: [ 'id', 'title', 'date', 'registrationStartDate', 'registrationEndDate', 'openQuotaSize', 'signupsPublic', ], distinct: true, raw: false, // Filter out events that are saved as draft where: { draft: 0, }, // Include quotas of event and count of signups include: [ { model: sequelize.models.quota, attributes: ['title', 'size', [sequelize.fn('COUNT', sequelize.col('quota->signups.id')), 'signupCount']], include: [ { model: sequelize.models.signup, attributes: [], }, ], }, ], group: [sequelize.col('event.id'), sequelize.col('quota.id')], }; };
module.exports = () => (hook) => { const sequelize = hook.app.get('sequelize'); hook.params.sequelize = { attributes: [ 'id', 'title', 'date', 'registrationStartDate', 'registrationEndDate', 'openQuotaSize', 'signupsPublic', ], distinct: true, raw: false, // Include quotas of event and count of signups include: [ { model: sequelize.models.quota, attributes: ['title', 'size', [sequelize.fn('COUNT', sequelize.col('quota->signups.id')), 'signupCount']], include: [ { model: sequelize.models.signup, attributes: [], }, ], }, ], group: [sequelize.col('event.id'), sequelize.col('quota.id')], }; };
Add `revoke` method to Screenboard - This method allow to revoke the public access of a shared screenboard
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource): """ A wrapper around Screenboard HTTP API. """ _class_name = 'screen' _class_url = '/screen' _json_name = 'board' @classmethod def share(cls, board_id): """ Share the screenboard with given id :param board_id: screenboard to share :type board_id: id :returns: JSON response from HTTP request """ return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id) @classmethod def revoke(cls, board_id): """ Revoke a shared screenboard with given id :param board_id: screenboard to revoke :type board_id: id :returns: JSON response from HTTP request """ return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id)
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource): """ A wrapper around Screenboard HTTP API. """ _class_name = 'screen' _class_url = '/screen' _json_name = 'board' @classmethod def share(cls, board_id): """ Share the screenboard with given id :param board_id: screenboard to share :type board_id: id :returns: JSON response from HTTP request """ return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
Use new output formatters feature @single-field-default to reduce table data down to a single element when 'string' format is selected.
<?php namespace Pantheon\Terminus\Commands\Auth; use Pantheon\Terminus\Commands\TerminusCommand; use Terminus\Models\Auth; use Consolidation\OutputFormatters\StructuredData\AssociativeList; class WhoamiCommand extends TerminusCommand { /** * Displays information about the user currently logged in * * @command auth:whoami * @aliases whoami * * @field-labels * firstname: First Name * lastname: Last Name * email: eMail * id: ID * @single-field-default email * @usage terminus auth:whoami * Responds with the email of the logged-in user * @usage terminus auth:whoami --format=table * Responds with the current session and user's data * @return string */ public function whoAmI($options = ['format' => 'string', 'fields' => '']) { $auth = new Auth(); if ($auth->loggedIn()) { $user = $this->session()->getUser(); return new AssociativeList($user->fetch()->serialize()); } else { $this->log()->notice('You are not logged in.'); return null; } } }
<?php namespace Pantheon\Terminus\Commands\Auth; use Pantheon\Terminus\Commands\TerminusCommand; use Terminus\Models\Auth; class WhoamiCommand extends TerminusCommand { /** * Displays information about the user currently logged in * * @command auth:whoami * @aliases whoami * * @usage terminus auth:whoami * Responds with the email of the logged-in user * @usage terminus auth:whoami -vvv * Responds with the current session and user's data * @return string */ public function whoAmI() { $auth = new Auth(); if ($auth->loggedIn()) { $user = $this->session()->getUser(); $this->log()->debug(print_r($user->fetch()->serialize(), true)); return $user->get('email'); } else { $this->log()->notice('You are not logged in.'); return null; } } }
Fix set notation for Python 2.6
"""Application-specific settings for django-authorizenet""" from django.conf import settings as django_settings class Settings(object): """ Retrieves django.conf settings, using defaults from Default subclass All usable settings are specified in settings attribute. Use an ``AUTHNET_`` prefix when specifying settings in django.conf. """ prefix = 'AUTHNET_' settings = set(('DEBUG', 'LOGIN_ID', 'TRANSACTION_KEY', 'CUSTOMER_MODEL', 'DELIM_CHAR', 'FORCE_TEST_REQUEST', 'EMAIL_CUSTOMER', 'MD5_HASH')) class Default: CUSTOMER_MODEL = getattr( django_settings, 'AUTH_USER_MODEL', "auth.User") DELIM_CHAR = "|" FORCE_TEST_REQUEST = False EMAIL_CUSTOMER = None MD5_HASH = "" def __init__(self): self.defaults = Settings.Default() def __getattr__(self, name): if name not in self.settings: raise AttributeError("Setting %s not understood" % name) try: return getattr(django_settings, self.prefix + name) except AttributeError: return getattr(self.defaults, name) settings = Settings()
"""Application-specific settings for django-authorizenet""" from django.conf import settings as django_settings class Settings(object): """ Retrieves django.conf settings, using defaults from Default subclass All usable settings are specified in settings attribute. Use an ``AUTHNET_`` prefix when specifying settings in django.conf. """ prefix = 'AUTHNET_' settings = {'DEBUG', 'LOGIN_ID', 'TRANSACTION_KEY', 'CUSTOMER_MODEL', 'DELIM_CHAR', 'FORCE_TEST_REQUEST', 'EMAIL_CUSTOMER', 'MD5_HASH'} class Default: CUSTOMER_MODEL = getattr( django_settings, 'AUTH_USER_MODEL', "auth.User") DELIM_CHAR = "|" FORCE_TEST_REQUEST = False EMAIL_CUSTOMER = None MD5_HASH = "" def __init__(self): self.defaults = Settings.Default() def __getattr__(self, name): if name not in self.settings: raise AttributeError("Setting %s not understood" % name) try: return getattr(django_settings, self.prefix + name) except AttributeError: return getattr(self.defaults, name) settings = Settings()
Revert "Remove not used imports" This reverts commit 85706eb3faffe65b77432a46cde0ff9fe2a4312f.
package org.synyx.urlaubsverwaltung.mail; import org.hibernate.validator.constraints.URL; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; @Validated @ConfigurationProperties(prefix = "uv.mail") public class MailProperties { @Email @NotEmpty private String sender; @Email @NotEmpty private String administrator; @URL private String applicationUrl; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getAdministrator() { return administrator; } public void setAdministrator(String administrator) { this.administrator = administrator; } public String getApplicationUrl() { return applicationUrl; } public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } }
package org.synyx.urlaubsverwaltung.mail; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; @Validated @ConfigurationProperties(prefix = "uv.mail") public class MailProperties { @Email @NotEmpty private String sender; @Email @NotEmpty private String administrator; @URL private String applicationUrl; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getAdministrator() { return administrator; } public void setAdministrator(String administrator) { this.administrator = administrator; } public String getApplicationUrl() { return applicationUrl; } public void setApplicationUrl(String applicationUrl) { this.applicationUrl = applicationUrl; } }
Set jQuery to noConflict mode for better compatability
/* ============================================================= * tabby.js * Simple, mobile-first toggle tabs. * Script by Chris Ferdinandi - http://gomakethings.com * Licensed under WTFPL - http://www.wtfpl.net * ============================================================= */ (function($) { $(function () { $('.tabs a').click(function(e) { e.preventDefault(); // Prevent default link behavior. var tabID = $(this).attr('href'); // Pull the href value as the tabID. $(this).addClass('active').parent().addClass('active'); // Add the .active class to the link and it's parent li (if one exists). $(this).siblings().removeClass('active'); // Remove the .active class from sibling tab navigation elements. $(this).parent('li').siblings().removeClass('active').children().removeClass('active'); // Remove the .active class from sibling li elements and their links. $(tabID).addClass('active'); // Add the .active class to the div with the tab content. $(tabID).siblings().removeClass('active'); // Remove the .active class from other tab content divs. }); }); })(jQuery); /* ============================================================= * js-accessibility.js * Adds .js class to <body> for progressive enhancement. * Script by Chris Ferdinandi - http://gomakethings.com * Licensed under WTFPL - http://www.wtfpl.net * ============================================================= */ (function($) { $(function () { $('body').addClass('js'); // On page load, add the .js class to the <body> element. }); })(jQuery);
/* ============================================================= * tabby.js v1.0 * Simple, mobile-first toggle tabs. * Script by Chris Ferdinandi - http://gomakethings.com * Licensed under WTFPL - http://www.wtfpl.net * ============================================================= */ $(function () { $('.tabs a').click(function(e) { e.preventDefault(); // Prevent default link behavior. var tabID = $(this).attr('href'); // Pull the href value as the tabID. $(this).addClass('active').parent().addClass('active'); // Add the .active class to the link and it's parent li (if one exists). $(this).siblings().removeClass('active'); // Remove the .active class from sibling tab navigation elements. $(this).parent('li').siblings().removeClass('active').children().removeClass('active'); // Remove the .active class from sibling li elements and their links. $(tabID).addClass('active'); // Add the .active class to the div with the tab content. $(tabID).siblings().removeClass('active'); // Remove the .active class from other tab content divs. }); }); /* ============================================================= * js-accessibility.js v1.0.0 * Adds .js class to <body> for progressive enhancement. * Script by Chris Ferdinandi - http://gomakethings.com * Licensed under WTFPL - http://www.wtfpl.net * ============================================================= */ $(function () { $('body').addClass('js'); // On page load, add the .js class to the <body> element. });
Break destroy calling when not initialized
// Save the other cropper Cropper.other = $.fn.cropper; // Register as jQuery plugin $.fn.cropper = function (options) { var args = toArray(arguments, 1), result; this.each(function () { var $this = $(this), data = $this.data('cropper'), fn; if (!data) { if (/destroy/.test(options)) { return; } $this.data('cropper', (data = new Cropper(this, options))); } if (typeof options === 'string' && $.isFunction((fn = data[options]))) { result = fn.apply(data, args); } }); return isUndefined(result) ? this : result; }; $.fn.cropper.Constructor = Cropper; $.fn.cropper.setDefaults = Cropper.setDefaults; // No conflict $.fn.cropper.noConflict = function () { $.fn.cropper = Cropper.other; return this; };
// Save the other cropper Cropper.other = $.fn.cropper; // Register as jQuery plugin $.fn.cropper = function (options) { var args = toArray(arguments, 1), result; this.each(function () { var $this = $(this), data = $this.data('cropper'), fn; if (!data) { $this.data('cropper', (data = new Cropper(this, options))); } if (typeof options === 'string' && $.isFunction((fn = data[options]))) { result = fn.apply(data, args); } }); return isUndefined(result) ? this : result; }; $.fn.cropper.Constructor = Cropper; $.fn.cropper.setDefaults = Cropper.setDefaults; // No conflict $.fn.cropper.noConflict = function () { $.fn.cropper = Cropper.other; return this; };
Add charset to HTML5 doc (and make more XHTML friendly)
<!DOCTYPE html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script> </head><body></body> </html>
<!doctype html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script>
Refactor to clean up code
var intersection = require('robust-segment-intersect') var assert = require('assert') var util = require('util') module.exports = function intersects(line1, line2) { assert(util.isArray(line1), 'argument `line1` must be an array') assert(util.isArray(line2), 'argument `line2` must be an array') var index1 = 0 while (line1.length > 0) { var startA = line1[index1] var endA = line1[++index1] if (typeof endA === 'undefined') break; var index2 = 0 while (line2.length > 0) { var startB = line2[index2] var endB = line2[++index2] if (typeof endB === 'undefined') break; if (intersection(startA, endA, startB, endB)) return true } } return false }
var intersection = require('robust-segment-intersect') var assert = require('assert') var util = require('util') module.exports = function intersects(line1, line2) { assert(util.isArray(line1), 'argument `line1` must be an array') assert(util.isArray(line2), 'argument `line2` must be an array') var index1 = 0 while (line1.length > 0) { var startA = line1[index1] var endA = line1[index1 + 1] if (typeof endA === 'undefined') break; var index2 = 0 while (line2.length > 0) { var startB = line2[index2] var endB = line2[index2 + 1] if (typeof endB === 'undefined') break; if (intersection(startA, endA, startB, endB)) return true index2++ } index1++ } return false }
Remove test for hubot-scripts.json since the file has been removed
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('hubot:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../generators/app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'bin/hubot', 'bin/hubot.cmd', 'Procfile', 'README.md', 'external-scripts.json', '.gitignore', 'package.json', 'scripts/example.coffee', '.editorconfig', ]); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('hubot:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../generators/app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'bin/hubot', 'bin/hubot.cmd', 'Procfile', 'README.md', 'external-scripts.json', 'hubot-scripts.json', '.gitignore', 'package.json', 'scripts/example.coffee', '.editorconfig', ]); }); });
Change unicode test, to test decoding and encoding is done correctly.
# -*- coding: utf-8 -*- import subprocess def test_basic(string=u"This is a test."): """Test function to test echo server and client with inputted string.""" process = subprocess.Popen(['./echo_client.py', string], stdout=subprocess.PIPE) assert string == process.stdout.readline().rstrip() def test_exact32(): """Test echo server and client with string length 32, the buffer size.""" test_basic(u"12345678901234567890123456789012") def test_unicode(): """Test that server and client handle encoding and decoding of unicode.""" inp = u'Testing «ταБЬℓσ»: 1<2 & 4+1>3, now 20 off!' process = subprocess.Popen(['./echo_client.py', inp], stdout=subprocess.PIPE) assert inp == process.stdout.readline().rstrip().decode('utf-8') def test_long(): """Test server and client can handle long messages.""" test_basic(u"Running the server script in one terminal should allow you to \ run the client script in a separate terminal. The client script should\ take an argument which is the message to send. Upon completing, the \ response from the server should be printed to stdout.")
# -*- coding: utf-8 -*- import subprocess import pytest def test_basic(string="This is a test."): """Test function to test echo server and client with inputted string.""" process = subprocess.Popen(['./echo_client.py', string], stdout=subprocess.PIPE) assert string == process.stdout.readline().rstrip() def test_exact32(): """Test echo server and client with string length 32, the buffer size.""" test_basic("12345678901234567890123456789012") def test_unicode(): """Test that server and client handle decoding and encoding of unicode.""" with pytest.raises(AssertionError): inp = 'Testing «ταБЬℓσ»: 1<2 & 4+1>3, now 20 off!' inp = inp.decode('utf-8') process = subprocess.Popen(['./echo_client.py', inp], stdout=subprocess.PIPE) assert inp == process.stdout.readline().rstrip() def test_long(): """Test server and client can handle long messages.""" test_basic("Running the server script in one terminal should allow you to \ run the client script in a separate terminal. The client script should\ take an argument which is the message to send. Upon completing, the \ response from the server should be printed to stdout.")
Fix JSDoc optional type syntax
'use strict'; /** * Module dependencies */ var crypto = require('crypto'); /** * 64 characters in the ascii range that can be used in URLs without special * encoding. */ var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; /** * Make a Buffer into a string ready for use in URLs * * @param {String} bytes a Buffer containing the bytes to convert * @returns {String} UID * @api private */ function tostr(bytes) { var r = '', i; for (i = 0; i < bytes.length; i++) { r += UIDCHARS[bytes[i] % 64]; } return r; } /** * Generate an Unique Id * * @param {Number} length The number of chars of the uid * @param {Number} [cb] Callback for async uid generation * @api public */ function uid(length, cb) { if (typeof cb === 'undefined') { return tostr(crypto.randomBytes(length)); } else { crypto.randomBytes(length, function (err, bytes) { if (err) return cb(err); cb(null, tostr(bytes)); }); } } /** * Exports */ module.exports = uid;
'use strict'; /** * Module dependencies */ var crypto = require('crypto'); /** * 64 characters in the ascii range that can be used in URLs without special * encoding. */ var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; /** * Make a Buffer into a string ready for use in URLs * * @param {String} bytes a Buffer containing the bytes to convert * @returns {String} UID * @api private */ function tostr(bytes) { var r = '', i; for (i = 0; i < bytes.length; i++) { r += UIDCHARS[bytes[i] % 64]; } return r; } /** * Generate an Unique Id * * @param {Number} length The number of chars of the uid * @param {Number} cb (optional) Callback for async uid generation * @api public */ function uid(length, cb) { if (typeof cb === 'undefined') { return tostr(crypto.randomBytes(length)); } else { crypto.randomBytes(length, function (err, bytes) { if (err) return cb(err); cb(null, tostr(bytes)); }); } } /** * Exports */ module.exports = uid;
Fix boken test - install WebSite before trying to locateChild
from twisted.trial import unittest from axiom.store import Store from axiom.item import Item from axiom.attributes import text from xmantissa.website import PrefixURLMixin, WebSite from xmantissa.ixmantissa import ISiteRootPlugin from zope.interface import implements class Dummy: def __init__(self, pfx): self.pfx = pfx class PrefixTester(Item, PrefixURLMixin): implements(ISiteRootPlugin) typeName = 'test_prefix_widget' schemaVersion = 1 prefixURL = text() def createResource(self): return Dummy(self.prefixURL) class SiteRootTest(unittest.TestCase): def testPrefixPriorityMath(self): s = Store() PrefixTester(store=s, prefixURL=u"hello").installOn(s) PrefixTester(store=s, prefixURL=u"").installOn(s) ws = WebSite(store=s) ws.installOn(s) res, segs = ws.locateChild(None, ('hello',)) self.assertEquals(res.pfx, 'hello') self.assertEquals(segs, ()) res, segs = ws.locateChild(None, ('',)) self.assertEquals(res.pfx, '') self.assertEquals(segs, ('',))
from twisted.trial import unittest from axiom.store import Store from axiom.item import Item from axiom.attributes import text from xmantissa.website import PrefixURLMixin, WebSite from xmantissa.ixmantissa import ISiteRootPlugin from zope.interface import implements class Dummy: def __init__(self, pfx): self.pfx = pfx class PrefixTester(Item, PrefixURLMixin): implements(ISiteRootPlugin) typeName = 'test_prefix_widget' schemaVersion = 1 prefixURL = text() def createResource(self): return Dummy(self.prefixURL) class SiteRootTest(unittest.TestCase): def testPrefixPriorityMath(self): s = Store() PrefixTester(store=s, prefixURL=u"hello").installOn(s) PrefixTester(store=s, prefixURL=u"").installOn(s) ws = WebSite(store=s) res, segs = ws.locateChild(None, ('hello',)) self.assertEquals(res.pfx, 'hello') self.assertEquals(segs, ()) res, segs = ws.locateChild(None, ('',)) self.assertEquals(res.pfx, '') self.assertEquals(segs, ('',))
Remove MessageScript injection for ExecService
#!/usr/bin/env node const { FileService, ExecService, TermApplication, ListScriptsCommand, RunScriptCommand, ConfigService, OPTION_PATH_FILE_TOKEN, getOptionsFilePath, getPackageData, MessageService } = require('../src') ;(() => { const cli = TermApplication.createInstance() const pkg = getPackageData() cli.version = pkg.version cli.description = 'Custom scripts manager.' cli.register(RunScriptCommand, [ExecService, FileService, MessageService]) cli.register(ListScriptsCommand, [FileService, MessageService]) cli.provide({ identity: OPTION_PATH_FILE_TOKEN, useValue: getOptionsFilePath() }) cli.provide(FileService, [ConfigService, MessageService]) cli.provide(ExecService) cli.provide(ConfigService, [OPTION_PATH_FILE_TOKEN]) cli.start() })()
#!/usr/bin/env node const { FileService, ExecService, TermApplication, ListScriptsCommand, RunScriptCommand, ConfigService, OPTION_PATH_FILE_TOKEN, getOptionsFilePath, getPackageData, MessageService } = require('../src') ;(() => { const cli = TermApplication.createInstance() const pkg = getPackageData() cli.version = pkg.version cli.description = 'Custom scripts manager.' cli.register(RunScriptCommand, [ExecService, FileService, MessageService]) cli.register(ListScriptsCommand, [FileService, MessageService]) cli.provide({ identity: OPTION_PATH_FILE_TOKEN, useValue: getOptionsFilePath() }) cli.provide(FileService, [ConfigService, MessageService]) cli.provide(ExecService, [MessageService]) cli.provide(ConfigService, [OPTION_PATH_FILE_TOKEN]) cli.start() })()
Increase migration conversion speed by a factor of 3x
/* eslint-env browser */ const EventEmitter = require('events'); const POLL_INTERVAL_MS = 5 * 1000; const IDLE_THRESHOLD_MS = 20; class IdleDetector extends EventEmitter { constructor() { super(); this.handle = null; this.timeoutId = null; } start() { console.log('Start idle detector'); this._scheduleNextCallback(); } stop() { console.log('Stop idle detector'); this._clearScheduledCallbacks(); } _clearScheduledCallbacks() { if (this.handle) { cancelIdleCallback(this.handle); } if (this.timeoutId) { clearTimeout(this.timeoutId); } } _scheduleNextCallback() { this._clearScheduledCallbacks(); this.handle = window.requestIdleCallback((deadline) => { const { didTimeout } = deadline; const timeRemaining = deadline.timeRemaining(); const isIdle = timeRemaining >= IDLE_THRESHOLD_MS; if (isIdle || didTimeout) { this.emit('idle', { timestamp: Date.now(), didTimeout, timeRemaining }); } this.timeoutId = setTimeout(() => this._scheduleNextCallback(), POLL_INTERVAL_MS); }); } } module.exports = { IdleDetector, };
/* eslint-env browser */ const EventEmitter = require('events'); const POLL_INTERVAL_MS = 15 * 1000; const IDLE_THRESHOLD_MS = 20; class IdleDetector extends EventEmitter { constructor() { super(); this.handle = null; this.timeoutId = null; } start() { console.log('Start idle detector'); this._scheduleNextCallback(); } stop() { console.log('Stop idle detector'); this._clearScheduledCallbacks(); } _clearScheduledCallbacks() { if (this.handle) { cancelIdleCallback(this.handle); } if (this.timeoutId) { clearTimeout(this.timeoutId); } } _scheduleNextCallback() { this._clearScheduledCallbacks(); this.handle = window.requestIdleCallback((deadline) => { const { didTimeout } = deadline; const timeRemaining = deadline.timeRemaining(); const isIdle = timeRemaining >= IDLE_THRESHOLD_MS; if (isIdle || didTimeout) { this.emit('idle', { timestamp: Date.now(), didTimeout, timeRemaining }); } this.timeoutId = setTimeout(() => this._scheduleNextCallback(), POLL_INTERVAL_MS); }); } } module.exports = { IdleDetector, };
Use ant filtering for MC version number.
package invtweaks.forge.asm; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import java.util.Map; @IFMLLoadingPlugin.MCVersion("@MCVERSION@") @IFMLLoadingPlugin.TransformerExclusions({"invtweaks.forge.asm.ITAccessTransformer"}) public class FMLPlugin implements IFMLLoadingPlugin { @Override public String[] getLibraryRequestClass() { return new String[0]; } @Override public String[] getASMTransformerClass() { return new String[] { "invtweaks.forge.asm.ITAccessTransformer" }; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { } }
package invtweaks.forge.asm; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import java.util.Map; @IFMLLoadingPlugin.MCVersion("1.5.2") @IFMLLoadingPlugin.TransformerExclusions({"invtweaks.forge.asm.ITAccessTransformer"}) public class FMLPlugin implements IFMLLoadingPlugin { @Override public String[] getLibraryRequestClass() { return new String[0]; } @Override public String[] getASMTransformerClass() { return new String[] { "invtweaks.forge.asm.ITAccessTransformer" }; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { } }
fix(Router): Add lang to payload if payload doesn't exist closes #16134
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitly added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (!action.payload || !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitally added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (action && action.payload && !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
[improve] Use Optional return values for all the queries
package net.safedata.springboot.training.d02.s05.repository; import net.safedata.springboot.training.d02.s05.model.Product; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; /** * A simple Spring Data {@link CrudRepository} for the {@link Product} entity * * @author bogdan.solga */ @Repository @SuppressWarnings("unused") public interface ProductRepository extends CrudRepository<Product, Integer> { Optional<List<Product>> findByName(final String name); @Query(value = "SELECT product " + "FROM Product product " + "WHERE product.name LIKE :name" ) Optional<List<Product>> findProductsWhichIncludeName(@Param(value = "name") final String name); Optional<Product> findById(int id); }
package net.safedata.springboot.training.d02.s05.repository; import net.safedata.springboot.training.d02.s05.model.Product; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * A simple Spring Data {@link CrudRepository} for the {@link Product} entity * * @author bogdan.solga */ @Repository @SuppressWarnings("unused") public interface ProductRepository extends CrudRepository<Product, Integer> { List<Product> findByName(final String name); @Query(value = "SELECT product " + "FROM Product product " + "WHERE product.name LIKE :name" ) List<Product> findProductsWhichIncludeName(final @Param(value = "name") String name); }
Set default port for local API server
'use strict'; const production = process.env.NODE_ENV === 'production'; const oneDay = 24 * 60 * 60; function get(name, fallback, options = {}) { if (process.env[name]) { return process.env[name]; } if (fallback !== undefined && (!production || !options.requireInProduction)) { return fallback; } throw new Error('Missing env var ' + name); } module.exports = { version: 0.1, db: { username: get('DB_USER', 'user'), password: get('DB_PASS', 'password'), server: get('DB_SERVER', 'server'), database: get('DB_NAME', 'licences') }, licences: { apiUrl: get('LICENCES_API_URL', 'http://localhost:3001'), timeout: { response: 2000, deadline: 2500 } }, https: production, staticResourceCacheDuration: 365 * oneDay, healthcheckInterval: Number(get('HEALTHCHECK_INTERVAL', 0)), sessionSecret: get('SESSION_SECRET', 'licences-insecure-default-session', {requireInProduction: true}) };
'use strict'; const production = process.env.NODE_ENV === 'production'; const oneDay = 24 * 60 * 60; function get(name, fallback, options = {}) { if (process.env[name]) { return process.env[name]; } if (fallback !== undefined && (!production || !options.requireInProduction)) { return fallback; } throw new Error('Missing env var ' + name); } module.exports = { version: 0.1, db: { username: get('DB_USER', 'user'), password: get('DB_PASS', 'password'), server: get('DB_SERVER', 'server'), database: get('DB_NAME', 'licences') }, licences: { apiUrl: get('LICENCES_API_URL', 'http://localhost:9091'), timeout: { response: 2000, deadline: 2500 } }, https: production, staticResourceCacheDuration: 365 * oneDay, healthcheckInterval: Number(get('HEALTHCHECK_INTERVAL', 0)), sessionSecret: get('SESSION_SECRET', 'licences-insecure-default-session', {requireInProduction: true}) };
Change URL bar result ordering
user_pref("beacon.enabled", false); user_pref("browser.contentblocking.enabled", false); user_pref("browser.library.activity-stream.enabled", false); user_pref("browser.safebrowsing.downloads.enabled", false); user_pref("browser.safebrowsing.malware.enabled", false); user_pref("browser.safebrowsing.phishing.enabled", false); user_pref("browser.tabs.drawInTitlebar", true); user_pref("browser.urlbar.matchBuckets", "general:5,suggestion:Infinity"); user_pref("dom.battery.enabled", false); user_pref("extensions.pocket.enabled", false); user_pref("general.autoScroll", true); user_pref("gfx.canvas.azure.accelerated", true); user_pref("javascript.options.asyncstack", false); user_pref("layers.acceleration.force-enabled", true); user_pref("layers.omtp.paint-workers", 4); user_pref("media.eme.enabled", false); user_pref("media.navigator.enabled", false); user_pref("media.peerconnection.enabled", false); user_pref("network.IDN_show_punycode", true); user_pref("privacy.donottrackheader.enabled", true);
user_pref("beacon.enabled", false); user_pref("browser.contentblocking.enabled", false); user_pref("browser.library.activity-stream.enabled", false); user_pref("browser.safebrowsing.downloads.enabled", false); user_pref("browser.safebrowsing.malware.enabled", false); user_pref("browser.safebrowsing.phishing.enabled", false); user_pref("browser.tabs.drawInTitlebar", true); user_pref("dom.battery.enabled", false); user_pref("extensions.pocket.enabled", false); user_pref("general.autoScroll", true); user_pref("gfx.canvas.azure.accelerated", true); user_pref("javascript.options.asyncstack", false); user_pref("layers.acceleration.force-enabled", true); user_pref("layers.omtp.paint-workers", 4); user_pref("media.eme.enabled", false); user_pref("media.navigator.enabled", false); user_pref("media.peerconnection.enabled", false); user_pref("network.IDN_show_punycode", true); user_pref("privacy.donottrackheader.enabled", true);
Comment test on vuejsdialog with vue3
import { createApp, defineAsyncComponent } from 'vue'; import '@fontsource/kreon'; const app = createApp({ mounted: function() { document.body.classList.add('cssLoading'); setTimeout(() => document.body.classList.remove('cssLoading'), 0); }, components: { PageRandom: defineAsyncComponent(() => import('./components/pageRandom.vue')), Pending: defineAsyncComponent(() => import('./components/pending.vue')), OrganizerForm: defineAsyncComponent(() => import('./components/organizer/form.vue')), DearSantaForm: defineAsyncComponent(() => import('./components/dearSantaForm.vue')), Dashboard: defineAsyncComponent(() => import('./components/dashboard.vue')), Faq: defineAsyncComponent(() => import('./components/faq.vue')), VueFetcher: defineAsyncComponent(() => import('./components/vueFetcher.vue')) } }); app.mount('#main'); const lang = document.documentElement.lang.substr(0, 2); import Locale from './vue-i18n-locales.generated.js'; import { createI18n } from 'vue-i18n'; const i18n = createI18n({ locale: lang, messages: Locale, globalInjection: true }); app.use(i18n); //import VuejsDialog from 'vuejs-dialog'; //app.use(VueJsDialog);
import { createApp, defineAsyncComponent } from 'vue'; import '@fontsource/kreon'; const app = createApp({ mounted: function() { document.body.classList.add('cssLoading'); setTimeout(() => document.body.classList.remove('cssLoading'), 0); }, components: { PageRandom: defineAsyncComponent(() => import('./components/pageRandom.vue')), Pending: defineAsyncComponent(() => import('./components/pending.vue')), OrganizerForm: defineAsyncComponent(() => import('./components/organizer/form.vue')), DearSantaForm: defineAsyncComponent(() => import('./components/dearSantaForm.vue')), Dashboard: defineAsyncComponent(() => import('./components/dashboard.vue')), Faq: defineAsyncComponent(() => import('./components/faq.vue')), VueFetcher: defineAsyncComponent(() => import('./components/vueFetcher.vue')) } }); app.mount('#main'); const lang = document.documentElement.lang.substr(0, 2); import Locale from './vue-i18n-locales.generated.js'; import { createI18n } from 'vue-i18n'; const i18n = createI18n({ locale: lang, messages: Locale, globalInjection: true }); app.use(i18n); import VuejsDialog from 'vuejs-dialog'; app.use(VueJsDialog);
Add --version flag for homebrew test
package main import ( "flag" "fmt" "os" "github.com/simeji/jid" ) const VERSION = "0.6.2" func main() { content := os.Stdin var qm bool var version bool qs := "." flag.BoolVar(&qm, "q", false, "Output query mode") flag.BoolVar(&version, "version", false, "print the version and exit") flag.Parse() if version { fmt.Println(fmt.Sprintf("jid version v%s", VERSION)) os.Exit(0) } args := flag.Args() if len(args) > 0 { qs = args[0] } e, err := jid.NewEngine(content, qs) if err != nil { fmt.Println(err) os.Exit(1) } os.Exit(run(e, qm)) } func run(e jid.EngineInterface, qm bool) int { result := e.Run() if result.GetError() != nil { return 2 } if qm { fmt.Printf("%s", result.GetQueryString()) } else { fmt.Printf("%s", result.GetContent()) } return 0 }
package main import ( "flag" "fmt" "os" "github.com/simeji/jid" ) func main() { content := os.Stdin var qm bool qs := "." flag.BoolVar(&qm, "q", false, "Output query mode") flag.Parse() args := flag.Args() if len(args) > 0 { qs = args[0] } e, err := jid.NewEngine(content, qs) if err != nil { fmt.Println(err) os.Exit(1) } os.Exit(run(e, qm)) } func run(e jid.EngineInterface, qm bool) int { result := e.Run() if result.GetError() != nil { return 2 } if qm { fmt.Printf("%s", result.GetQueryString()) } else { fmt.Printf("%s", result.GetContent()) } return 0 }
Fix style on migration - waste of time, but whatever
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-20 18:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accelerator', '0043_remove_exclude_fields'), ] help_text = 'Show the new-style side navigation' operations = [ migrations.RemoveField( model_name='programfamily', name='side_navigation', ), migrations.AddField( model_name='programfamily', name='use_site_tree_side_nav', field=models.BooleanField(default=False, help_text=help_text), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-20 18:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accelerator', '0043_remove_exclude_fields'), ] operations = [ migrations.RemoveField( model_name='programfamily', name='side_navigation', ), migrations.AddField( model_name='programfamily', name='use_site_tree_side_nav', field=models.BooleanField(default=False, help_text='Show the new-style side navigation'), ), ]
Remove logger name from logs
#!/usr/bin/env python3 # # Copyright (c) 2016, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-7s %(message)-100s ' '[%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
#!/usr/bin/env python3 # # Copyright (c) 2016, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %(message)-100s ' '%(name)s [%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
Fix bug introduced in efdd3d6
import angular from 'angular'; import template from './authorityView.html'; export const authorityViewComponentName = 'appAuthorityView'; export const authorityViewComponent = { template, controller: AuthorityViewController, controllerAs: 'vm', bindings: { 'data': '<', }, }; ///// /* @ngInject */ function AuthorityViewController($scope, $state, $stateParams, $timeout, $rootScope, $q, $http, $filter, gettext, gettextCatalog, Config, langService, AuthorityService) { /*jshint validthis: true */ var vm = this; vm.history = []; vm.currentSubject = null; activate(); ///// function updateSubject() { vm.history = AuthorityService.history; vm.currentSubject = AuthorityService.currentSubject; if (vm.currentSubject) { vm.currentSubject.sortLabels(); } } function activate() { updateSubject(); AuthorityService.onSubject($scope, updateSubject); } }
import angular from 'angular'; import template from './authorityView.html'; export const authorityViewComponentName = 'appAuthorityView'; export const authorityViewComponent = { template, controller: AuthorityViewController, controllerAs: 'vm', bindings: { 'data': '<', }, }; ///// /* @ngInject */ function AuthorityViewController($scope, $state, $stateParams, $timeout, $rootScope, $q, $http, $filter, gettext, gettextCatalog, Config, langService, AuthorityService) { /*jshint validthis: true */ var vm = this; vm.history = []; vm.currentSubject = null; activate(); ///// function activate() { vm.history = AuthorityService.history; vm.currentSubject = AuthorityService.currentSubject; AuthorityService.currentSubject.sortLabels(); AuthorityService.onSubject($scope, function () { vm.history = AuthorityService.history; vm.currentSubject = AuthorityService.currentSubject; AuthorityService.currentSubject.sortLabels(); }); } }
Add links to Android/iOS apps
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Mappy' SITENAME = u'Mappy Labs' SITEURL = '' TIMEZONE = 'Europe/Paris' DEFAULT_LANG = u'en' THEME = 'theme/mappy' # Feed generation is usually not desired when developing FEED_ALL_ATOM = 'feeds/rss.xml' CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml' TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Mappy', 'https://www.mappy.com/'), ('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'), ('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'), ('Blog Mappy', 'http://corporate.mappy.com'), ('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'), ) # Social widget #SOCIAL = (('Twitter', 'https://twitter.com/Mappy'), # ) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True STATIC_PATHS = ['images','resources'] TWITTER_URL = 'https://twitter.com/Mappy' GITHUB_URL = 'https://github.com/Mappy' FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Mappy' SITENAME = u'Mappy Labs' SITEURL = '' TIMEZONE = 'Europe/Paris' DEFAULT_LANG = u'en' THEME = 'theme/mappy' # Feed generation is usually not desired when developing FEED_ALL_ATOM = 'feeds/rss.xml' CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml' TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Mappy', 'https://www.mappy.com/'), ('Blog Mappy', 'http://corporate.mappy.com'), ('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'), ) # Social widget #SOCIAL = (('Twitter', 'https://twitter.com/Mappy'), # ) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True STATIC_PATHS = ['images','resources'] TWITTER_URL = 'https://twitter.com/Mappy' GITHUB_URL = 'https://github.com/Mappy' FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
Add "name_mask" value in configuration file
<?php return [ /* |-------------------------------------------------------------------------- | Default Filesystem Disk |-------------------------------------------------------------------------- | | Here you may specify the default filesystem disk that should be used | by the Uploadify package. If default filesystem disk is not provided, | package will use default filesystem from Laravel configuration. | */ 'disk' => 'public', /* |-------------------------------------------------------------------------- | Default Thumbnail Folder |-------------------------------------------------------------------------- | | Default suffix for path to thumbnail folder. Example: if "path" is set to | "upload/images/logo/", "path_thumb" will be "upload/images/logo/thumb/". | */ 'path_thumb_suffix' => 'thumb/', /* |-------------------------------------------------------------------------- | Name Mask |-------------------------------------------------------------------------- */ 'name_mask' => '{name}-w{width}-h{height}', /* |-------------------------------------------------------------------------- | Name Separator |-------------------------------------------------------------------------- | */ 'name_separator' => '-', ];
<?php return [ /* |-------------------------------------------------------------------------- | Default Filesystem Disk |-------------------------------------------------------------------------- | | Here you may specify the default filesystem disk that should be used | by the Uploadify package. If default filesystem disk is not provided, | package will use default filesystem from Laravel configuration. | */ 'disk' => 'public', /* |-------------------------------------------------------------------------- | Default Thumbnail Folder |-------------------------------------------------------------------------- | | Default suffix for path to thumbnail folder. Example: if "path" is set to | "upload/images/logo/", "path_thumb" will be "upload/images/logo/thumb/". | */ 'path_thumb_suffix' => 'thumb/', /* |-------------------------------------------------------------------------- | Name Separator |-------------------------------------------------------------------------- | */ 'name_separator' => '-', ];
Refactor ciscospark Migrate Avatar to packages use default SparkMock issue #62 Migrate Avatar
/**! * * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. */ import {assert} from '@ciscospark/test-helper-chai'; import Avatar from '../../'; import MockSpark from '@ciscospark/test-helper-mock-spark'; describe(`Services`, () => { describe(`Avatar`, () => { describe(`AvatarUrlBatcher`, () => { let batcher; let spark; beforeEach(() => { spark = new MockSpark({ children: { avatar: Avatar } }); console.warn('spark: <' + JSON.stringify(spark) + '>'); batcher = spark.avatar.batcher; }); describe(`#fingerprintRequest(item)`, () => { it(`returns 'uuid - size'`, () => { assert.equal(batcher.fingerprintRequest({uuid: `uuid1`, size: 80}), `uuid1 - 80`); }); }); }); }); });
/**! * * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. */ import {assert} from '@ciscospark/test-helper-chai'; import Avatar, {config} from '../../'; // import '@ciscospark/test-helper-sinon'; import {MockSpark} from '@ciscospark/test-helper-mock-spark'; describe(`Services`, () => { describe(`Avatar`, () => { describe(`AvatarUrlBatcher`, () => { let batcher; let spark; beforeEach(() => { spark = new MockSpark({ children: { avatar: Avatar } }); spark.config.avatar = config.avatar; batcher = spark.avatar.batcher; console.warn(JSON.stringify(spark, null, `\t`)); }); describe(`#fingerprintRequest(item)`, () => { it(`returns 'uuid - size'`, () => { assert.equal(batcher.fingerprintRequest({uuid: `uuid1`, size: 80}), `uuid1 - 80`); }); }); }); }); });
Create variable for tracking finished QA set
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0, answeredQA = []; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question; var revealBtn = document.getElementById('reveal-answer'); function revealAns() { question.innerHTML = questions[questionNum].answer; } revealBtn.onclick = revealAns;
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question; var revealBtn = document.getElementById('reveal-answer'); function revealAns() { question.innerHTML = questions[questionNum].answer; } revealBtn.onclick = revealAns;
Make sure the APP_ENV is "testing" when switching db for tests
<?php namespace Criterion; class Application { public static $app; public $config = false; public $config_file = false; public $mongo = false; public $db = false; public function __construct() { $this->config_file = dirname(dirname(__DIR__)) . '/config.json'; if (file_exists($this->config_file)) { $this->config = json_decode(file_get_contents($this->config_file), true); } $db = getenv('APP_ENV') === 'testing' ? 'criterion_testing' : 'criterion'; $this->mongo = new \MongoMinify\Client(); $this->db = $this->mongo->{$db}; return $this; } }
<?php namespace Criterion; class Application { public static $app; public $config = false; public $config_file = false; public $mongo = false; public $db = false; public function __construct() { $this->config_file = dirname(dirname(__DIR__)) . '/config.json'; if (file_exists($this->config_file)) { $this->config = json_decode(file_get_contents($this->config_file), true); } $db = getenv('APP_ENV') ? 'criterion_testing' : 'criterion'; $this->mongo = new \MongoMinify\Client(); $this->db = $this->mongo->{$db}; return $this; } }
Refactor test, check if price is an integer
<?php namespace Albergrala\Crawlers; use Albertgrala\Crawlers\PcComponentesCrawler; class PcComponentesCrawlerTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $url = 'http://www.pccomponentes.com/kingston_valueram_4gb_ddr3_1333mhz_pc3_10600_cl9.html'; $this->crawler = new PcComponentesCrawler($url); } protected function tearDown() { } public function testCrawlsUrl() { $this->crawler->crawl(); $this->isTrue($this->crawler->isCrawled()); } public function testExtractPriceReturnsAndInteger() { $this->crawler->crawl(); $this->crawler->extractPrice(); $this->assertInternalType('int', $this->crawler->getPrice()); } }
<?php namespace Albergrala\Crawlers; use Albertgrala\Crawlers\PcComponentesCrawler; class PcComponentesCrawlerTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $url = 'http://www.pccomponentes.com/kingston_valueram_4gb_ddr3_1333mhz_pc3_10600_cl9.html'; $this->crawler = new PcComponentesCrawler($url); } protected function tearDown() { } public function testCrawlsUrl() { $this->crawler->crawl(); $this->isTrue($this->crawler->isCrawled()); } public function testExtractPrice() { $this->crawler->crawl(); $this->crawler->extractPrice(); $this->assertNotNull($this->crawler->getPrice()); } }
Refactor sending slack response to its own function
'use strict'; require('dotenv').load(); const _ = require('lodash'); const Slack = require('slack-client'); const responses = require('./responses.js'); const slackToken = process.env.SLACK_TOKEN; const slackChannel = process.env.SLACK_CHANNEL; const autoReconnect = true; const autoMark = true; let slack = new Slack(slackToken, autoReconnect, autoMark); function sendResponse(channel, message) { console.log('Response: ' + message); channel.send(message); } slack.on('open', function() { console.log('Connected to ' + slack.team.name + ' as ' + slack.self.name); }); slack.on('message', function(message) { console.log('Received: ' + message); let channel = slack.getChannelGroupOrDMByID(message.channel); if (!channel) return; let user = slack.getUserByID(message.user); if (!user) return; // Only respond in the specified channel or to individual users if (!channel.is_channel || channel.name === slackChannel) { if (message.text.match(/praise koffee/ig)) { sendResponse(channel, '༼ つ ◕_◕ ༽つ ☕️'); } else if (message.text.match(/c/ig)) { sendResponse(channel, _.sample(responses)('@' + user.name)); } } }); slack.on('error', function(err) { console.error('Error', err); }); slack.login();
'use strict'; require('dotenv').load(); const _ = require('lodash'); const Slack = require('slack-client'); const responses = require('./responses.js'); const slackToken = process.env.SLACK_TOKEN; const slackChannel = process.env.SLACK_CHANNEL; const autoReconnect = true; const autoMark = true; let slack = new Slack(slackToken, autoReconnect, autoMark); slack.on('open', function() { console.log('Connected to ' + slack.team.name + ' as ' + slack.self.name); }); slack.on('message', function(message) { console.log('Received: ' + message); let channel = slack.getChannelGroupOrDMByID(message.channel); if (!channel) return; let user = slack.getUserByID(message.user); if (!user) return; // Only respond in the specified channel or to individual users if (!channel.is_channel || channel.name === slackChannel) { if (message.text.match(/praise koffee/ig)) { let res = '༼ つ ◕_◕ ༽つ ☕️'; console.log('Response: ' + res); channel.send(res); } else if (message.text.match(/c/ig)) { let res = _.sample(responses)('@' + user.name); console.log('Response: ' + res); channel.send(res); } } }); slack.on('error', function(err) { console.error('Error', err); }); slack.login();
Remove now useless TearDown method. git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@53797 6015fed2-1504-0410-9fe1-9d1591cc4771
# Basic test of dynamic code generation import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) def test_compiler_errors(self): from ctypeslib.codegen.cparser import CompilerError from ctypeslib.dynamic_module import include self.failUnlessRaises(CompilerError, lambda: include("#error")) if __name__ == "__main__": unittest.main()
# Basic test of dynamic code generation import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: pass def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) def test_compiler_errors(self): from ctypeslib.codegen.cparser import CompilerError from ctypeslib.dynamic_module import include self.failUnlessRaises(CompilerError, lambda: include("#error")) if __name__ == "__main__": unittest.main()
Stop when a step exit code > 0
<?php namespace Rizeway\Anchour\Step; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputInterface; class StepRunner { /** * The steps * @var Step[] */ protected $steps; protected $application; /** * @param Step[] $steps */ public function __construct($application, array $steps) { $this->application = $application; $this->steps = $steps; } /** * @param \Symfony\Component\Console\Output\OutputInterface $output */ public function run(InputInterface $input, OutputInterface $output) { foreach ($this->steps as $step) { if ($step instanceof \Rizeway\Anchour\Step\StepApplicationAware) { $step->setApplication($this->application); } $status = $step->run($input, $output); if ( $status != 0 ) { return $status; } } return 0; } }
<?php namespace Rizeway\Anchour\Step; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputInterface; class StepRunner { /** * The steps * @var Step[] */ protected $steps; protected $application; /** * @param Step[] $steps */ public function __construct($application, array $steps) { $this->application = $application; $this->steps = $steps; } /** * @param \Symfony\Component\Console\Output\OutputInterface $output */ public function run(InputInterface $input, OutputInterface $output) { $status = 0; foreach ($this->steps as $step) { if ($step instanceof \Rizeway\Anchour\Step\StepApplicationAware) { $step->setApplication($this->application); } $status += $step->run($input, $output); } return $status; } }
Fix tests for PHP 5.3
<?php /* * This file is part of the league/markua package. * * (c) Davey Shafik <me@daveyshafik.com> * * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\Markua\Tests; use League\Markua\Extension\MarkuaExtension; use League\Markua\MarkuaConverter; class ExtensionTest extends \PHPUnit_Framework_TestCase { public function testGetExtensionName() { $extension = new MarkuaExtension(); $this->assertEquals('markua', $extension->getName()); } public function testConvertor() { $convertor = new MarkuaConverter(); $extensions = $convertor->getDocParser()->getEnvironment()->getExtensions(); $this->assertEquals('markua', $extensions[0]->getName()); $extensions = $convertor->getHtmlRenderer()->getEnvironment()->getExtensions(); $this->assertEquals('markua', $extensions[0]->getName()); } }
<?php /* * This file is part of the league/markua package. * * (c) Davey Shafik <me@daveyshafik.com> * * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\Markua\Tests; use League\Markua\Extension\MarkuaExtension; use League\Markua\MarkuaConverter; class ExtensionTest extends \PHPUnit_Framework_TestCase { public function testGetExtensionName() { $extension = new MarkuaExtension(); $this->assertEquals('markua', $extension->getName()); } public function testConvertor() { $convertor = new MarkuaConverter(); $this->assertEquals('markua', $convertor->getDocParser()->getEnvironment()->getExtensions()[0]->getName()); $this->assertEquals('markua', $convertor->getHtmlRenderer()->getEnvironment()->getExtensions()[0]->getName()); } }
Rename main html file to index.html during build to make publish process more streamlined
/*jslint node: true, sloppy: true */ module.exports = function (grunt) { grunt.initConfig({ inlineEverything: { simpleExample: { options: { tags: { link: true, script: true } }, src: 'czemaco.html', dest: 'build/index.html' } } }); grunt.loadNpmTasks('grunt-cruncher'); grunt.registerTask('inline', ['inlineEverything']); grunt.registerTask('default', ['inlineEverything']); };
/*jslint node: true, sloppy: true */ module.exports = function (grunt) { grunt.initConfig({ inlineEverything: { simpleExample: { options: { tags: { link: true, script: true } }, src: 'czemaco.html', dest: 'build/czemaco.html' } } }); grunt.loadNpmTasks('grunt-cruncher'); grunt.registerTask('inline', ['inlineEverything']); grunt.registerTask('default', ['inlineEverything']); };
Fix a small bug with new line
package main import ( "bytes" "os/exec" "strings" ) const script = ` tell application "System Events" set frontApp to name of first application process whose frontmost is true set activeURL to "" if frontApp is "Google Chrome" then tell application "Google Chrome" set normalWindows to (windows whose mode is not "incognito") if length of normalWindows is greater than 0 then set activeURL to (get URL of active tab of (first item of normalWindows)) end if end tell end if end tell if activeURL is not "" then activeURL else frontApp end if ` func GetActivityName() (string, error) { cmd := exec.Command("osascript", "-") cmd.Stdin = bytes.NewBufferString(script) output, err := cmd.Output() return strings.Replace(string(output), "\n", "", -1), err }
package main import ( "bytes" "os/exec" ) const script = ` tell application "System Events" set frontApp to name of first application process whose frontmost is true set activeURL to "" if frontApp is "Google Chrome" then tell application "Google Chrome" set normalWindows to (windows whose mode is not "incognito") if length of normalWindows is greater than 0 then set activeURL to (get URL of active tab of (first item of normalWindows)) end if end tell end if end tell if activeURL is not "" then activeURL else frontApp end if ` func GetActivityName() (string, error) { cmd := exec.Command("osascript", "-") cmd.Stdin = bytes.NewBufferString(script) output, err := cmd.Output() return string(output), err }
Move the PushMessagingBrowserTest to use SWR.showNotification(). This will allow us to start throwing a TypeError per the specification when constructing a new Notification object in a Service Worker. This is part of a two-sided patch: [1] This patch. [2] https://codereview.chromium.org/923443005 BUG=459038 Review URL: https://codereview.chromium.org/930963002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#316496}
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. this.onpush = function(event) { var data = event.data.text(); if (data !== 'shownotification') { sendMessageToClients('push', data); return; } event.waitUntil(registration.showNotification('Push test title', { body: 'Push test body', tag: 'push_test_tag' }).then(function(notification) { sendMessageToClients('push', data); }, function(ex) { sendMessageToClients('push', String(ex)); })); }; function sendMessageToClients(type, data) { var message = JSON.stringify({ 'type': type, 'data': data }); clients.getAll().then(function(clients) { clients.forEach(function(client) { client.postMessage(message); }); }, function(error) { console.log(error); }); }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. this.onpush = function(event) { // TODO(peter): Remove this check once Blink supports PushMessageData.json(). var data = event.data; if (typeof data !== 'string') data = data.text(); if (data !== 'shownotification') { sendMessageToClients('push', data); return; } // TODO(peter): Switch to self.registration.showNotification once implemented. event.waitUntil(showLegacyNonPersistentNotification('Push test title', { body: 'Push test body', tag: 'push_test_tag' }).then(function(notification) { sendMessageToClients('push', data); }, function(ex) { sendMessageToClients('push', String(ex)); })); }; function sendMessageToClients(type, data) { var message = JSON.stringify({ 'type': type, 'data': data }); clients.getAll().then(function(clients) { clients.forEach(function(client) { client.postMessage(message); }); }, function(error) { console.log(error); }); } function showLegacyNonPersistentNotification(title, options) { return new Promise(function(resolve, reject) { var notification = new Notification(title, options); notification.onshow = function() { resolve(notification); }; notification.onerror = function() { reject(new Error('Failed to show')); }; }); }
Switch Winch speed controller from Spark to Talon Because we're lazy :sparkles:
package org.usfirst.frc.team2503.r2016; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; public class Constants { public static final SpeedController leftTrackSpeedController = new Talon(0); public static final SpeedController rightTrackSpeedController = new Talon(1); public static final SpeedController shooterSpeedController = new Spark(2); public static final SpeedController winchSpeedController = new Talon(3); public static final SpeedController hookerSpeedController = new Talon(4); public static final DigitalInput leftTrackEncoderAChannel = new DigitalInput(0); public static final DigitalInput leftTrackEncoderBChannel = new DigitalInput(1); public static final DigitalInput rightTrackEncoderAChannel = new DigitalInput(2); public static final DigitalInput rightTrackEncoderBChannel = new DigitalInput(3); public static final DigitalInput intakeDigitalInput = new DigitalInput(4); }
package org.usfirst.frc.team2503.r2016; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; public class Constants { public static final SpeedController leftTrackSpeedController = new Talon(0); public static final SpeedController rightTrackSpeedController = new Talon(1); public static final SpeedController shooterSpeedController = new Spark(2); public static final SpeedController winchSpeedController = new Spark(3); public static final SpeedController hookerSpeedController = new Talon(4); public static final DigitalInput leftTrackEncoderAChannel = new DigitalInput(0); public static final DigitalInput leftTrackEncoderBChannel = new DigitalInput(1); public static final DigitalInput rightTrackEncoderAChannel = new DigitalInput(2); public static final DigitalInput rightTrackEncoderBChannel = new DigitalInput(3); public static final DigitalInput intakeDigitalInput = new DigitalInput(4); }
Convert spaces to U+3000 (ideographic space)
module.exports = { commands: { fullwidth: { help: 'Creates an aesthetic', aliases: [ 'vw', 'fw' ], command: function (bot, msg) { let codePoints = Array.prototype.map.call(msg.body, (c) => c.codePointAt(0)) codePoints = codePoints.map((c) => { if (c >= 33 && c <= 126) return c - 33 + 0xFF01 if (c == 32) return 0x3000 return c }) return String.fromCodePoint(...codePoints) } } } }
module.exports = { commands: { fullwidth: { help: 'Creates an aesthetic', aliases: [ 'vw', 'fw' ], command: function (bot, msg) { let codePoints = Array.prototype.map.call(msg.body, (c) => c.codePointAt(0)) codePoints = codePoints.map((c) => { if (c >= 33 && c <= 126) return c - 33 + 0xFF01 return c }) return String.fromCodePoint(...codePoints) } } } }
Add code comments for begins example Code comments for the major sections of the begins example program.
#!/usr/bin/env python import begin import twitterlib # sub-command definitions using subcommand decorator for each sub-command that # implements a timeline display @begin.subcommand def timeline(): "Display recent tweets from users timeline" for status in begin.context.api.timeline: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def mentions(): "Display recent tweets mentioning user" for status in begin.context.api.mentions: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def retweets(): "Display recent retweets from user's timeline" for status in begin.context.api.retweets: print u"%s: %s" % (status.user.screen_name, status.text) # program main definition replace __name__ === '__main__' magic # sub-commands are registered and loaded automatically @begin.start(env_prefix='', short_args=False) def main(api_key='', api_secret='', access_token='', access_secret=''): """Minimal Twitter client Demonstrate the use of the begins command line application framework by implementing a simple Twitter command line client. """ api = twitterlib.API(api_key, api_secret, access_token, access_secret) begin.context.api = api
#!/usr/bin/env python import begin import twitterlib @begin.subcommand def timeline(): "Display recent tweets from users timeline" for status in begin.context.api.timeline: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def mentions(): "Display recent tweets mentioning user" for status in begin.context.api.mentions: print u"%s: %s" % (status.user.screen_name, status.text) @begin.subcommand def retweets(): "Display recent retweets from user's timeline" for status in begin.context.api.retweets: print u"%s: %s" % (status.user.screen_name, status.text) @begin.start(env_prefix='', short_args=False) def main(api_key='', api_secret='', access_token='', access_secret=''): """Minimal Twitter client Demonstrate the use of the begins command line application framework by implementing a simple Twitter command line client. """ api = twitterlib.API(api_key, api_secret, access_token, access_secret) begin.context.api = api
BAP-9985: Add processor that will set total deleted items count into response header -- comment fix
<?php namespace Oro\Bundle\ApiBundle\Processor\DeleteList; use Oro\Component\ChainProcessor\ContextInterface; use Oro\Component\ChainProcessor\ProcessorInterface; /** * Unset the "X-Include-Delete-Count" response header * in case if it was requested by "X-Include: deleteCount" request header but an error occurred in deletion process. */ class UnsetDeleteCountHeader implements ProcessorInterface { /** * {@inheritdoc} */ public function process(ContextInterface $context) { /** @var DeleteListContext $context */ if (!$context->getResponseHeaders()->has(SetDeleteCountHeader::HEADER_NAME)) { // delete count header was not set return; } if ($context->hasResult()) { $context->getResponseHeaders()->remove(SetDeleteCountHeader::HEADER_NAME); } } }
<?php namespace Oro\Bundle\ApiBundle\Processor\DeleteList; use Oro\Component\ChainProcessor\ContextInterface; use Oro\Component\ChainProcessor\ProcessorInterface; /** * Unset the "X-Include-Delete-Count" response header * in case if it was requested by "X-Include: deleteCount" request header and an error occurred in deletion process. */ class UnsetDeleteCountHeader implements ProcessorInterface { /** * {@inheritdoc} */ public function process(ContextInterface $context) { /** @var DeleteListContext $context */ if (!$context->getResponseHeaders()->has(SetDeleteCountHeader::HEADER_NAME)) { // delete count header was not set return; } if ($context->hasResult()) { $context->getResponseHeaders()->remove(SetDeleteCountHeader::HEADER_NAME); } } }
Delete the document from the disk on delete
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf import settings from django.db.models.signals import post_save from django.db.models.signals import post_delete from django.dispatch import receiver from wger.gym.models import Gym from wger.gym.models import GymConfig from wger.gym.models import UserDocument @receiver(post_save, sender=Gym) def gym_config(sender, instance, created, **kwargs): ''' Creates a configuration entry for newly added gyms ''' if not created or kwargs['raw']: return config = GymConfig() config.gym = instance config.save() @receiver(post_delete, sender=UserDocument) def delete_user_document_on_delete(sender, instance, **kwargs): ''' Deletes the document from the disk as well ''' instance.document.delete(save=False)
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from wger.gym.models import Gym from wger.gym.models import GymConfig @receiver(post_save, sender=Gym) def gym_config(sender, instance, created, **kwargs): ''' Creates a configuration entry for newly added gyms ''' if not created or kwargs['raw']: return config = GymConfig() config.gym = instance config.save()
Add MaybeNotify for state change notifications
package main import ( "fmt" "github.com/0xAX/notificator" "github.com/datawire/teleproxy/pkg/supervisor" ) var notifyConfig *notificator.Notificator // Notify displays a desktop banner notification to the user func Notify(p *supervisor.Process, title string, message ...string) { if notifyConfig == nil { notifyConfig = notificator.New(notificator.Options{ DefaultIcon: "", AppName: "Playpen Daemon", }) } var err error switch { case len(message) == 0: p.Logf("NOTIFY: %s", title) err = notifyConfig.Push(title, "", "", notificator.UR_NORMAL) case len(message) == 1: p.Logf("NOTIFY: %s: %s", title, message) err = notifyConfig.Push(title, message[0], "", notificator.UR_NORMAL) default: panic(fmt.Sprintf("NOTIFY message too long: %d", len(message))) } if err != nil { p.Logf("ERROR while notifying: %v", err) } } // MaybeNotify displays a notification only if a value changes func MaybeNotify(p *supervisor.Process, name string, old, new bool) { if old != new { Notify(p, fmt.Sprintf("%s: %t -> %t", name, old, new)) } }
package main import ( "fmt" "github.com/0xAX/notificator" "github.com/datawire/teleproxy/pkg/supervisor" ) var notifyConfig *notificator.Notificator // Notify displays a desktop banner notification to the user func Notify(p *supervisor.Process, title string, message ...string) { if notifyConfig == nil { notifyConfig = notificator.New(notificator.Options{ DefaultIcon: "", AppName: "Playpen Daemon", }) } var err error switch { case len(message) == 0: p.Logf("NOTIFY: %s", title) err = notifyConfig.Push(title, "", "", notificator.UR_NORMAL) case len(message) == 1: p.Logf("NOTIFY: %s: %s", title, message) err = notifyConfig.Push(title, message[0], "", notificator.UR_NORMAL) default: panic(fmt.Sprintf("NOTIFY message too long: %d", len(message))) } if err != nil { p.Logf("ERROR while notifying: %v", err) } }
Set loginRequired to false. For users without login, this is required for "back" link on some pages to function. SVN-Revision: 10730
/* The caLAB Software License, Version 0.5 Copyright 2006 SAIC. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. */ package gov.nih.nci.calab.ui.core; /** * This class calls the Struts ForwardAction to forward to a page, aslo * extends AbstractBaseAction to inherit the user authentication features. * * @author pansu */ /* CVS $Id: BaseForwardAction.java,v 1.4 2007-10-25 20:56:51 cais Exp $ */ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.ForwardAction; public class BaseForwardAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ForwardAction forwardAction = new ForwardAction(); return forwardAction.execute(mapping, form, request, response); } public boolean loginRequired() { //return true; return false; } public boolean canUserExecute(HttpSession session) { return true; } }
/* The caLAB Software License, Version 0.5 Copyright 2006 SAIC. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. */ package gov.nih.nci.calab.ui.core; /** * This class calls the Struts ForwardAction to forward to a page, aslo * extends AbstractBaseAction to inherit the user authentication features. * * @author pansu */ /* CVS $Id: BaseForwardAction.java,v 1.3 2006-08-02 21:27:59 pansu Exp $ */ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.ForwardAction; public class BaseForwardAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ForwardAction forwardAction = new ForwardAction(); return forwardAction.execute(mapping, form, request, response); } public boolean loginRequired() { return true; } public boolean canUserExecute(HttpSession session) { return true; } }
Change URL from Zolera (sob, snif, sigh :) to SF git-svn-id: c4afb4e777bcbfe9afa898413b708b5abcd43877@123 7150bf37-e60d-0410-b93f-83e91ef0e581
#! /usr/bin/env python # $Header$ import sys from distutils.core import setup _url = "http://pywebsvcs.sf.net/" import ConfigParser cf = ConfigParser.ConfigParser() cf.read('setup.cfg') _version = "%d.%d" % \ ( cf.getint('version', 'major'), cf.getint('version', 'minor') ) try: open('ZSI/version.py', 'r').close() except: print 'ZSI/version.py not found; run "make"' sys.exit(1) setup( name="ZSI", version=_version, licence="Python", packages=[ "ZSI", ], description="Zolera SOAP Infrastructure", author="Rich Salz", author_email="rsalz@zolera.com", maintainer="Rich Salz", maintainer_email="rsalz@zolera.com", url=_url, long_description='For additional information, please see ' + _url )
#! /usr/bin/env python # $Header$ import sys from distutils.core import setup _url = "http://www.zolera.com/resources/opensrc/zsi" import ConfigParser cf = ConfigParser.ConfigParser() cf.read('setup.cfg') _version = "%d.%d" % \ ( cf.getint('version', 'major'), cf.getint('version', 'minor') ) try: open('ZSI/version.py', 'r').close() except: print 'ZSI/version.py not found; run "make"' sys.exit(1) setup( name="ZSI", version=_version, licence="Python", packages=[ "ZSI", ], description="Zolera SOAP Infrastructure", author="Rich Salz", author_email="rsalz@zolera.com", maintainer="Rich Salz", maintainer_email="rsalz@zolera.com", url=_url, long_description='For additional information, please see ' + _url )
Use right length of header
define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) { 'use strict'; function open(item) { function onBlock(item, byteSource) { return byteSource.slice(0, 12).getBytes().then(function(headerBytes) { var dv = new DataView( headerBytes.buffer, headerBytes.byteOffset, headerBytes.byteLength); var length = dv.getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var id = dv.getInt32(8, false); var blockItem = itemOM.createItem(name + " " + id); item.addItem(blockItem); if (length > 8) { blockItem.byteSource = byteSource.slice(12, length); } if (byteSource.byteLength >= (length + 12)) { return onBlock(item, byteSource.slice(length)); } }); } return onBlock(item, item.byteSource); } return open; });
define(['itemObjectModel', 'mac/roman'], function(itemOM, macRoman) { 'use strict'; function open(item) { function onBlock(item, byteSource) { return byteSource.slice(0, 12).getBytes().then(function(headerBytes) { var dv = new DataView(headerBytes.buffer, headerBytes.byteOffset, 4); var length = dv.getUint32(0, false); var name = macRoman(headerBytes, 4, 4); var id = dv.getInt32(8, false); var blockItem = itemOM.createItem(name + " " + id); item.addItem(blockItem); if (length > 8) { blockItem.byteSource = byteSource.slice(12, length); } if (byteSource.byteLength >= (length + 12)) { return onBlock(item, byteSource.slice(length)); } }); } return onBlock(item, item.byteSource); } return open; });
Fix client manifest download url.
angular.module( 'App.Views' ).controller( 'ClientCtrl', function( $sce, $http, App, Device, Growls ) { var _this = this; App.title = 'Game Jolt Client' this.platform = Device.os(); var MANIFEST_URL = 'http://d.gamejolt.net/data/client/manifest.json'; this.download = function( platform ) { if ( platform == 'windows' ) { platform = 'win32'; } else if ( platform == 'linux' ) { platform = 'linux64'; } else if ( platform == 'mac' ) { platform = 'osx64'; } // This will reset the iframe since it removes it when there is no download src. this.downloadSrc = undefined; $http.get( MANIFEST_URL ) .then( function( response ) { if ( !response.data[ platform ] || !response.data[ platform ].url ) { Growls.error( 'Could not find a download for your platform!' ); return; } _this.downloadSrc = $sce.trustAsResourceUrl( response.data[ platform ].url ); } ); }; } );
angular.module( 'App.Views' ).controller( 'ClientCtrl', function( $sce, $http, App, Device, Growls ) { var _this = this; App.title = 'Game Jolt Client' this.platform = Device.os(); var MANIFEST_URL = 'http://d.gamejolt.net/data/client/manifest-2.json'; this.download = function( platform ) { if ( platform == 'windows' ) { platform = 'win32'; } else if ( platform == 'linux' ) { platform = 'linux64'; } else if ( platform == 'mac' ) { platform = 'osx64'; } // This will reset the iframe since it removes it when there is no download src. this.downloadSrc = undefined; $http.get( MANIFEST_URL ) .then( function( response ) { if ( !response.data[ platform ] || !response.data[ platform ].url ) { Growls.error( 'Could not find a download for your platform!' ); return; } _this.downloadSrc = $sce.trustAsResourceUrl( response.data[ platform ].url ); } ); }; } );
Remove magic number for "count" in get requests
angular.module('cat-buddy.services', []) .factory('Animals', function($http) { var getAllFromInternetByZipCode = function(animalName, zipCode, count, offset) { offset = offset || 0; return $http({ method: 'GET', url: 'http://api.petfinder.com/pet.find', data: { key: PETFINDER_API_KEY, animal: animalName, count: count, offset: offset, location: zipCode, format: 'json' } }) .then(function(resp){ return resp.petfinder.pets; }); }; var getAllFromSaved = function() { return $http({ method: 'GET', url: '/api/' + animalName }); }; var addOneToSaved = function(animal) { return $http({ method: 'POST', url: '/api/' + animalName, data: animal }); }; return { getAllFromInternetByZipCode: getAllFromInternetByZipCode, getAllFromSaved: getAllFromSaved, addOneToSaved: addOneToSaved }; });
angular.module('cat-buddy.services', []) .factory('Animals', function($http) { var getAllFromInternetByZipCode = function(animalName, zipCode, offset) { offset = offset || 0; return $http({ method: 'GET', url: 'http://api.petfinder.com/pet.find', data: { key: PETFINDER_API_KEY, //to fix animal: animalName, count: 20, offset: offset, location: zipCode, format: 'json' } }) .then(function(resp){ return resp.petfinder.pets; }); }; var getAllFromSaved = function() { return $http({ method: 'GET', url: '/api/' + animalName }); }; var addOneToSaved = function(animal) { return $http({ method: 'POST', url: '/api/' + animalName, data: animal }); }; return { getAllFromInternetByZipCode: getAllFromInternetByZipCode, getAllFromSaved: getAllFromSaved, addOneToSaved: addOneToSaved }; });
Make class abstract so it is not run by test runner Only subclasses of ScmSyncConfigurationPluginBaseTest should be run by the test runner.
package hudson.plugins.scm_sync_configuration.util; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import hudson.plugins.scm_sync_configuration.ScmSyncConfigurationPlugin; import hudson.plugins.test.utils.scms.ScmUnderTest; // Class will start current ScmSyncConfigurationPlugin instance public abstract class ScmSyncConfigurationPluginBaseTest extends ScmSyncConfigurationBaseTest { protected ScmSyncConfigurationPluginBaseTest(ScmUnderTest scmUnderTest) { super(scmUnderTest); } public void setup() throws Throwable { super.setup(); // Let's start the plugin... ScmSyncConfigurationPlugin.getInstance().start(); } public void teardown() throws Throwable { // Stopping current plugin ScmSyncConfigurationPlugin.getInstance().stop(); super.teardown(); } protected void assertStatusManagerIsOk() { assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastFail(), nullValue()); assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastSuccess(), notNullValue()); } protected void assertStatusManagerIsNull() { assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastFail(), nullValue()); assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastSuccess(), nullValue()); } }
package hudson.plugins.scm_sync_configuration.util; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import hudson.plugins.scm_sync_configuration.ScmSyncConfigurationPlugin; import hudson.plugins.test.utils.scms.ScmUnderTest; // Class will start current ScmSyncConfigurationPlugin instance public class ScmSyncConfigurationPluginBaseTest extends ScmSyncConfigurationBaseTest { protected ScmSyncConfigurationPluginBaseTest(ScmUnderTest scmUnderTest) { super(scmUnderTest); } public void setup() throws Throwable { super.setup(); // Let's start the plugin... ScmSyncConfigurationPlugin.getInstance().start(); } public void teardown() throws Throwable { // Stopping current plugin ScmSyncConfigurationPlugin.getInstance().stop(); super.teardown(); } protected void assertStatusManagerIsOk() { assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastFail(), nullValue()); assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastSuccess(), notNullValue()); } protected void assertStatusManagerIsNull() { assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastFail(), nullValue()); assertThat(sscBusiness.getScmSyncConfigurationStatusManager().getLastSuccess(), nullValue()); } }
Add sleep method to robot
package com.tobi.movies; import android.support.annotation.IdRes; import android.support.test.espresso.contrib.RecyclerViewActions; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.*; import static org.hamcrest.core.AllOf.allOf; public abstract class Robot<T extends Robot> { protected T checkTextIsDisplayed(String text, @IdRes int view) { onView(allOf(withId(view), withText(text))).check(matches(isDisplayed())); return (T) this; } protected T selectPositionInRecyclerView(int position, @IdRes int recyclerView) { onView(withId(recyclerView)) .perform(RecyclerViewActions.actionOnItemAtPosition(position, click())); return (T) this; } public T waitFor(int seconds) throws InterruptedException { Thread.sleep(seconds * 1000); return (T) this; } public <K> K toRobot(Class<K> robotClass) throws IllegalAccessException, InstantiationException { return robotClass.newInstance(); } }
package com.tobi.movies; import android.support.annotation.IdRes; import android.support.test.espresso.contrib.RecyclerViewActions; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.*; import static org.hamcrest.core.AllOf.allOf; public abstract class Robot<T extends Robot> { protected T checkTextIsDisplayed(String text, @IdRes int view) { onView(allOf(withId(view), withText(text))).check(matches(isDisplayed())); return (T) this; } protected T selectPositionInRecyclerView(int position, @IdRes int recyclerView) { onView(withId(recyclerView)) .perform(RecyclerViewActions.actionOnItemAtPosition(position, click())); return (T) this; } public <K> K toRobot(Class<K> robotClass) throws IllegalAccessException, InstantiationException { return robotClass.newInstance(); } }
Fix the path using 'path.join()'
/* eslint-disable */ import path from 'path'; import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import graphqlHTTP from 'express-graphql'; import schema from './graphql/schema'; import { getTokenFromRequest } from './api/auth/utils'; import config from './config'; const app = express(); const ENV = process.env.NODE_ENV; const PORT = process.env.PORT || 3000; mongoose.Promise = global.Promise; mongoose.connect(`mongodb://${config.database.host}:${config.database.port}/${config.database.name}`); const db = mongoose.connection; db.on('error', console.error.bind(console, 'Connection error:')); db.once('open', () => console.log('We are connected!')); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use('/static', express.static(path.join(__dirname, 'public'))); app.use('/graphql', graphqlHTTP(req => ({ schema, context: { token: getTokenFromRequest(req) }, pretty: true, graphiql: ENV !== 'production' }))); const server = app.listen(PORT, err => { if (err) { return err; } console.log(`GraphQL server running on http://localhost:${PORT}/graphql`); }); export default server;
/* eslint-disable */ import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import graphqlHTTP from 'express-graphql'; import schema from './graphql/schema'; import { getTokenFromRequest } from './api/auth/utils'; import config from './config'; const app = express(); const ENV = process.env.NODE_ENV; const PORT = process.env.PORT || 3000; mongoose.Promise = global.Promise; mongoose.connect(`mongodb://${config.database.host}:${config.database.port}/${config.database.name}`); const db = mongoose.connection; db.on('error', console.error.bind(console, 'Connection error:')); db.once('open', () => console.log('We are connected!')); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use('/static', express.static('src/app/public')); app.use('/graphql', graphqlHTTP(req => ({ schema, context: { token: getTokenFromRequest(req) }, pretty: true, graphiql: ENV !== 'production' }))); const server = app.listen(PORT, err => { if (err) { return err; } console.log(`GraphQL server running on http://localhost:${PORT}/graphql`); }); export default server;
Tweak for building with cython
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( name = "DragonCreole", packages = ["dragoncreole"], version = "0.1.0", description = "Optimized parser for creole-like markup language", author = "Zauber Paracelsus", author_email = "admin@zauberparacelsus.xyz", url = "http://github.com/zauberparacelsus/dragoncreole", download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1", keywords = ["parser", "markup", "html"], install_requires= [ 'html2text', 'cython' ], classifiers = [ "Programming Language :: Python", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Markup :: HTML" ], long_description = "", cmdclass = {"build_ext": build_ext}, ext_modules = [Extension("dragoncreole.DragonCreoleC", ["dragoncreole/dragoncreole.py"])] )
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( name = "DragonCreole", packages = ["dragoncreole"], version = "0.1.0", description = "Optimized parser for creole-like markup language", author = "Zauber Paracelsus", author_email = "admin@zauberparacelsus.xyz", url = "http://github.com/zauberparacelsus/dragoncreole", download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1", keywords = ["parser", "markup", "html"], install_requires= [ 'html2text' ], classifiers = [ "Programming Language :: Python", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Markup :: HTML" ], long_description = "", cmdclass = {"build_ext": build_ext}, ext_modules = [Extension("DragonCreoleC", ["dragoncreole/dragoncreole.py"])] )
Replace usage of ndimage from nd to ndi
import numpy as np from scipy import ndimage as ndi def nd_sobel_magnitude(image, spacing=None): """Compute the magnitude of Sobel gradients along all axes. Parameters ---------- image : array The input image. spacing : list of float, optional The voxel spacing along each dimension. Returns ------- filtered : array The filtered image. """ image = image.astype(np.float) filtered = np.zeros_like(image) if spacing is None: spacing = np.ones(image.ndim, np.float32) for ax, sp in enumerate(spacing): axsobel = ndi.sobel(image, axis=ax) / sp filtered += axsobel * axsobel filtered = np.sqrt(filtered) return filtered
import numpy as np from scipy import ndimage as nd def nd_sobel_magnitude(image, spacing=None): """Compute the magnitude of Sobel gradients along all axes. Parameters ---------- image : array The input image. spacing : list of float, optional The voxel spacing along each dimension. Returns ------- filtered : array The filtered image. """ image = image.astype(np.float) filtered = np.zeros_like(image) if spacing is None: spacing = np.ones(image.ndim, np.float32) for ax, sp in enumerate(spacing): axsobel = nd.sobel(image, axis=ax) / sp filtered += axsobel * axsobel filtered = np.sqrt(filtered) return filtered
Remove a bit of console output junk
'use strict'; var knexConfig = require('./knex-config.js'); var knex = require('knex')(knexConfig[process.env.HAL_ENV]); var bookshelf = require('bookshelf')(knex); /* * For the unittest environment we perform a schema migration + loading * of the seed data. Each unit test can create additional data if it * wishes. However, the seed data should not be molested with too much * as most unit tests will rely on it. */ if (process.env.HAL_ENV === 'unittest') { global.unittestDataSeeded = false; knex.migrate.latest() .then(function() { knex.seed.run().then(function() { global.unittestDataSeeded = true; }); }); } module.exports = bookshelf;
'use strict'; var knexConfig = require('./knex-config.js'); var knex = require('knex')(knexConfig[process.env.HAL_ENV]); var bookshelf = require('bookshelf')(knex); console.log('Top of bookshelf.js'); console.log(' env: ' + process.env.HAL_ENV); /* * For the unittest environment we perform a schema migration + loading * of the seed data. Each unit test can create additional data if it * wishes. However, the seed data should not be molested with too much * as most unit tests will rely on it. */ if (process.env.HAL_ENV === 'unittest') { console.log('Bootstrapping database...'); global.unittestDataSeeded = false; knex.migrate.latest() .then(function() { knex.seed.run().then(function() { global.unittestDataSeeded = true; }); //global.unittestDataSeeded = true; }, function(err) { console.log(err); }); } module.exports = bookshelf;
Return the correct cookie-opt value Previously the old value would be returned after setting the new value.
var $ = require('jQuery'); var componentEvent = require('kwf/component-event'); var cookies = require('js-cookie'); var onOptChangedCb = []; var api = { getDefaultOpt: function() { var defaultOpt = $('body').data('cookieDefaultOpt'); if (defaultOpt != 'in' && defaultOpt != 'out') defaultOpt = 'in'; return defaultOpt; }, getCookieIsSet: function() { return !!cookies.get('cookieOpt'); }, getOpt: function() { if (api.getCookieIsSet()) { return cookies.get('cookieOpt'); } else { return api.getDefaultOpt(); } }, setOpt: function(value) { var oldValue = cookies.get('cookieOpt'); cookies.set('cookieOpt', value, { expires: 3*365 }); if (oldValue != value) { for (var i=0; i< onOptChangedCb.length; i++) { onOptChangedCb[i].call(this, value); } } }, onOptChanged: function(callback) { onOptChangedCb.push(callback); } }; var getAdapter = function(deferred) { deferred.resolve(api); }; module.exports = getAdapter;
var $ = require('jQuery'); var componentEvent = require('kwf/component-event'); var cookies = require('js-cookie'); var onOptChangedCb = []; var api = { getDefaultOpt: function() { var defaultOpt = $('body').data('cookieDefaultOpt'); if (defaultOpt != 'in' && defaultOpt != 'out') defaultOpt = 'in'; return defaultOpt; }, getCookieIsSet: function() { return !!cookies.get('cookieOpt'); }, getOpt: function() { if (api.getCookieIsSet()) { return cookies.get('cookieOpt'); } else { return api.getDefaultOpt(); } }, setOpt: function(value) { var opt = cookies.get('cookieOpt'); cookies.set('cookieOpt', value, { expires: 3*365 }); if (opt != value) { for (var i=0; i< onOptChangedCb.length; i++) { onOptChangedCb[i].call(this, opt); } } }, onOptChanged: function(callback) { onOptChangedCb.push(callback); } }; var getAdapter = function(deferred) { deferred.resolve(api); }; module.exports = getAdapter;
Reorder exports and added widgets export
//Neutrine version export {version} from "./src/version.js"; //Import global styles import "./src/style.scss"; //Export helpers export * from "./src/global.js"; export * from "./src/helpers.js"; export * from "./src/ready.js"; //Export basic components export * from "./src/core/index.js"; export * from "./src/experiments/index.js"; export * from "./src/future/index.js"; export * from "./src/icon/index.js"; export * from "./src/widgets/index.js"; //Loaders export * from "./src/loaders/basic-loader/index.js"; export * from "./src/loaders/dna-loader/index.js"; //Big components export * from "./src/dashboard/index.js"; export * from "./src/datatable/index.js"; //Export testing components export * from "./src/test/index.js"; //Export utils components export * from "./src/utils/choose.js"; export * from "./src/utils/for-each.js"; export * from "./src/utils/if.js"; export * from "./src/utils/renderer.js";
//Neutrine version export {version} from "./src/version.js"; //Import global styles import "./src/style.scss"; //Export helpers export * from "./src/global.js"; export * from "./src/helpers.js"; export * from "./src/ready.js"; //Export basic components export * from "./src/core/index.js"; export * from "./src/dashboard/index.js"; export * from "./src/experiments/index.js"; export * from "./src/future/index.js"; export * from "./src/icon/index.js"; //Loaders export * from "./src/loaders/basic-loader/index.js"; export * from "./src/loaders/dna-loader/index.js"; //Widgets export * from "./src/datatable/index.js"; //export * from "./src/text-editor/index.js"; //Export testing components export * from "./src/test/index.js"; //Export utils components export * from "./src/utils/choose.js"; export * from "./src/utils/for-each.js"; export * from "./src/utils/if.js"; export * from "./src/utils/renderer.js";
Add icon that works for linux apps also
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; var menu = require('./menu'); var argv = require('optimist').argv; let mainWindow; app.on('ready', function() { mainWindow = new BrowserWindow({ center: true, title: 'JBrowseDesktop', width: 1024, height: 768, icon: require('path').resolve(__dirname, 'icons/jbrowse.png') }); var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&'); mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString)); Menu.setApplicationMenu(Menu.buildFromTemplate(menu)); mainWindow.on('closed', function () { mainWindow = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function () { app.quit(); });
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; var menu = require('./menu'); var argv = require('optimist').argv; let mainWindow; app.on('ready', function() { mainWindow = new BrowserWindow({ center: true, title: 'JBrowseDesktop', width: 1024, height: 768 }); var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&'); mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString)); Menu.setApplicationMenu(Menu.buildFromTemplate(menu)); mainWindow.on('closed', function () { mainWindow = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function () { app.quit(); });