text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Extend list of supported python versions
#!/usr/bin/env python from distutils.core import setup from os.path import dirname, join from codecs import open setup(name='hashids', version='1.1.0', description='Python implementation of hashids (http://www.hashids.org).' 'Compatible with python 2.6-3.', long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(), author='David Aurelio', author_email='dev@david-aurelio.com', url='https://github.com/davidaurelio/hashids-python', license='MIT License', py_modules=('hashids',), classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ],)
#!/usr/bin/env python from distutils.core import setup from os.path import dirname, join from codecs import open setup(name='hashids', version='1.1.0', description='Python implementation of hashids (http://www.hashids.org).' 'Compatible with python 2.6-3.', long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(), author='David Aurelio', author_email='dev@david-aurelio.com', url='https://github.com/davidaurelio/hashids-python', license='MIT License', py_modules=('hashids',), classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ],)
Fix code for review comments
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging from urllib.parse import urljoin logger = logging.getLogger(__name__) def _api_call(url, params=None): params = params or {} try: logger.info("API Call for url: %s, params: %s" % (url, params)) r = requests.get(url, params=params) r.raise_for_status() result = {"data": r.json()} except requests.exceptions.HTTPError: logger.error(traceback.format_exc()) result = {"error": "Failed to retrieve data from Data Model Importer backend"} return result def fetch_pending(params=None): """Invoke Pending Graph Sync APIs for given parameters.""" params = params or {} url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/pending") return _api_call(url, params) def invoke_sync(params=None): """Invoke Graph Sync APIs to sync for given parameters.""" params = params or {} url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/sync_all") return _api_call(url, params)
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging from urllib.parse import urljoin logger = logging.getLogger(__name__) def _api_call(url, params=None): params = params or {} try: logger.info("API Call for url: %s, params: %s" % (url, params)) r = requests.get(url, params=params) r.raise_for_status() result = {"data": r.json()} except requests.exceptions.HTTPError: logger.error(traceback.format_exc()) result = {"error": "Failed to retrieve data from Data Model Importer backend"} return result def fetch_pending(params=None): params = params or {} """Invoke Pending Graph Sync APIs for given parameters.""" url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/pending") return _api_call(url, params) def invoke_sync(params=None): params = params or {} """Invoke Graph Sync APIs to sync for given parameters.""" url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/sync_all") return _api_call(url, params)
Fix display of the action when loaded a saved FAL
CRM.$(function ($) { displayActionEntity(); $('#action_type').change(function () { CRM.$('#action_entity_id').val(""); displayActionEntity(); }); }); /** * Set up the display of the action_entity_id field. * Hide if this action doesn't use it; if it does, set the label correctly, * * @returns {undefined} */ function displayActionEntity() { action_type = CRM.$('#action_type').val(); params = {'action_type': action_type}; entity = CRM.api3('FastActionLink', 'getaction', params) .done(function (result) { if (result.is_error) { CRM.$('#action_entity_id').parent().parent().hide(); } else { entityLabel = ts("Select a") + " " + ts(result.entityLabel); CRM.$("label[for='action_entity_id']").html(entityLabel); CRM.$('#action_entity_id').crmEntityRef({ entity: result.entityName, placeholder: entityLabel, create: false, select: {'minimumInputLength': 0, 'width': 'resolve'}, api: {params: result.apiParams}, }); CRM.$('#action_entity_id').parent().parent().show(); } }); }
CRM.$(function ($) { displayActionEntity(); $('#action_type').change(function () { displayActionEntity(); }); }); /** * Set up the display of the action_entity_id field. * Hide if this action doesn't use it; if it does, set the label correctly, * * @returns {undefined} */ function displayActionEntity() { action_type = CRM.$('#action_type').val(); params = {'action_type': action_type}; entity = CRM.api3('FastActionLink', 'getaction', params) .done(function (result) { if (result.is_error) { CRM.$('#action_entity_id').parent().parent().hide(); } else { entityLabel = ts("Select a") + " " + ts(result.entityLabel); CRM.$("label[for='action_entity_id']").html(entityLabel); CRM.$('#action_entity_id').val(""); CRM.$('#action_entity_id').crmEntityRef({ entity: result.entityName, placeholder: entityLabel, create: false, select: {'minimumInputLength': 0, 'width': 'resolve'}, api: {params: result.apiParams}, }); CRM.$('#action_entity_id').parent().parent().show(); } }); }
Fix issue with EDT violation occurring during FEST tests
package org.multibit.hd.ui.views; import org.multibit.hd.ui.views.components.Images; import javax.imageio.ImageIO; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.InputStream; /** * <p>Java AWT Frame to provide the following to startup sequence:</p> * <ul> * <li>A quick rendering splash screen image</li> * </ul> * * @since 0.0.8 *   */ public class SplashScreen extends Frame { private final transient Image image; public SplashScreen() throws HeadlessException { setLayout(new FlowLayout()); setUndecorated(true); // Inline the image access to avoid a Swing EDT violation during construction try (InputStream is = Images.class.getResourceAsStream("/assets/images/splash-screen.png")) { // Transform the mask color into the current themed text image = ImageIO.read(is); } catch (IOException e) { throw new IllegalStateException("The splash screen image is missing"); } setSize(image.getWidth(null), image.getHeight(null)); setLocationRelativeTo(null); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); } @Override public void paint(Graphics g) { super.paint(g); g.drawImage(image, 0, 0, this); } }
package org.multibit.hd.ui.views; import org.multibit.hd.ui.views.components.Images; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * <p>Java AWT Frame to provide the following to startup sequence:</p> * <ul> * <li>A quick rendering splash screen image</li> * </ul> * * @since 0.0.8 *   */ public class SplashScreen extends Frame { private final transient Image image; public SplashScreen() throws HeadlessException { setLayout(new FlowLayout()); setUndecorated(true); image = Images.newSplashScreenIconImage(); setSize(image.getWidth(null), image.getHeight(null)); setLocationRelativeTo(null); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); } @Override public void paint(Graphics g) { super.paint(g); g.drawImage(image, 0, 0, this); } }
devilry_qualfiesforexam: Remove period id from app url.
from django.conf.urls import patterns, url, include from django.contrib.auth.decorators import login_required from django.views.i18n import javascript_catalog from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie from devilry_settings.i18n import get_javascript_catalog_packages from .views import AppView i18n_packages = get_javascript_catalog_packages('devilry_header', 'devilry.apps.core') urlpatterns = patterns('devilry_qualifiesforexam', url('^rest/', include('devilry_qualifiesforexam.rest.urls')), url('^$', login_required(csrf_protect(ensure_csrf_cookie(AppView.as_view()))), name='devilry_qualifiesforexam_ui'), url('^i18n.js$', javascript_catalog, kwargs={'packages': i18n_packages}, name='devilry_qualifiesforexam_i18n') )
from django.conf.urls import patterns, url, include from django.contrib.auth.decorators import login_required from django.views.i18n import javascript_catalog from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie from devilry_settings.i18n import get_javascript_catalog_packages from .views import AppView i18n_packages = get_javascript_catalog_packages('devilry_header', 'devilry.apps.core') urlpatterns = patterns('devilry_qualifiesforexam', url('^rest/', include('devilry_qualifiesforexam.rest.urls')), url('^wizard/(?P<periodid>\d+)/$', login_required(csrf_protect(ensure_csrf_cookie(AppView.as_view()))), name='devilry_qualifiesforexam_ui'), url('^i18n.js$', javascript_catalog, kwargs={'packages': i18n_packages}, name='devilry_qualifiesforexam_i18n') )
Update for custom user model support
# -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = generic.GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
# -*- coding: UTF-8 -*- from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = generic.GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey("auth.User", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
PHPSDK&REMOTECS007: Remove Hold And Release options
<?php namespace com\realexpayments\remote\sdk\domain\payment; use com\realexpayments\remote\sdk\EnumBase; /** * Class ReasonCode * Enumeration for the Reason type. * @package com\realexpayments\remote\sdk\domain\payment */ class ReasonCode extends EnumBase { const __default = self::NOT_GIVEN; const FRAUD = "FRAUD"; const OUT_OF_STOCK = "OUTOFSTOCK"; const OTHER = "OTHER"; const FALSE_POSITIVE = "FALSEPOSITIVE"; const IN_STOCK = "INSTOCK"; const NOT_GIVEN = "NOTGIVEN"; /** * @var string The payment type String value */ private $type; /** * @param string $type */ public function __construct( $type ) { parent::__construct( $type ); $this->type = $type; } /** * Get the string value of the payment type * * @return string */ public function getType() { return $this->type; } }
<?php namespace com\realexpayments\remote\sdk\domain\payment; use com\realexpayments\remote\sdk\EnumBase; /** * Class ReasonCode * Enumeration for the Reason type. * @package com\realexpayments\remote\sdk\domain\payment */ class ReasonCode extends EnumBase { const __default = self::NOT_GIVEN; const FRAUD = "FRAUD"; const OUT_OF_STOCK = "OUTOFSTOCK"; const OTHER = "OTHER"; const FALSE_POSITIVE = "FALSEPOSITIVE"; const IN_STOCK = "INSTOCK"; const NOT_GIVEN = "NOTGIVEN"; const HOLD = "HOLD"; const RELEASE = "RELEASE"; /** * @var string The payment type String value */ private $type; /** * @param string $type */ public function __construct( $type ) { parent::__construct( $type ); $this->type = $type; } /** * Get the string value of the payment type * * @return string */ public function getType() { return $this->type; } }
[FIX] medical_medicament_us: Add missing dependency * medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Medicament - US Locale', 'version': '10.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_us', 'medical_medication', 'medical_manufacturer', ], 'website': 'https://laslabs.com', 'license': 'AGPL-3', 'data': [ 'views/medical_medicament_view.xml', 'security/ir.model.access.csv', ], 'installable': True, 'auto_install': True, }
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Medicament - US Locale', 'version': '10.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_us', 'medical_medication', ], 'website': 'https://laslabs.com', 'license': 'AGPL-3', 'data': [ 'views/medical_medicament_view.xml', 'security/ir.model.access.csv', ], 'installable': True, 'auto_install': True, }
Modify HelperPluginManage not to overwrite parent fields
<?php namespace ZfcTwig\View; use Zend\View\HelperPluginManager as ZendHelperPluginManager; class HelperPluginManager extends ZendHelperPluginManager { /** * HelperPluginManager constructor. * @param null $configOrContainerInstance * @param array $v3config */ public function __construct($configOrContainerInstance = null, array $v3config = []) { $this->factories['flashmessenger'] = \Zend\View\Helper\Service\FlashMessengerFactory::class; parent::__construct($configOrContainerInstance, $v3config); } /** * Default set of helpers * * @var array */ protected $invokableClasses = array( 'declarevars' => 'Zend\View\Helper\DeclareVars', 'htmlflash' => 'Zend\View\Helper\HtmlFlash', 'htmllist' => 'Zend\View\Helper\HtmlList', 'htmlobject' => 'Zend\View\Helper\HtmlObject', 'htmlpage' => 'Zend\View\Helper\HtmlPage', 'htmlquicktime' => 'Zend\View\Helper\HtmlQuicktime', 'layout' => 'Zend\View\Helper\Layout', 'renderchildmodel' => 'Zend\View\Helper\RenderChildModel', ); }
<?php namespace ZfcTwig\View; use Zend\View\HelperPluginManager as ZendHelperPluginManager; class HelperPluginManager extends ZendHelperPluginManager { /** * Default set of helpers factories * * @var array */ protected $factories = array( 'flashmessenger' => 'Zend\View\Helper\Service\FlashMessengerFactory', ); /** * Default set of helpers * * @var array */ protected $invokableClasses = array( 'declarevars' => 'Zend\View\Helper\DeclareVars', 'htmlflash' => 'Zend\View\Helper\HtmlFlash', 'htmllist' => 'Zend\View\Helper\HtmlList', 'htmlobject' => 'Zend\View\Helper\HtmlObject', 'htmlpage' => 'Zend\View\Helper\HtmlPage', 'htmlquicktime' => 'Zend\View\Helper\HtmlQuicktime', 'layout' => 'Zend\View\Helper\Layout', 'renderchildmodel' => 'Zend\View\Helper\RenderChildModel', ); }
Call MtkStyle.Reload whenever a window is created
function MtkWindow (settings) { MtkContainer.call (this, settings); MtkStyle.Reload (); this.Xaml = this.Control.Content.Root; this.Realize (); this.Override ("OnSizeAllocationRequest", function () { var self = this; return { Width: self.Control.Content.ActualWidth, Height: self.Control.Content.ActualHeight, Top: 0, Left: 0 }; }); this.Virtual ("OnFullScreenChange", function () this.QueueResize); this.Virtual ("OnToggleFullScreen", function () { this.Control.Content.FullScreen = !this.Control.Content.FullScreen; this.QueueResize (); }); this.ToggleFullScreen = function () this.OnToggleFullScreen (); this.Control.Content.OnResize = delegate (this, this.QueueResize); this.Control.Content.OnFullScreenChange = delegate (this, this.OnFullScreenChange); this.MapProperties (["Background"]); this.AfterConstructed (); }
function MtkWindow (settings) { MtkContainer.call (this, settings); this.Xaml = this.Control.Content.Root; this.Realize (); this.Override ("OnSizeAllocationRequest", function () { var self = this; return { Width: self.Control.Content.ActualWidth, Height: self.Control.Content.ActualHeight, Top: 0, Left: 0 }; }); this.Virtual ("OnFullScreenChange", function () this.QueueResize); this.Virtual ("OnToggleFullScreen", function () { this.Control.Content.FullScreen = !this.Control.Content.FullScreen; this.QueueResize (); }); this.ToggleFullScreen = function () this.OnToggleFullScreen (); this.Control.Content.OnResize = delegate (this, this.QueueResize); this.Control.Content.OnFullScreenChange = delegate (this, this.OnFullScreenChange); this.MapProperties (["Background"]); this.AfterConstructed (); }
Add type computed to the component calendar model.
import Ember from 'ember'; import computedMoment from 'ember-calendar/macros/computed-moment'; import computedDuration from 'ember-calendar/macros/computed-duration'; import Calendar from './calendar'; import OccurrenceProxy from './occurrence-proxy'; export default Calendar.extend({ component: null, timeZone: Ember.computed.oneWay('component.timeZone'), startingTime: computedMoment('component.startingDate'), dayStartingTime: computedDuration('component.dayStartingTime'), dayEndingTime: computedDuration('component.dayEndingTime'), timeSlotDuration: computedDuration('component.timeSlotDuration'), type: Ember.computed.oneWay('component.type'), defaultOccurrenceTitle: Ember.computed.oneWay( 'component.defaultOccurrenceTitle' ), defaultOccurrenceDuration: computedDuration( 'component.defaultOccurrenceDuration' ), defaultOccurrenceType: computedDuration( 'component.defaultOccurrenceType' ), occurrences: Ember.computed('component.occurrences.[]', function() { return this.get('component.occurrences').map((occurrence) => { return OccurrenceProxy.create({ calendar: this, content: occurrence }); }); }) });
import Ember from 'ember'; import computedMoment from 'ember-calendar/macros/computed-moment'; import computedDuration from 'ember-calendar/macros/computed-duration'; import Calendar from './calendar'; import OccurrenceProxy from './occurrence-proxy'; export default Calendar.extend({ component: null, timeZone: Ember.computed.oneWay('component.timeZone'), startingTime: computedMoment('component.startingDate'), dayStartingTime: computedDuration('component.dayStartingTime'), dayEndingTime: computedDuration('component.dayEndingTime'), timeSlotDuration: computedDuration('component.timeSlotDuration'), defaultOccurrenceTitle: Ember.computed.oneWay( 'component.defaultOccurrenceTitle' ), defaultOccurrenceDuration: computedDuration( 'component.defaultOccurrenceDuration' ), defaultOccurrenceType: computedDuration( 'component.defaultOccurrenceType' ), occurrences: Ember.computed('component.occurrences.[]', function() { return this.get('component.occurrences').map((occurrence) => { return OccurrenceProxy.create({ calendar: this, content: occurrence }); }); }) });
Fix typo resouceGroup -> resourceGroup
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution.resourceGroups; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.resourceGroups.ResourceGroupId; import static com.facebook.presto.spi.StandardErrorCode.QUERY_QUEUE_FULL; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class QueryQueueFullException extends PrestoException { private final ResourceGroupId resourceGroup; public QueryQueueFullException(ResourceGroupId resourceGroup) { super(QUERY_QUEUE_FULL, format("Too many queued queries for \"%s\"", resourceGroup)); this.resourceGroup = requireNonNull(resourceGroup, "resourceGroup is null"); } public ResourceGroupId getResourceGroup() { return resourceGroup; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution.resourceGroups; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.resourceGroups.ResourceGroupId; import static com.facebook.presto.spi.StandardErrorCode.QUERY_QUEUE_FULL; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class QueryQueueFullException extends PrestoException { private final ResourceGroupId resourceGroup; public QueryQueueFullException(ResourceGroupId resourceGroup) { super(QUERY_QUEUE_FULL, format("Too many queued queries for \"%s\"", resourceGroup)); this.resourceGroup = requireNonNull(resourceGroup, "resouceGroup is null"); } public ResourceGroupId getResourceGroup() { return resourceGroup; } }
Fix parameter documentation in `IPlaceholderFormField` See #2509
<?php namespace wcf\system\form\builder\field; /** * Represents a form field that supports a placeholder value. * * @author Matthias Schmidt * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @since 3.2 */ interface IPlaceholderFormField { /** * Returns the placeholder value of this field or `null` if no placeholder has * been set. * * @return null|string */ public function getPlaceholder(); /** * Sets the placeholder value of this field using the given language item * and returns this element. If `null` is passed, the placeholder value is * removed. * * @param null|string $languageItem language item containing the placeholder or `null` to unset placeholder * @param array $variables additional variables used when resolving the language item * @return static this field * * @throws \InvalidArgumentException if the given value is no string or otherwise invalid */ public function placeholder($languageItem = null, array $variables = []); }
<?php namespace wcf\system\form\builder\field; /** * Represents a form field that supports a placeholder value. * * @author Matthias Schmidt * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @since 3.2 */ interface IPlaceholderFormField { /** * Returns the placeholder value of this field or `null` if no placeholder has * been set. * * @return null|string */ public function getPlaceholder(); /** * Sets the placeholder value of this field using the given language item * and returns this element. If `null` is passed, the placeholder value is * removed. * * @param null|string $languageItem language item containing the placeholder or `null` to unset description * @param array $variables additional variables used when resolving the language item * @return static this field * * @throws \InvalidArgumentException if the given value is no string or otherwise invalid */ public function placeholder($languageItem = null, array $variables = []); }
Add some debugging for circle
package pro.cucumber; import org.junit.Before; import org.junit.Test; import pro.cucumber.gitcli.GitCliRevisionProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; public abstract class RevisionProviderContract { private Path rootPath; @Before public void createScm() throws IOException { rootPath = Files.createTempDirectory("GitWC"); Path subfolder = rootPath.resolve("subfolder"); Files.createDirectory(subfolder); Files.createFile(subfolder.resolve("file")); Exec.cmd("git init", rootPath); Exec.cmd("git add -A", rootPath); Exec.cmd("git commit -am \"files\"", rootPath); System.out.println(Exec.cmd("ls -al", rootPath)); } @Test public void findsRev() { String sha1Pattern = "^[a-f0-9]{40}$"; RevisionProvider revisionProvider = makeRevisionProvider(rootPath); assertTrue("Expected a sha1", Pattern.matches(sha1Pattern, revisionProvider.getRev())); } protected abstract RevisionProvider makeRevisionProvider(Path rootPath); }
package pro.cucumber; import org.junit.Before; import org.junit.Test; import pro.cucumber.gitcli.GitCliRevisionProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; public abstract class RevisionProviderContract { private Path rootPath; @Before public void createScm() throws IOException { rootPath = Files.createTempDirectory("GitWC"); Path subfolder = rootPath.resolve("subfolder"); Files.createDirectory(subfolder); Files.createFile(subfolder.resolve("file")); Exec.cmd("git init", rootPath); Exec.cmd("git add -A", rootPath); Exec.cmd("git commit -am \"files\"", rootPath); } @Test public void findsRev() { String sha1Pattern = "^[a-f0-9]{40}$"; RevisionProvider revisionProvider = makeRevisionProvider(rootPath); assertTrue("Expected a sha1", Pattern.matches(sha1Pattern, revisionProvider.getRev())); } protected abstract RevisionProvider makeRevisionProvider(Path rootPath); }
Fix test that was reaching over its call stack size.
const chai = require('chai'); const assert = chai.assert; const Yeti = require('../app/lib/yeti'); const Skier = require('../app/lib/skier'); var yetiEnding = require('../app/lib/yeti-ending'); describe('yetiEnding', function() { beforeEach(function () { this.canvas = document.createElement('canvas'); this.canvas.width = 600; this.canvas.height = 500; this.context = this.canvas.getContext('2d'); }); it('should set the yeti to aggressive under the right circumstances', function() { var yeti = new Yeti({ canvas: this.canvas, context: this.context }); var skier = new Skier({ canvas: this.canvas, context: this.context }); var image = new Image(); image.src = 'images/sprites.png'; skier.distance = 30500; (function doLotsOfTimes(count) { if (count < 1000) { yetiEnding(skier, yeti, image); count += 1; doLotsOfTimes(count); } })(0); assert.strictEqual(yeti.aggressive, true); }); });
const chai = require('chai'); const assert = chai.assert; const Yeti = require('../app/lib/yeti'); const Skier = require('../app/lib/skier'); var yetiEnding = require('../app/lib/yeti-ending'); describe('yetiEnding', function() { beforeEach(function () { this.canvas = document.createElement('canvas'); this.canvas.width = 600; this.canvas.height = 500; this.context = this.canvas.getContext('2d'); }); it('should set the yeti to aggressive under the right circumstances', function() { var yeti = new Yeti({ canvas: this.canvas, context: this.context }); var skier = new Skier({ canvas: this.canvas, context: this.context }); var image = new Image(); image.src = 'images/sprites.png'; skier.distance = 30500; (function doLotsOfTimes(count) { if (count < 10000) { yetiEnding(skier, yeti, image); count += 1; doLotsOfTimes(count); } })(0); assert.strictEqual(yeti.aggressive, true); }); });
Add mongoose debugging and move models to context
import bodyParser from "body-parser" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import mongoose from "mongoose" import schema from "./graphql" import Item from "./db/item" import Update from "./db/update" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb .database}`, { useMongoClient: true } ) mongoose.set("debug", true) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(req => { return { schema, context: { loaders: {}, models: { items: Item, updates: Update } } } }) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import bodyParser from "body-parser" import mongoose, { Schema } from "mongoose" import schema from "./graphql" import Item from "./db/item" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb.database}`, { useMongoClient: true } ) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(() => ({ schema })) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
Update frontend code to work on ES5 only.
(function () { var backKey = 37; var backSpaceKey = 8; var forwardKey = 39; var spaceKey = 32; var content = [ '<h1>async @ async</h1>', '<h1>Test 1</h1>', '<h1>Test 2</h1>' ] function setPageContent(index) { document.body.innerHTML = content[index]; } function navigate(by) { var index = (parseInt(document.location.hash.slice(1), 10) || 0) + by; if (index < 0) { return; } history.pushState({index: index}, '', '#' + index); setPageContent(index); } window.addEventListener('popstate', function (evt) { var index = evt.state.index; if (typeof index === 'number' && !isNaN(index)) { setPageContent(evt.state.index); } }); document.addEventListener('keyup', function (evt) { switch (evt.keyCode) { case backKey: case backSpaceKey: navigate(-1); break; case forwardKey: case spaceKey: navigate(+1); break; default: console.log(evt.keyCode); } }); new EventSource('/emitter').addEventListener('navigate', function (evt) { navigate(JSON.parse(evt.data).by); }); navigate(0); }());
(function() { const backKey = 37; const backSpaceKey = 8; const forwardKey = 39; const spaceKey = 32; const content = [ '<h1>async @ async</h1>', '<h1>Test 1</h1>', '<h1>Test 2</h1>' ] function setPageContent(index) { document.body.innerHTML = content[index]; } function navigate(by) { const index = (parseInt(document.location.hash.slice(1), 10) || 0) + by; if (index < 0) { return; } history.pushState({index}, '', `#${index}`); setPageContent(index); } window.addEventListener('popstate', evt => { const index = evt.state.index; if (typeof index === 'number' && !isNaN(index)) { setPageContent(evt.state.index); } }); document.addEventListener('keyup', evt => { switch (evt.keyCode) { case backKey: case backSpaceKey: navigate(-1); break; case forwardKey: case spaceKey: navigate(+1); break; default: console.log(evt.keyCode); } }); new EventSource('/emitter').addEventListener('navigate', evt => navigate(JSON.parse(evt.data).by)); navigate(0); }());
Use `Ext.iterate` to map response data
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.store.people.UserClasses', { extend: 'Ext.data.Store', requires: [ 'SlateAdmin.proxy.API' ], idProperty: 'value', fields: [{ name: 'value', type: 'string' }], proxy: { type: 'slateapi', url: '/people/*classes', extraParams: { interface: 'user' }, reader: { type: 'json', transform: function(response) { var records = []; Ext.iterate(response.data, function(key, value) { records.push({ value: value }); }); return records; } } } });
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.store.people.UserClasses', { extend: 'Ext.data.Store', requires: [ 'SlateAdmin.proxy.API' ], idProperty: 'value', fields: [{ name: 'value', type: 'string' }], proxy: { type: 'slateapi', url: '/invitations/*userclasses', reader: { type: 'json', transform: function(data) { return Ext.Array.map(data.data, function(value) { return { value: value } }); } } } });
Fix webs use of non-breaking spaces
package groupme import "strings" type gmMessage struct { GID string `json:"group_id"` Name string `json:"name"` MID string `json:"id"` UID string `json:"user_id"` MessageText string `json:"text"` SenderType string `json:"sender_type"` FavoritedBy []string `json:"favorited_by"` } func (m gmMessage) GroupID() string { return m.GID } func (m gmMessage) UserName() string { return m.Name } func (m gmMessage) UserID() string { return m.UID } func (m gmMessage) MessageID() string { return m.MID } func (m gmMessage) Text() string { filtered := strings.Replace(m.MessageText, "\xC2\xA0", " ", -1) return filtered } func (m gmMessage) UserType() string { return m.SenderType }
package groupme type gmMessage struct { GID string `json:"group_id"` Name string `json:"name"` MID string `json:"id"` UID string `json:"user_id"` MessageText string `json:"text"` SenderType string `json:"sender_type"` FavoritedBy []string `json:"favorited_by"` } func (m gmMessage) GroupID() string { return m.GID } func (m gmMessage) UserName() string { return m.Name } func (m gmMessage) UserID() string { return m.UID } func (m gmMessage) MessageID() string { return m.MID } func (m gmMessage) Text() string { return m.MessageText } func (m gmMessage) UserType() string { return m.SenderType }
Remove check for get_fields to fix loading order This is check is unnecessary because the add_filter option just returns false if we're unable to hook into that function. It will also cause the plugin to fail if it loads before Advanced Custom Fields
<?php /** * Plugin Name: Add Advance Custom Fields to JSON API * Description: Add Advance Custom Fields to JSON API - from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 * Author: @PanMan * Author URI: https://github.com/PanManAms/WP-JSON-API-ACF * Version: 0.1 * Plugin URI: https://github.com/PanManAms/WP-JSON-API-ACF * Copied from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 - but a plugin is nicer */ function wp_api_encode_acf($data,$post,$context){ $customMeta = (array) get_fields($post['ID']); $data['meta'] = array_merge($data['meta'], $customMeta ); return $data; } add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
<?php /** * Plugin Name: Add Advance Custom Fields to JSON API * Description: Add Advance Custom Fields to JSON API - from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 * Author: @PanMan * Author URI: https://github.com/PanManAms/WP-JSON-API-ACF * Version: 0.1 * Plugin URI: https://github.com/PanManAms/WP-JSON-API-ACF * Copied from https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51 - but a plugin is nicer */ function wp_api_encode_acf($data,$post,$context){ $customMeta = (array) get_fields($post['ID']); $data['meta'] = array_merge($data['meta'], $customMeta ); return $data; } if( function_exists('get_fields') ){ add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3); }
Use some Guava .net classes to clean up code a little
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online.partition; import java.util.List; import com.google.common.net.HostAndPort; /** * Does nothing; not applicable in local mode. * * @author Sean Owen */ public final class PartitionLoaderImpl implements PartitionLoader { /** * @throws UnsupportedOperationException */ @Override public List<List<HostAndPort>> loadPartitions(int defaultPort, String bucket, String instanceID) { throw new UnsupportedOperationException(); } }
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online.partition; import java.util.List; import org.apache.mahout.common.Pair; /** * Does nothing; not applicable in local mode. * * @author Sean Owen */ public final class PartitionLoaderImpl implements PartitionLoader { /** * @throws UnsupportedOperationException */ @Override public List<List<Pair<String, Integer>>> loadPartitions(int defaultPort, String bucket, String instanceID) { throw new UnsupportedOperationException(); } }
CC-2279: Upgrade script for converting stor directory to new format -almost there...
<?php namespace DoctrineMigrations; /* update cc_files table to include to "directory" column as well as add foreign key relation to cc_music_dirs table. */ use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; class Version20110711161043 extends AbstractMigration { public function up(Schema $schema) { //CREATE the default value of "/srv/airtime/stor", this can be updated later in the upgrade script. $this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('stor', '/srv/airtime/stor');"); $this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('upgrade', '');"); $cc_music_dirs = $schema->getTable('cc_music_dirs'); //start cc_files modifications $cc_files = $schema->getTable('cc_files'); $cc_files->addColumn('directory', 'integer', array('default'=> 2)); $cc_files->addNamedForeignKeyConstraint('cc_music_dirs_folder_fkey', $cc_music_dirs, array('directory'), array('id'), array('onDelete' => 'CASCADE')); //end cc_files modifications } public function down(Schema $schema) { } }
<?php namespace DoctrineMigrations; /* update cc_files table to include to "directory" column as well as add foreign key relation to cc_music_dirs table. */ use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; class Version20110711161043 extends AbstractMigration { public function up(Schema $schema) { //CREATE the default value of "/srv/airtime/stor", this can be updated later in the upgrade script. $this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('stor', '/srv/airtime/stor');"); $this->_addSql("INSERT INTO cc_music_dirs (type, directory) VALUES ('upgrade', '');"); } public function postUp(Schema $schema){ $cc_music_dirs = $schema->getTable('cc_music_dirs'); //start cc_files modifications $cc_files = $schema->getTable('cc_files'); $cc_files->addColumn('directory', 'integer', array('default'=> 2)); $cc_files->addNamedForeignKeyConstraint('cc_music_dirs_folder_fkey', $cc_music_dirs, array('directory'), array('id'), array('onDelete' => 'CASCADE')); //end cc_files modifications } public function down(Schema $schema) { } }
Switch from nosetest -> pytest
import os from setuptools import setup def get_version(): """Get the version info from the mpld3 package without importing it""" import ast with open(os.path.join("geneimpacts", "__init__.py"), "r") as init_file: module = ast.parse(init_file.read()) version = (ast.literal_eval(node.value) for node in ast.walk(module) if isinstance(node, ast.Assign) and node.targets[0].id == "__version__") try: return next(version) except StopIteration: raise ValueError("version could not be located") setup(version=get_version(), name='geneimpacts', description="normalize effects from variant annotation tools (snpEff, VEP)", packages=['geneimpacts', 'geneimpacts.tests'], long_description=open('README.md').read(), long_description_content_type="text/markdown", author="Brent Pedersen", author_email="bpederse@gmail.com", zip_safe=False, test_suite='pytest', include_package_data=True, tests_require=['pytest'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Bio-Informatics' ])
import os from setuptools import setup def get_version(): """Get the version info from the mpld3 package without importing it""" import ast with open(os.path.join("geneimpacts", "__init__.py"), "r") as init_file: module = ast.parse(init_file.read()) version = (ast.literal_eval(node.value) for node in ast.walk(module) if isinstance(node, ast.Assign) and node.targets[0].id == "__version__") try: return next(version) except StopIteration: raise ValueError("version could not be located") setup(version=get_version(), name='geneimpacts', description="normalize effects from variant annotation tools (snpEff, VEP)", packages=['geneimpacts', 'geneimpacts.tests'], long_description=open('README.md').read(), long_description_content_type="text/markdown", author="Brent Pedersen", author_email="bpederse@gmail.com", zip_safe=False, test_suite='nose.collector', include_package_data=True, tests_require=['nose'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Bio-Informatics' ])
Add missing fields from GetPlayerBans (v1) response
package steamapi import ( "net/url" "strconv" "strings" ) type playerBansJSON struct { Players []PlayerBan } // PlayerBan contains all ban status for community, VAC and economy type PlayerBan struct { SteamID uint64 `json:"SteamId,string"` CommunityBanned bool VACBanned bool EconomyBan string NumberOfVACBans uint DaysSinceLastBan uint NumberOfGameBans uint } // GetPlayerBans takes a list of steamIDs and returns PlayerBan slice func GetPlayerBans(steamIDs []uint64, apiKey string) ([]PlayerBan, error) { var getPlayerBans = NewSteamMethod("ISteamUser", "GetPlayerBans", 1) strSteamIDs := make([]string, len(steamIDs)) for _, id := range steamIDs { strSteamIDs = append(strSteamIDs, strconv.FormatUint(id, 10)) } data := url.Values{} data.Add("key", apiKey) data.Add("steamids", strings.Join(strSteamIDs, ",")) var resp playerBansJSON err := getPlayerBans.Request(data, &resp) if err != nil { return nil, err } return resp.Players, nil }
package steamapi import ( "net/url" "strconv" "strings" ) type playerBansJSON struct { Players []PlayerBan } // PlayerBan contains all ban status for community, VAC and economy type PlayerBan struct { SteamID uint64 `json:"SteamId,string"` CommunityBanned bool VACBanned bool EconomyBan string } // GetPlayerBans takes a list of steamIDs and returns PlayerBan slice func GetPlayerBans(steamIDs []uint64, apiKey string) ([]PlayerBan, error) { var getPlayerBans = NewSteamMethod("ISteamUser", "GetPlayerBans", 1) strSteamIDs := make([]string, len(steamIDs)) for _, id := range steamIDs { strSteamIDs = append(strSteamIDs, strconv.FormatUint(id, 10)) } data := url.Values{} data.Add("key", apiKey) data.Add("steamids", strings.Join(strSteamIDs, ",")) var resp playerBansJSON err := getPlayerBans.Request(data, &resp) if err != nil { return nil, err } return resp.Players, nil }
Rewrite Vimeo to use the new scope selection system
import foauth.providers class Vimeo(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://vimeo.com/' docs_url = 'http://developer.vimeo.com/apis/advanced' category = 'Videos' # URLs to interact with the API request_token_url = 'https://vimeo.com/oauth/request_token' authorize_url = 'https://vimeo.com/oauth/authorize' access_token_url = 'https://vimeo.com/oauth/access_token' api_domain = 'vimeo.com' available_permissions = [ (None, 'access your videos'), ('write', 'access, update and like videos'), ('delete', 'access, update, like and delete videos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Vimeo, self).get_authorize_params(redirect_uri, scopes) if any(scopes): params['permission'] = scopes[0] return params def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json') return r.json[u'person'][u'id']
import foauth.providers class Vimeo(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://vimeo.com/' docs_url = 'http://developer.vimeo.com/apis/advanced' category = 'Videos' # URLs to interact with the API request_token_url = 'https://vimeo.com/oauth/request_token' authorize_url = 'https://vimeo.com/oauth/authorize?permission=delete' access_token_url = 'https://vimeo.com/oauth/access_token' api_domain = 'vimeo.com' available_permissions = [ ('read', 'access information about videos'), ('write', 'update and like videos'), ('delete', 'delete videos'), ] def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json') return r.json[u'person'][u'id']
Replace skip with skipAll in tests
var path = require('path'), assert = require('yeoman-generator').assert, helpers = require('yeoman-generator').test, os = require('os'); describe('sails-rest-api:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({skipAll: true}) .on('end', done); }); it('Should properly create root files', function () { assert.file([ '.editorconfig', '.gitignore', '.sailsrc', 'app.js', 'package.json' ]); }); });
var path = require('path'), assert = require('yeoman-generator').assert, helpers = require('yeoman-generator').test, os = require('os'); describe('sails-rest-api:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ skipHello: true, skipInstall: true, skipGeneratorUpdate: true }) .on('end', done); }); it('Should properly create root files', function () { assert.file([ '.editorconfig', '.gitignore', '.sailsrc', 'app.js', 'package.json' ]); }); });
Fix return on active user accessing the portal
from alexandria import app, mongo from decorators import * from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash import os import shutil import requests from pymongo import MongoClient from functools import wraps import bcrypt from bson.objectid import ObjectId @app.route('/', methods=['GET']) @authenticated def index(): return render_template('app.html') @app.route('/portal') def portal(): if not session.get('username'): return render_template('portal.html') else: return redirect(url_for('index')) @app.route('/logout') def logout(): session.pop('username', None) session.pop('role', None) session.pop('realname', None) return redirect(url_for('index')) @app.route('/download/<id>/<format>') @authenticated def download(id, format): book = mongo.Books.find({'id':id})[0] response = send_from_directory(app.config['LIB_DIR'], id+'.'+format) response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"') return response @app.route('/upload') @authenticated @administrator def upload(): return render_template('upload.html') if __name__ == "__main__": app.run()
from alexandria import app, mongo from decorators import * from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash import os import shutil import requests from pymongo import MongoClient from functools import wraps import bcrypt from bson.objectid import ObjectId @app.route('/', methods=['GET']) @authenticated def index(): return render_template('app.html') @app.route('/portal') def portal(): if not session.get('username'): return render_template('portal.html') else: return render_template('index.html') @app.route('/logout') def logout(): session.pop('username', None) session.pop('role', None) session.pop('realname', None) return redirect(url_for('index')) @app.route('/download/<id>/<format>') @authenticated def download(id, format): book = mongo.Books.find({'id':id})[0] response = send_from_directory(app.config['LIB_DIR'], id+'.'+format) response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"') return response @app.route('/upload') @authenticated @administrator def upload(): return render_template('upload.html') if __name__ == "__main__": app.run()
Remove cxs property type for now
<?php namespace Jstewmc\Rtf\Element\Control\Word; /** * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a * series of strokes using pure steno notation with forward-slashes between them but * no leading- or trailing-slashes. * * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#) * are allowed. * * A hyphen is used in cases where there may be confusion between initial and final * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS. * * If the number bar was used in a stroke, the stroke contains a number sign to * indicate that. The number sign may be anywhere within the stroke, but it should * probably be at one end or the other. Keep in mind, most steno programs will output * the digit when the number bar is used to create a number, but the number sign when * the number bar is used to create a stroke (e.g., "/K#"). */ class Cxs extends Word { /** * The "\cxs" is an ignored control word */ protected $isIgnored = true; }
<?php namespace Jstewmc\Rtf\Element\Control\Word; /** * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a * series of strokes using pure steno notation with forward-slashes between them but * no leading- or trailing-slashes. * * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#) * are allowed. * * A hyphen is used in cases where there may be confusion between initial and final * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS. * * If the number bar was used in a stroke, the stroke contains a number sign to * indicate that. The number sign may be anywhere within the stroke, but it should * probably be at one end or the other. Keep in mind, most steno programs will output * the digit when the number bar is used to create a number, but the number sign when * the number bar is used to create a stroke (e.g., "/K#"). */ class Cxs extends Word { /** * The "\cxs" is an ignored control word */ protected bool $isIgnored = true; }
Adjust async run handler to use the JobContext manager.
# # Copyright 2012 WebFilings, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = Async.from_dict(async_options) logging.info(work._function_path) with context.job_context_from_async(async): run_job(async) return 200, work._function_path
# # Copyright 2012 WebFilings, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) work = Async.from_dict(async_options) logging.info(work._function_path) run_job(work) return 200, work._function_path
Use Meteor.wrapAsync instead of Fibers.
// Get our NPM stuff. request = Npm.require("request"); // Wrap request with something that can be `Meteor.wrapAsync`ed. var requestAsync = function(uri, options, callback) { request(uri, options, function(error, response, body) { if (error) { console.log(error); callback(error); } else { callback(null, { response: response, body: body }); } }); }; // Make a sync function out of it. var requestSync; if (typeof Meteor.wrapAsync === "function") { requestSync = Meteor.wrapAsync(requestAsync); } else { requestSync = Meteor._wrapAsync(requestAsync); } // Use this to extend the prototype _.extend(request, { putSync: function(uri, options) { options.method = "PUT"; return requestSync(uri, options); }, patchSync: function(uri, options) { options.method = "PATCH"; return requestSync(uri, options); }, postSync: function(uri, options) { options.method = "POST"; return requestSync(uri, options); }, headSync: function(uri, options) { options.method = "HEAD"; return requestSync(uri, options); }, delSync: function(uri, options) { options.method = "DELETE"; return requestSync(uri, options); }, getSync: requestSync });
// Get our NPM stuff. var Future = Npm.require("fibers/future"); request = Npm.require("request"); // This is our main wrapping function, using Fibers. var requestSync = function(uri, options) { var future = new Future(); request(uri, options, function(error, response, body) { if (error) { console.log(error); throw error; } future.return({ response: response, body: body }); }); return future.wait(); }; // Use this to extend the prototype _.extend(request, { putSync: function(uri, options) { options.method = "PUT"; return requestSync(uri, options); }, patchSync: function(uri, options) { options.method = "PATCH"; return requestSync(uri, options); }, postSync: function(uri, options) { options.method = "POST"; return requestSync(uri, options); }, headSync: function(uri, options) { options.method = "HEAD"; return requestSync(uri, options); }, delSync: function(uri, options) { options.method = "DELETE"; return requestSync(uri, options); }, getSync: requestSync });
Make attributes in struct more visible
package TLSHandshakeDecoder import ( _ "bytes" "errors" "fmt" ) type TLSRecordLayer struct { ContentType uint8 Version uint16 length uint16 Fragment []byte } func DecodeRecord(p *TLSRecordLayer, data []byte) error { if len(data) < 5 { return errors.New("Payload too short to be a TLS packet.") } p.ContentType = uint8(data[0]) p.Version = uint16(data[1])<<8 | uint16(data[2]) p.length = uint16(data[3])<<8 | uint16(data[4]) p.Fragment = make([]byte, p.length) l := copy(p.Fragment, data[5:5+p.length]) if l < int(p.length) { return fmt.Errorf("Payload to short: copied %d, expected %d.", l, p.length) } return nil }
package TLSHandshakeDecoder import ( _ "bytes" "errors" "fmt" ) type TLSRecordLayer struct { contentType uint8 version uint16 length uint16 Fragment []byte } func DecodeRecord(p *TLSRecordLayer, data []byte) error { if len(data) < 5 { return errors.New("Payload too short to be a TLS packet.") } p.contentType = uint8(data[0]) p.version = uint16(data[1])<<8 | uint16(data[2]) p.length = uint16(data[3])<<8 | uint16(data[4]) p.Fragment = make([]byte, p.length) l := copy(p.Fragment, data[5:5+p.length]) if l < int(p.length) { return fmt.Errorf("Payload to short: copied %d, expected %d.", l, p.length) } return nil }
Allow no setting parameter at all.
function Carousel(settings){ 'use strict'; settings = settings || {}; this.carousel = document.querySelector(settings.carousel || '.carousel'); this.slides = this.carousel.querySelectorAll('ul li'); this.delay = settings.delay || 2.5; this.autoplay = settings.autoplay === undefined ? true : settings.autoplay; this.slides_total = this.slides.length; this.current_slide = -1; if (this.autoplay) { this.play(); } } Carousel.prototype.next = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = (this.current_slide + 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.prev = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = Math.abs(this.current_slide - 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.play = function () { 'use strict'; this.next(); var that = this; if (this.autoplay) { this.interval = setTimeout(function () { that.play(); }, this.delay * 1000); } };
function Carousel(settings){ 'use strict'; this.carousel = document.querySelector(settings.carousel || '.carousel'); this.slides = this.carousel.querySelectorAll('ul li'); this.delay = settings.delay || 2.5; this.autoplay = settings.autoplay === undefined ? true : settings.autoplay; this.slides_total = this.slides.length; this.current_slide = -1; if (this.autoplay) { this.play(); } } Carousel.prototype.next = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = (this.current_slide + 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.prev = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = Math.abs(this.current_slide - 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.play = function () { 'use strict'; this.next(); var that = this; if (this.autoplay) { this.interval = setTimeout(function () { that.play(); }, this.delay * 1000); } };
Correct typo for style prop.
/** * Spinner component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * A single module. Keeps track of its own active state and settings. */ function Spinner( { isSaving, style = {} } ) { return ( <span className="spinner" style={ { display: isSaving ? 'inline-block' : 'none', float: 'none', marginTop: '0', visibility: 'visible', ...style, } } /> ); } Spinner.propTypes = { isSaving: PropTypes.bool, style: PropTypes.object, }; export default Spinner;
/** * Spinner component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * A single module. Keeps track of its own active state and settings. */ function Spinner( { isSaving, styles = {} } ) { return ( <span className="spinner" style={ { display: isSaving ? 'inline-block' : 'none', float: 'none', marginTop: '0', visibility: 'visible', ...styles, } } /> ); } Spinner.propTypes = { isSaving: PropTypes.bool, styles: PropTypes.object, }; export default Spinner;
Set default accept header to json
package fr.insee.rmes.api.utils; import javax.ws.rs.core.MediaType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class ResponseUtils { private static Logger logger = LogManager.getLogger(ResponseUtils.class); public static String produceResponse(Object obj, String header) { ObjectMapper mapper = new ObjectMapper();; String response = ""; if (header != null && header.equals(MediaType.APPLICATION_XML)) { mapper = new XmlMapper(); } else { mapper = new ObjectMapper(); } try { response = mapper.writeValueAsString(obj); } catch (Exception e) { logger.error(e.getMessage()); } return response; } }
package fr.insee.rmes.api.utils; import javax.ws.rs.core.MediaType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class ResponseUtils { private static Logger logger = LogManager.getLogger(ResponseUtils.class); public static String produceResponse(Object obj, String header) { ObjectMapper mapper; String response = ""; if (header == null || header.equals(MediaType.APPLICATION_JSON)) { mapper = new ObjectMapper(); } else { mapper = new XmlMapper(); } try { response = mapper.writeValueAsString(obj); } catch (Exception e) { logger.error(e.getMessage()); } return response; } }
Convert unit test to test all registered schemas instead of plugins directly.
from __future__ import unicode_literals, division, absolute_import import jsonschema from flexget import config_schema from tests import FlexGetBase class TestSchemaValidator(FlexGetBase): def test_registered_schemas_are_valid(self): for path in config_schema.schema_paths: schema = config_schema.resolve_ref(path) try: config_schema.SchemaValidator.check_schema(schema) except jsonschema.SchemaError as e: assert False, 'plugin `%s` has an invalid schema. %s %s' % ( path, '/'.join(str(p) for p in e.path), e.message) def test_resolves_local_refs(self): schema = {'$ref': '/schema/plugin/accept_all'} v = config_schema.SchemaValidator(schema) # accept_all schema should be for type boolean assert v.is_valid(True) assert not v.is_valid(14) def test_custom_format_checker(self): schema = {'type': 'string', 'format': 'quality'} v = config_schema.SchemaValidator(schema) assert v.is_valid('720p') assert not v.is_valid('aoeu')
from __future__ import unicode_literals, division, absolute_import import jsonschema from flexget import config_schema from flexget import plugin from tests import FlexGetBase class TestSchemaValidator(FlexGetBase): def test_plugin_schemas_are_valid(self): for p in plugin.plugins.values(): if p.schema is None: continue try: config_schema.SchemaValidator.check_schema(p.schema) except jsonschema.SchemaError as e: assert False, 'plugin `%s` has an invalid schema. %s %s' % ( p.name, '/'.join(str(p) for p in e.path), e.message) def test_resolves_local_refs(self): schema = {'$ref': '/schema/plugin/accept_all'} v = config_schema.SchemaValidator(schema) # accept_all schema should be for type boolean assert v.is_valid(True) assert not v.is_valid(14) def test_custom_format_checker(self): schema = {'type': 'string', 'format': 'quality'} v = config_schema.SchemaValidator(schema) assert v.is_valid('720p') assert not v.is_valid('aoeu')
Use the correct name for the run script It may be time to go home.
#! /usr/bin/env python import sys import subprocess class BmiIlamb(object): _command = 'run_ilamb.sh' _args = None _env = None def __init__(self): self._time = self.get_start_time() @property def args(self): return [self._command] + (self._args or []) def get_component_name(self): return 'ILAMB' def initialize(self, filename): self._args = [filename or 'ILAMB_PARA_SETUP'] def update(self): subprocess.check_call(self.args, shell=False, env=self._env) self._time = self.get_end_time() def update_until(self, time): self.update(time) def finalize(self): pass def get_input_var_names(self): return () def get_output_var_names(self): return () def get_start_time(self): return 0.0 def get_end_time(self): return 1.0 def get_current_time(self): return self._time
#! /usr/bin/env python import sys import subprocess class BmiIlamb(object): _command = 'run_ilamb' _args = None _env = None def __init__(self): self._time = self.get_start_time() @property def args(self): return [self._command] + (self._args or []) def get_component_name(self): return 'ILAMB' def initialize(self, filename): self._args = [filename or 'ILAMB_PARA_SETUP'] def update(self): subprocess.check_call(self.args, shell=False, env=self._env) self._time = self.get_end_time() def update_until(self, time): self.update(time) def finalize(self): pass def get_input_var_names(self): return () def get_output_var_names(self): return () def get_start_time(self): return 0.0 def get_end_time(self): return 1.0 def get_current_time(self): return self._time
Add docstring to export investment project mock
var investmentProjects = require('../../../fixtures/v3/search/investment-project.json') exports.investmentProjects = function (req, res) { const hasFilters = !!( req.body.estimated_land_date_before || req.body.estimated_land_date_after || req.body.sector_descends || req.body.adviser ) if (req.body.uk_region_location) { var regionQuery = req.body.uk_region_location var regions = typeof regionQuery === 'string' ? [regionQuery] : regionQuery var ukRegionFilteredResults = _.filter( investmentProjects.results, function (investmentProject) { return _.intersection( regions, investmentProject.actual_uk_regions.map(function (region) { return region.id }) ).length } ) return res.json({ count: ukRegionFilteredResults.length, results: ukRegionFilteredResults, }) } else if (hasFilters) { return res.json({ count: 12, results: investmentProjects.results, }) } else { return res.json(investmentProjects) } } exports.export = function (req, res) { /* * Mock a simple csv file for export */ res.header('Content-Type', 'text/csv') res.attachment('export.csv') res.send('a,b,c\n1,2,3') }
var investmentProjects = require('../../../fixtures/v3/search/investment-project.json') exports.investmentProjects = function (req, res) { const hasFilters = !!( req.body.estimated_land_date_before || req.body.estimated_land_date_after || req.body.sector_descends || req.body.adviser ) if (req.body.uk_region_location) { var regionQuery = req.body.uk_region_location var regions = typeof regionQuery === 'string' ? [regionQuery] : regionQuery var ukRegionFilteredResults = _.filter( investmentProjects.results, function (investmentProject) { return _.intersection( regions, investmentProject.actual_uk_regions.map(function (region) { return region.id }) ).length } ) return res.json({ count: ukRegionFilteredResults.length, results: ukRegionFilteredResults, }) } else if (hasFilters) { return res.json({ count: 12, results: investmentProjects.results, }) } else { return res.json(investmentProjects) } } exports.export = function (req, res) { res.header('Content-Type', 'text/csv') res.attachment('export.csv') res.send('a,b,c\n1,2,3') }
Make object.Type a type alias
package object type Type = string const ( /* Internal Types */ RETURN_VALUE = "<return value>" FUNCTION = "<function>" NEXT = "<next>" BREAK = "<break>" /* Special Types */ COLLECTION = "<collection>" CONTAINER = "<container>" HASHER = "<hasher>" ANY = "<any>" /* Normal Types */ NUMBER = "<number>" BOOLEAN = "<boolean>" STRING = "<string>" CHAR = "<char>" ARRAY = "<array>" NULL = "<null>" BLOCK = "<block>" TUPLE = "<tuple>" MAP = "<map>" CLASS = "<class>" INIT = "<init method>" METHOD = "<method>" INSTANCE = "<instance>" ) func is(obj Object, t Type) bool { if t == ANY { return true } if t == COLLECTION { _, ok := obj.(Collection) return ok } if t == CONTAINER { _, ok := obj.(Container) return ok } if t == HASHER { _, ok := obj.(Hasher) return ok } return obj.Type() == t }
package object type Type string const ( /* Internal Types */ RETURN_VALUE Type = "<return value>" FUNCTION Type = "<function>" NEXT Type = "<next>" BREAK Type = "<break>" /* Special Types */ COLLECTION Type = "<collection>" CONTAINER Type = "<container>" HASHER Type = "<hasher>" ANY Type = "<any>" /* Normal Types */ NUMBER Type = "<number>" BOOLEAN Type = "<boolean>" STRING Type = "<string>" CHAR Type = "<char>" ARRAY Type = "<array>" NULL Type = "<null>" BLOCK Type = "<block>" TUPLE Type = "<tuple>" MAP Type = "<map>" CLASS Type = "<class>" INIT Type = "<init method>" METHOD Type = "<method>" INSTANCE Type = "<instance>" ) func is(obj Object, t Type) bool { if t == ANY { return true } if t == COLLECTION { _, ok := obj.(Collection) return ok } if t == CONTAINER { _, ok := obj.(Container) return ok } if t == HASHER { _, ok := obj.(Hasher) return ok } return obj.Type() == t }
Comment out csv test case Travis
'use strict'; var grunt = require('grunt'); function readFile(file) { var contents = grunt.file.read(file); if (process.platform === 'win32') { contents = contents.replace(/\r\n/g, '\n'); } return contents; } exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(3); actual = readFile('reports/txt/report.txt'); expected = readFile('test/expected/txt/report.txt'); test.equal(actual, expected, 'Should produce a TXT report without DOM element for a test file'); actual = readFile('reports/json/report.json'); expected = readFile('test/expected/json/report.json'); test.equal(actual, expected, 'Should produce a JSON report without DOM element for a test file'); // This is commented out since travis has some issues with csv or something // ---------- // actual = readFile('reports/csv/report.csv'); // expected = readFile('test/expected/csv/report.csv'); // test.equal(actual, expected, 'Should produce a CSV report without DOM element for a test file'); test.done(); } };
'use strict'; var grunt = require('grunt'); function readFile(file) { var contents = grunt.file.read(file); if (process.platform === 'win32') { contents = contents.replace(/\r\n/g, '\n'); } return contents; } exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(3); actual = readFile('reports/txt/report.txt'); expected = readFile('test/expected/txt/report.txt'); test.equal(actual, expected, 'Should produce a TXT report without DOM element for a test file'); actual = readFile('reports/json/report.json'); expected = readFile('test/expected/json/report.json'); test.equal(actual, expected, 'Should produce a JSON report without DOM element for a test file'); actual = readFile('reports/csv/report.csv'); expected = readFile('test/expected/csv/report.csv'); test.equal(actual, expected, 'Should produce a CSV report without DOM element for a test file'); test.done(); } };
Remove redundant created on value
'use strict'; const collectionValidator = require('../validators/collection'), repo = require('../repositories/collection'), restify = require('restify'); module.exports = { post: (req, res, next) => { let collection = req.body; let username = req.user.username; let errors = collectionValidator(collection); if (errors && errors.length) { let msg = errors[0].message; return next(new restify.errors.BadRequestError(msg)); } collection.username = username; let docSource = repo .get(username, collection.name) .do(doc => { if (doc) { let msg = `user ${username} already has a collection named ${collection.name}`; throw new restify.errors.ConflictError(msg); } }) .flatMap(repo.create(collection)) .subscribe(data => res.send(data), next, next); } };
'use strict'; const collectionValidator = require('../validators/collection'), repo = require('../repositories/collection'), restify = require('restify'); module.exports = { post: (req, res, next) => { let collection = req.body; let username = req.user.username; let errors = collectionValidator(collection); if (errors && errors.length) { let msg = errors[0].message; return next(new restify.errors.BadRequestError(msg)); } collection.username = username; collection.created = new Date(); let docSource = repo .get(username, collection.name) .do(doc => { if (doc) { let msg = `user ${username} already has a collection named ${collection.name}`; throw new restify.errors.ConflictError(msg); } }) .flatMap(repo.create(collection)) .subscribe(data => res.send(data), next, next); } };
Add UsesQCoreApplication in state machine test
#!/usr/bin/python import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation from helper import UsesQCoreApplication class QStateMachineTest(UsesQCoreApplication): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, self.app.quit) self.app.exec_() if __name__ == '__main__': unittest.main()
#!/usr/bin/python import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation class QStateMachineTest(unittest.TestCase): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): app = QCoreApplication([]) self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, app.quit) app.exec_() if __name__ == '__main__': unittest.main()
Rename route '/users/{user_name}/{project_name}' to '/projects/{project_name}'
from routes.index import index from routes.project_page import project from routes.user_overview import user_overview from routes.project_overview import group_overview, series_overview from routes.login import login def setup_routes(app): """ Sets up all the routes for the webapp. :param app: :return: """ app.router.add_get('/', index) app.router.add_post('/login', login) app.router.add_get('/user_overview', user_overview) app.router.add_get('/projects/', group_overview) app.router.add_get('/projects/legacy/{group_series}/{group_part}', group_overview) app.router.add_get('/projects/legacy/{group_series}/', series_overview) app.router.add_get('/projects/{project_name}', project)
from routes.index import index from routes.project_page import project from routes.user_overview import user_overview from routes.project_overview import group_overview, series_overview from routes.login import login def setup_routes(app): """ Sets up all the routes for the webapp. :param app: :return: """ app.router.add_get('/', index) app.router.add_post('/login', login) app.router.add_get('/user_overview', user_overview) app.router.add_get('/projects/', group_overview) app.router.add_get('/projects/legacy/{group_series}/{group_part}', group_overview) app.router.add_get('/projects/legacy/{group_series}/', series_overview) app.router.add_get('/users/{user_name}/{project_name}', project)
Create new object instead of modifying, to make sure they are optimized by V8
import Set from 'es6-set'; import blockElements from 'block-elements'; const BLOCK_ELEMENTS = new Set(blockElements); const TEXT_ELEMENTS = { h1: 'header1', h2: 'header2', h3: 'header3', h4: 'header4', h5: 'header5', h6: 'header6', p: 'paragraph', blockquote: 'blockquote' }; const isPullQuote = (elm) => { return elm.classList.contains('q'); }; const createBlockElement = (type, elm) => { if (type === 'blockquote') { return { type, pullQuote: isPullQuote(elm), children: [] }; } else { return { type, children: [] }; } }; // inject parse to avoid recursive requires export default (parse, text) => { return (elm, textOpts) => { const tagName = elm.tagName.toLowerCase(); if (BLOCK_ELEMENTS.has(tagName)) { const type = TEXT_ELEMENTS[tagName] || 'block'; const blockElement = createBlockElement(type, elm); if (elm.childNodes.length) { parse(elm.childNodes, text(textOpts, elm), blockElement.children); } return blockElement; } }; };
import Set from 'es6-set'; import blockElements from 'block-elements'; const BLOCK_ELEMENTS = new Set(blockElements); const TEXT_ELEMENTS = { h1: 'header1', h2: 'header2', h3: 'header3', h4: 'header4', h5: 'header5', h6: 'header6', p: 'paragraph', blockquote: 'blockquote' }; const isPullQuote = (elm) => { return elm.classList.contains('q'); }; // inject parse to avoid recursive requires export default (parse, text) => { return (elm, textOpts) => { const tagName = elm.tagName.toLowerCase(); if (BLOCK_ELEMENTS.has(tagName)) { const type = TEXT_ELEMENTS[tagName] || 'block'; const blockElement = { type, children: [] }; if (elm.childNodes.length) { parse(elm.childNodes, text(textOpts, elm), blockElement.children); } if (type === 'blockquote') { blockElement.pullQuote = isPullQuote(elm); } return blockElement; } }; };
Allow API to return health response when in a custom state
package api func (c *Sys) Health() (*HealthResponse, error) { r := c.c.NewRequest("GET", "/v1/sys/health") // If the code is 400 or above it will automatically turn into an error, // but the sys/health API defaults to returning 5xx when not sealed or // inited, so we force this code to be something else so we parse correctly r.Params.Add("uninitcode", "299") r.Params.Add("sealedcode", "299") r.Params.Add("standbycode", "299") r.Params.Add("drsecondarycode", "299") resp, err := c.c.RawRequest(r) if err != nil { return nil, err } defer resp.Body.Close() var result HealthResponse err = resp.DecodeJSON(&result) return &result, err } type HealthResponse struct { Initialized bool `json:"initialized"` Sealed bool `json:"sealed"` Standby bool `json:"standby"` ReplicationPerfMode string `json:"replication_perf_mode"` ReplicationDRMode string `json:"replication_dr_mode"` ServerTimeUTC int64 `json:"server_time_utc"` Version string `json:"version"` ClusterName string `json:"cluster_name,omitempty"` ClusterID string `json:"cluster_id,omitempty"` }
package api func (c *Sys) Health() (*HealthResponse, error) { r := c.c.NewRequest("GET", "/v1/sys/health") // If the code is 400 or above it will automatically turn into an error, // but the sys/health API defaults to returning 5xx when not sealed or // inited, so we force this code to be something else so we parse correctly r.Params.Add("sealedcode", "299") r.Params.Add("uninitcode", "299") resp, err := c.c.RawRequest(r) if err != nil { return nil, err } defer resp.Body.Close() var result HealthResponse err = resp.DecodeJSON(&result) return &result, err } type HealthResponse struct { Initialized bool `json:"initialized"` Sealed bool `json:"sealed"` Standby bool `json:"standby"` ReplicationPerfMode string `json:"replication_perf_mode"` ReplicationDRMode string `json:"replication_dr_mode"` ServerTimeUTC int64 `json:"server_time_utc"` Version string `json:"version"` ClusterName string `json:"cluster_name,omitempty"` ClusterID string `json:"cluster_id,omitempty"` }
Fix for 1.6 & 1.7
from django.views.generic.base import TemplateView from django.conf.urls import patterns, url, include import settings import os from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name="index.html")), url(r'^test/', 'test_app.views.test_index'), url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += patterns( '', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join( os.path.dirname(settings.__file__), 'static')}))
try: from django.conf.urls.defaults import patterns, include, url except ImportError: from django.conf.urls import patterns, url, include import settings import os from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'index.html'} ), url(r'^test/', 'test_app.views.test_index'), url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += patterns( '', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join( os.path.dirname(settings.__file__), 'static')}))
Update with reference to global nav partial
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var postcss = require('postcss') var cssstats = require('cssstats') var floats = require('tachyons-floats/package.json') var floatsCss = fs.readFileSync('node_modules/tachyons-floats/tachyons-floats.min.css', 'utf8') var floatsObj = cssstats(floatsCss) var floatsSize = filesize(floatsObj.gzipSize) var srcCSS = fs.readFileSync('./src/_floats.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/floats/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ floatsVersion: floats.version, floatsSize: floatsSize, floatsObj:floatsObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/floats/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var postcss = require('postcss') var cssstats = require('cssstats') var floats = require('tachyons-floats/package.json') var floatsCss = fs.readFileSync('node_modules/tachyons-floats/tachyons-floats.min.css', 'utf8') var floatsObj = cssstats(floatsCss) var floatsSize = filesize(floatsObj.gzipSize) var srcCSS = fs.readFileSync('./src/_floats.css', 'utf8') var template = fs.readFileSync('./templates/docs/floats/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ floatsVersion: floats.version, floatsSize: floatsSize, floatsObj:floatsObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/layout/floats/index.html', html)
Add stubs for addEdge methods for graph adjacency list.
import java.util.List; import java.util.ArrayList; /* Implements an adjacency list using linked lists. */ class GraphAdjacencyList<T> { private List<Node<T>> adjacencyList; public GraphAdjacencyList(int size) { this.adjacencyList = new ArrayList<Node<T>>(size); } /* Return true if firstNode points to secondNode. */ protected boolean hasDirectedEdge(T firstNode, T secondNode) { return true; } /* Return true if both firstNode and secondNode point to each other. */ protected boolean hasUndirectedEdge(T firstNode, T secondNode) { return true; } /* Add an edge from firstNode to secondNode. */ protected void addDirectedEdge(T firstNode, T secondNode) { return; } /* Remove the edge from firstNode to secondNode. */ protected void removeDirectedEdge(T firstNode, T secondNode) { return; } /* Remove the edge between both firstNode and secondNode. */ protected void removeUndirectedEdge(T firstNode, T secondNode) { return; } /* Finds the linked list starting with node value findData. */ private Node getNode(T findData) { Node current = this; while(current.data != findData) { current = current.next; } return current; } }
import java.util.List; import java.util.ArrayList; /* Implements an adjacency list using linked lists. */ class GraphAdjacencyList<T> { private List<Node<T>> adjacencyList; public GraphAdjacencyList(int size) { this.adjacencyList = new ArrayList<Node<T>>(size); } /* Return true if firstNode points to secondNode. */ protected boolean hasDirectedEdge(T firstNode, T secondNode) { return true; } /* Return true if both firstNode and secondNode point to each other. */ protected boolean hasUndirectedEdge(T firstNode, T secondNode) { return true; } /* Add an edge from firstNode to secondNode. */ protected void addDirectedEdge(T firstNode, T secondNode) { return; } /* Finds the linked list starting with node value findData. */ private Node getNode(T findData) { Node current = this; while(current.data != findData) { current = current.next; } return current; } }
Use resolve helper instead of app
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ use Flarum\Extend; use Flarum\Frontend\Document; use Psr\Http\Message\ServerRequestInterface as Request; return [ (new Extend\Frontend('forum')) ->route( '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]', 'embed.discussion', function (Document $document, Request $request) { // Add the discussion content to the document so that the // payload will be included on the page and the JS app will be // able to render the discussion immediately. resolve(Flarum\Forum\Content\Discussion::class)($document, $request); resolve(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request); } ), (new Extend\Frontend('embed')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ];
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ use Flarum\Extend; use Flarum\Frontend\Document; use Psr\Http\Message\ServerRequestInterface as Request; return [ (new Extend\Frontend('forum')) ->route( '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]', 'embed.discussion', function (Document $document, Request $request) { // Add the discussion content to the document so that the // payload will be included on the page and the JS app will be // able to render the discussion immediately. app(Flarum\Forum\Content\Discussion::class)($document, $request); app(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request); } ), (new Extend\Frontend('embed')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ];
Fix webui integration tests to use https
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { 'page': '', 'matching_text': 'Diamond', }, { 'page': 'scoreboard', }, { 'page': 'login', 'matching_text': 'Please sign in', }, { 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { 'page': 'overview', }, { 'page': 'api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://nginx' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { 'page': '/login', 'matching_text': 'Please sign in', }, { 'page': '/about', 'matching_text': 'Use the following credentials to login', }, { 'page': '/overview', }, { 'page': '/api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
Change way we init fading. The current strategy fails when chicago-brick is used as an npm dep. Instead, do something that works, but is also hacky.
/* Copyright 2015 Google Inc. 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. ==============================================================================*/ 'use strict'; var EventEmitter = require('events'); var assert = require('assert'); class ModuleLibrary extends EventEmitter { constructor() { super(); // Map of name -> ModuleDef this.modules = {}; } register(def) { assert(!(def.name in this.modules), 'Def ' + def.name + ' already exists!'); this.modules[def.name] = def; // We can safely use 'on' rather than 'once' here, because neither the // moduledefs nor this library are ever destroyed. def.on('reloaded', () => { this.emit('reloaded', def); }); if (def.name == 'solid') { this.register(def.extend('_faded_out', '', '', { color: 'black' })); } } } module.exports = new ModuleLibrary;
/* Copyright 2015 Google Inc. 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. ==============================================================================*/ 'use strict'; var EventEmitter = require('events'); var assert = require('assert'); var ModuleDef = require('server/modules/module_def'); class ModuleLibrary extends EventEmitter { constructor() { super(); // Map of name -> ModuleDef this.modules = {}; } register(def) { assert(!(def.name in this.modules), 'Def ' + def.name + ' already exists!'); this.modules[def.name] = def; // We can safely use 'on' rather than 'once' here, because neither the // moduledefs nor this library are ever destroyed. def.on('reloaded', () => { this.emit('reloaded', def); }); } } let library = new ModuleLibrary; // Engine modules. library.register(new ModuleDef('_faded_out', 'demo_modules/solid/solid.js', '', '', { color: 'black' })); module.exports = library;
style: Fix an old flake8 error
import os from frigg_settings.helpers import FileSystemWrapper def path(*args): return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args) def test_filesystemwrapper_list_files(): wrapper = FileSystemWrapper() files = wrapper.list_files(path()) # This check cannot check the exact files because of # generated coverage files. assert '.frigg.yml' in files assert '.gitignore' in files assert 'frigg_settings' not in files assert 'tests' not in files def test_filesystemwrapper_read_file(): wrapper = FileSystemWrapper() assert( wrapper.read_file(path('MANIFEST.in')) == 'include setup.py README.md MANIFEST.in LICENSE\n' ) def test_filesystemwrapper_file_exist(): wrapper = FileSystemWrapper() assert wrapper.file_exist(path('setup.py')) assert not wrapper.file_exist(path('non-exsting')) assert not wrapper.file_exist(path('tests'))
import os from frigg_settings.helpers import FileSystemWrapper def path(*args): return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args) def test_filesystemwrapper_list_files(): wrapper = FileSystemWrapper() files = wrapper.list_files(path()) # This check cannot check the exact files because of # generated coverage files. assert '.frigg.yml' in files assert '.gitignore' in files assert 'frigg_settings' not in files assert 'tests' not in files def test_filesystemwrapper_read_file(): wrapper = FileSystemWrapper() assert( wrapper.read_file(path('MANIFEST.in')) == 'include setup.py README.md MANIFEST.in LICENSE\n' ) def test_filesystemwrapper_file_exist(): wrapper = FileSystemWrapper() assert wrapper.file_exist(path('setup.py')) assert not wrapper.file_exist(path('non-exsting')) assert not wrapper.file_exist(path('tests'))
Fix bug with self reference
from __future__ import absolute_import from datetime import datetime import argparse as _argparse import os def is_dir(string): """ Type check for a valid directory for ArgumentParser. """ if not os.path.isdir(string): msg = '{0} is not a directory'.format(string) raise _argparse.ArgumentTypeError(msg) return string def is_file(string): """ Type check for a valid file for ArgumentParser. """ if not os.path.isfile(string): msg = u'{0} is not a file'.format(string) raise _argparse.ArgumentTypeError(msg) return string def gt_zero(string): """ Type check for int > 0 for ArgumentParser. """ if not int(string) > 0: msg = u'limit must be > 0' raise _argparse.ArgumentTypeError(msg) return int(string) def isodate(string): try: return datetime.strptime(string, '%Y-%m-%d').date() except ValueError: msg = u'date input must in the format of yyyy-mm-dd' raise _argparse.ArgumentTypeError(msg)
from datetime import datetime import argparse import os def is_dir(string): """ Type check for a valid directory for ArgumentParser. """ if not os.path.isdir(string): msg = '{0} is not a directory'.format(string) raise argparse.ArgumentTypeError(msg) return string def is_file(string): """ Type check for a valid file for ArgumentParser. """ if not os.path.isfile(string): msg = u'{0} is not a file'.format(string) raise argparse.ArgumentTypeError(msg) return string def gt_zero(string): """ Type check for int > 0 for ArgumentParser. """ if not int(string) > 0: msg = u'limit must be > 0' raise argparse.ArgumentTypeError(msg) return int(string) def isodate(string): try: return datetime.strptime(string, '%Y-%m-%d').date() except ValueError: msg = u'date input must in the format of yyyy-mm-dd' raise argparse.ArgumentTypeError(msg)
Improve exception logging within Angular.
'use strict'; define(['angular/map/app', 'angular/tags/app', 'angular/status/app'], function(map, tags, status) { map.addListener(function() { console.log('Map module ready.'); console.log('Angular app ready.'); for (var i in listeners) { listeners[i](); } }); var app = angular.module('berlin', ['map', 'tags', 'status']); app.config(['$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(false); }]); app.filter('rawHtml', ['$sce', function($sce) { return function(val) { return $sce.trustAsHtml(val); } }]); // See https://docs.angularjs.org/api/ng/service/$exceptionHandler : app.factory('$exceptionHandler', function() { return function(exception, cause) { console.error(exception.stack ? exception.stack : exception); }; }); // Adds a listener on module readiness. var addListener = function(listener) { listeners.push(listener); }; var listeners = []; return { addListener: addListener, status: status, dbg: map.dbg, }; });
'use strict'; define(['angular/map/app', 'angular/tags/app', 'angular/status/app'], function(map, tags, status) { map.addListener(function() { console.log('Map module ready.'); console.log('Angular app ready.'); for (var i in listeners) { listeners[i](); } }); var app = angular.module('berlin', ['map', 'tags', 'status']); app.config(['$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(false); }]); app.filter('rawHtml', ['$sce', function($sce) { return function(val) { return $sce.trustAsHtml(val); } }]); // Adds a listener on module readiness. var addListener = function(listener) { listeners.push(listener); }; var listeners = []; return { addListener: addListener, status: status, dbg: map.dbg, }; });
Refactor West Berks to use new BaseShpShpImporter
""" Import Wokingham Polling stations """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Wokingham Council """ council_id = 'E06000037' districts_name = 'polling_districts' stations_name = 'polling_places.shp' def district_record_to_dict(self, record): return { 'internal_council_id': record[0], 'name': record[2], } def station_record_to_dict(self, record): return { 'internal_council_id': record[4], 'postcode' : record[5].split(',')[-1], 'address' : "\n".join(record[5].split(',')[:-1]), }
""" Import Wokingham Polling stations """ from data_collection.management.commands import BaseShpImporter, import_polling_station_shapefiles class Command(BaseShpImporter): """ Imports the Polling Station data from Wokingham Council """ council_id = 'E06000037' districts_name = 'polling_districts' stations_name = 'polling_places.shp' def district_record_to_dict(self, record): return { 'internal_council_id': record[0], 'name': record[2], } def station_record_to_dict(self, record): return { 'internal_council_id': record[4], 'postcode' : record[5].split(',')[-1], 'address' : "\n".join(record[5].split(',')[:-1]), } def import_polling_stations(self): import_polling_station_shapefiles(self)
Disable cache properly when logged in. Prevents browser using cache for back button which breaks CSRF protection
<?php namespace BoomCMS\Core\Http\Middleware; use Closure; use BoomCMS\Core\Auth\Auth; class DisableHttpCacheIfLoggedIn { /** * * @var Auth */ protected $auth; public function __construct(Auth $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($this->auth->isLoggedIn()) { $response->header('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'); } return $response; } }
<?php namespace BoomCMS\Core\Http\Middleware; use Closure; use BoomCMS\Core\Auth\Auth; class DisableHttpCacheIfLoggedIn { /** * * @var Auth */ protected $auth; public function __construct(Auth $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($this->auth->isLoggedIn()) { $response->setCache(['private' => true]); } return $response; } }
Add Middleware to serve static assets
var express = require('express'), routes = require(__dirname + '/app/routes.js'), app = express(), port = (process.env.PORT || 3000); // Application settings app.engine('html', require(__dirname + '/lib/template-engine.js').__express); app.set('view engine', 'html'); app.set('vendorViews', __dirname + '/govuk_modules/views'); app.set('views', __dirname + '/app/views'); // Middleware to serve static assets app.use('/public', express.static(__dirname + '/public')); app.use('/public', express.static(__dirname + '/govuk_modules/govuk_template/assets')); app.use('/public', express.static(__dirname + '/govuk_modules/govuk_frontend_toolkit')); app.use(express.json()); // to support JSON-encoded bodies app.use(express.urlencoded()); // to support URL-encoded bodies // send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path="/public/"; next(); }); // routes (found in routes.js) routes.bind(app, '/public/'); // start the app app.listen(port); console.log(''); console.log('Listening on port ' + port); console.log('');
var express = require('express'), routes = require(__dirname + '/app/routes.js'), app = express(), port = (process.env.PORT || 3000); // Application settings app.engine('html', require(__dirname + '/lib/template-engine.js').__express); app.set('view engine', 'html'); app.set('vendorViews', __dirname + '/govuk_modules/views'); app.set('views', __dirname + '/app/views'); // Middleware to serve static assets app.use('/public', express.static(__dirname + '/public')); app.use('/public', express.static(__dirname + '/govuk_modules/public')); app.use(express.json()); // to support JSON-encoded bodies app.use(express.urlencoded()); // to support URL-encoded bodies // send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path="/public/"; next(); }); // routes (found in routes.js) routes.bind(app, '/public/'); // start the app app.listen(port); console.log(''); console.log('Listening on port ' + port); console.log('');
Update package restrictions for clarity and testing
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.md')).read() CHANGES = open(os.path.join(here, 'CHANGES.md')).read() requires = [ 'pycrypto >= 2.6.1', 'pycrypto < 3.0.0', 'requests >= 2.5.1', 'requests < 3.0.0', 'six >= 1.10.0', 'six < 2.0.0', ] setup(name='launchkey-python', version='1.3.0', description='LaunchKey Python SDK', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='LaunchKey', author_email='support@launchkey.com', url='https://launchkey.com', keywords='launchkey security authentication', license='MIT', py_modules=[ 'launchkey', ], zip_safe=False, test_suite='tests', install_requires=requires, tests_require=[ 'Mocker==1.1.1', 'mock==2.0.0', ], )
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.md')).read() CHANGES = open(os.path.join(here, 'CHANGES.md')).read() requires = [ 'pycrypto', 'requests>=2.5.1', 'six', ] setup(name='launchkey-python', version='1.3.0', description='LaunchKey Python SDK', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='LaunchKey', author_email='support@launchkey.com', url='https://launchkey.com', keywords='launchkey security authentication', license='MIT', py_modules=[ 'launchkey', ], zip_safe=False, test_suite='tests', install_requires=requires, tests_require=[ 'Mocker', 'mock', ], )
Add Scene class to SceneScroller object
/* global window */ /** * @module SceneScroller */ 'use strict'; /** * @namespace SceneScroller */ var SceneScroller = {} /** * @property {String} version The version of this SceneScroller distribution. */ SceneScroller.version = require('../package.json').version /** * @property {Class} EventEmitter * @see [EventEmitter](./eventemitter.md) */ SceneScroller.EventEmitter = require('./eventemitter') /** * @property {Class} Node * @see [Node](./node.md) */ SceneScroller.Node = require('./node') /** * @property {Class} Entity * @see [Entity](./entity.md) */ SceneScroller.Entity = require('./entity') /** * @property {Class} Scene * @see [Scene](./scene.md) */ SceneScroller.Scene= require('./scene') /** * @property {Object} symbols * @see [symbols](./symbols.md) */ SceneScroller.symbols = require('./symbols') /** * @property {Object} util * @see [util](./util.md) */ SceneScroller.util = require('./util') module.exports = SceneScroller if(window) { window.SceneScroller = SceneScroller }
/* global window */ /** * @module SceneScroller */ 'use strict'; /** * @namespace SceneScroller */ var SceneScroller = {} /** * @property {String} version The version of this SceneScroller distribution. */ SceneScroller.version = require('../package.json').version /** * @property {Class} EventEmitter * @see [EventEmitter](./eventemitter.md) */ SceneScroller.EventEmitter = require('./eventemitter') /** * @property {Class} Node * @see [Node](./node.md) */ SceneScroller.Node = require('./node') /** * @property {Class} Entity * @see [Entity](./entity.md) */ SceneScroller.Entity = require('./entity') /** * @property {Object} symbols * @see [symbols](./symbols.md) */ SceneScroller.symbols = require('./symbols') /** * @property {Object} util * @see [util](./util.md) */ SceneScroller.util = require('./util') module.exports = SceneScroller if(window) { window.SceneScroller = SceneScroller }
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>
Test of index arrays of type int.
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_equal(link_ids.dtype, np.int) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_equal(link_ids.dtype, np.int) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLOSED_BOUNDARY def test_active_links_ids(): status = np.empty((4, 5), dtype=int) status.fill(CLOSED_BOUNDARY) status[1, 2] = status[1, 3] = status[2, 2] = status[2, 3] = CORE_NODE link_ids = active_link_ids((4, 5), status) assert_array_equal(link_ids, [7, 8, 21, 25]) assert_true(str(link_ids.dtype).startswith('int')) def test_active_links_with_edge_boundaries(): status = status_with_perimeter_as_boundary((3, 4)) link_ids = active_link_ids((3, 4), status) assert_array_equal(link_ids, [1, 2, 5, 6, 11, 12, 13]) assert_true(str(link_ids.dtype).startswith('int')) @raises(ValueError) def test_active_link_ids_with_shape_mismatch(): active_link_ids((3, 4), np.zeros(3))
Add more flexibity to run tests independantly
#!/usr/bin/env python import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'td_biblio', ), ROOT_URLCONF='td_biblio.urls', SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', ) from django.test.utils import get_runner def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests([ 'td_biblio.tests.test_commands', 'td_biblio.tests.test_factories', 'td_biblio.tests.test_models', 'td_biblio.tests.test_views', ]) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'td_biblio', ), ROOT_URLCONF='td_biblio.urls', SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', ) from django.test.utils import get_runner def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(['td_biblio', ]) sys.exit(failures) if __name__ == '__main__': runtests()
Make the panel slightly taller.
var { ToggleButton } = require('sdk/ui/button/toggle'); var tabs = require("sdk/tabs"); var button = ToggleButton({ id: "tweet-that", label: "Tweet that link", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onClick: handleClick }); var panel = require("sdk/panel").Panel({ width: 320, height: 270, onHide: function() { button.state('window', {checked: false}); } }); function handleClick(state) { var twitter_uri = "https://twitter.com/intent/tweet?url=" + encodeURIComponent(tabs.activeTab.url) + "&text=" + encodeURIComponent(tabs.activeTab.title); panel.contentURL = twitter_uri; panel.show({ position: button }); }
var { ToggleButton } = require('sdk/ui/button/toggle'); var tabs = require("sdk/tabs"); var button = ToggleButton({ id: "tweet-that", label: "Tweet that link", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onClick: handleClick }); var panel = require("sdk/panel").Panel({ width: 320, height: 250, onHide: function() { button.state('window', {checked: false}); } }); function handleClick(state) { var twitter_uri = "https://twitter.com/intent/tweet?url=" + encodeURIComponent(tabs.activeTab.url) + "&text=" + encodeURIComponent(tabs.activeTab.title); panel.contentURL = twitter_uri; panel.show({ position: button }); }
Add custom error code: NO_RESET_METHODS
export const HTTP_ERROR_CODES = { ABORTED: -1, TIMEOUT: 0, UNPROCESSABLE_ENTITY: 422, UNAUTHORIZED: 401, UNLOCK: 403, TOO_MANY_REQUESTS: 429, }; export const API_CUSTOM_ERROR_CODES = { APP_VERSION_BAD: 5003, HUMAN_VERIFICATION_REQUIRED: 9001, AUTH_ACCOUNT_DISABLED: 10003, TOKEN_INVALID: 12087, KEY_GET_INPUT_INVALID: 33101, KEY_GET_ADDRESS_MISSING: 33102, KEY_GET_DOMAIN_MISSING_MX: 33103, INCOMING_DEFAULT_UPDATE_NOT_EXIST: 35023, USER_EXISTS_USERNAME_ALREADY_USED: 12106, NO_RESET_METHODS: 2029, }; export const EVENT_ERRORS = { MAIL: 1, CONTACTS: 2, };
export const HTTP_ERROR_CODES = { ABORTED: -1, TIMEOUT: 0, UNPROCESSABLE_ENTITY: 422, UNAUTHORIZED: 401, UNLOCK: 403, TOO_MANY_REQUESTS: 429, }; export const API_CUSTOM_ERROR_CODES = { APP_VERSION_BAD: 5003, HUMAN_VERIFICATION_REQUIRED: 9001, AUTH_ACCOUNT_DISABLED: 10003, TOKEN_INVALID: 12087, KEY_GET_INPUT_INVALID: 33101, KEY_GET_ADDRESS_MISSING: 33102, KEY_GET_DOMAIN_MISSING_MX: 33103, INCOMING_DEFAULT_UPDATE_NOT_EXIST: 35023, USER_EXISTS_USERNAME_ALREADY_USED: 12106, }; export const EVENT_ERRORS = { MAIL: 1, CONTACTS: 2, };
Add details to the query ARGB_8888
package paprika.neo4j; import org.neo4j.cypher.CypherException; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.Transaction; import java.io.IOException; /** * Created by antonin on 16-05-03. */ public class ARGB8888Query extends Query { private ARGB8888Query(QueryEngine queryEngine) { super(queryEngine); } public static ARGB8888Query createARGB8888Query(QueryEngine queryEngine) { return new ARGB8888Query(queryEngine); } @Override public void execute(boolean details) throws CypherException, IOException { try (Transaction ignored = graphDatabaseService.beginTx()) { String query = "MATCH (e: ExternalArgument) WHERE HAS(e.is_argb_8888) RETURN e"; if (details) { query += ", count(e) as ARGB8888"; } Result result = graphDatabaseService.execute(query); queryEngine.resultToCSV(result, "_ARGB8888.csv"); } } }
package paprika.neo4j; import org.neo4j.cypher.CypherException; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.Transaction; import java.io.IOException; /** * Created by antonin on 16-05-03. */ public class ARGB8888Query extends Query { private ARGB8888Query(QueryEngine queryEngine) { super(queryEngine); } public static ARGB8888Query createARGB8888Query(QueryEngine queryEngine) { return new ARGB8888Query(queryEngine); } @Override public void execute(boolean details) throws CypherException, IOException { try (Transaction ignored = graphDatabaseService.beginTx()) { String query = "MATCH (e: ExternalArgument) WHERE HAS(e.is_argb_8888) RETURN e, count(e) as ARGB8888"; Result result = graphDatabaseService.execute(query); queryEngine.resultToCSV(result, "_ARGB8888.csv"); } } }
Fix task path for cleanup
import os from datetime import timedelta BROKER_URL = os.environ['CELERY_BROKER_URL'] CELERY_IMPORTS = ('cabot.cabotapp.tasks', ) CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERYD_TASK_SOFT_TIME_LIMIT = 120 CELERYD_TASK_TIME_LIMIT = 150 CELERYBEAT_SCHEDULE = { 'run-all-checks': { 'task': 'cabot.cabotapp.tasks.run_all_checks', 'schedule': timedelta(seconds=60), }, 'update-shifts': { 'task': 'cabot.cabotapp.tasks.update_shifts', 'schedule': timedelta(seconds=1800), }, 'clean-db': { 'task': 'cabot.cabotapp.tasks.clean_db', 'schedule': timedelta(seconds=60*60*24), }, } CELERY_TIMEZONE = 'UTC'
import os from datetime import timedelta BROKER_URL = os.environ['CELERY_BROKER_URL'] CELERY_IMPORTS = ('cabot.cabotapp.tasks', ) CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERYD_TASK_SOFT_TIME_LIMIT = 120 CELERYD_TASK_TIME_LIMIT = 150 CELERYBEAT_SCHEDULE = { 'run-all-checks': { 'task': 'cabot.cabotapp.tasks.run_all_checks', 'schedule': timedelta(seconds=60), }, 'update-shifts': { 'task': 'cabot.cabotapp.tasks.update_shifts', 'schedule': timedelta(seconds=1800), }, 'clean-db': { 'task': 'app.cabotapp.tasks.clean_db', 'schedule': timedelta(seconds=60*60*24), }, } CELERY_TIMEZONE = 'UTC'
Update component if spacing has been changed
var Extend = require('../utils/extend'); var Types = { LIGHT: require('./themes/light-theme'), DARK: require('./themes/dark-theme') }; var ThemeManager = function() { return { types: Types, template: Types.LIGHT, spacing: Types.LIGHT.spacing, contentFontFamily: 'Roboto, sans-serif', palette: Types.LIGHT.getPalette(), component: Types.LIGHT.getComponentThemes(Types.LIGHT.getPalette()), getCurrentTheme: function() { return this; }, // Component gets updated to reflect palette changes. setTheme: function(newTheme) { this.setSpacing(newTheme.spacing); this.setPalette(newTheme.getPalette()); this.setComponentThemes(newTheme.getComponentThemes(newTheme.getPalette())); }, setSpacing: function setSpacing(newSpacing) { this.spacing = Extend(this.spacing, newSpacing); this.component = Extend(this.component, this.template.getComponentThemes(this.palette, this.spacing)); }, setPalette: function(newPalette) { this.palette = Extend(this.palette, newPalette); this.component = Extend(this.component, this.template.getComponentThemes(this.palette)); }, setComponentThemes: function(overrides) { this.component = Extend(this.component, overrides); } }; }; module.exports = ThemeManager;
var Extend = require('../utils/extend'); var Types = { LIGHT: require('./themes/light-theme'), DARK: require('./themes/dark-theme') }; var ThemeManager = function() { return { types: Types, template: Types.LIGHT, spacing: Types.LIGHT.spacing, contentFontFamily: 'Roboto, sans-serif', palette: Types.LIGHT.getPalette(), component: Types.LIGHT.getComponentThemes(Types.LIGHT.getPalette()), getCurrentTheme: function() { return this; }, // Component gets updated to reflect palette changes. setTheme: function(newTheme) { this.setSpacing(newTheme.spacing); this.setPalette(newTheme.getPalette()); this.setComponentThemes(newTheme.getComponentThemes(newTheme.getPalette())); }, setSpacing: function setSpacing(newSpacing) { this.spacing = Extend(this.spacing, newSpacing); }, setPalette: function(newPalette) { this.palette = Extend(this.palette, newPalette); this.component = Extend( this.component, this.template.getComponentThemes(this.palette, this.spacing) ); }, setComponentThemes: function(overrides) { this.component = Extend(this.component, overrides); } }; }; module.exports = ThemeManager;
Add attr.gpu decorator to gpu test of dropout
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import testing from chainer.testing import attr if cuda.available: cuda.init() class TestDropout(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32) def check_type_forward(self, x_data): x = chainer.Variable(x_data) try: functions.dropout(x) except Exception: self.fail() def test_type_forward_cpu(self): self.check_type_forward(self.x) @attr.gpu def test_type_forward_gpu(self): self.check_type_forward(cuda.to_gpu(self.x)) testing.run_module(__name__, __file__)
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import testing if cuda.available: cuda.init() class TestDropout(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32) def check_type_forward(self, x_data): x = chainer.Variable(x_data) try: functions.dropout(x) except Exception: self.fail() def test_type_forward_cpu(self): self.check_type_forward(self.x) def test_type_forward_gpu(self): self.check_type_forward(cuda.to_gpu(self.x)) testing.run_module(__name__, __file__)
Update grunt setup to compile JSX properly
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), babel: { options: { sourceMap: true, presets: ['es2015', 'react'] }, dist: { files: [ { expand: true, cwd: 'ui/js', src: ['*.js', '*.jsx'], ext: '.js', dest: 'ui/' } ] } }, watch: { scripts: { files: ['**/*.jsx'], tasks: ['babel'], options: { spawn: false, }, }, } }); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('load-grunt-tasks'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['babel']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), babel: { options: { sourceMap: true, presets: ['es2015', 'react'] }, dist: { files: [ { expand: true, cwd: 'ui/js', src: ['*.js'], ext: '.js', dest: 'ui/' } ] } }, watch: { scripts: { files: ['**/*.jsx'], tasks: ['babel'], options: { spawn: false, }, }, } }); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('load-grunt-tasks'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['babel']); };
Add test for wildcard search
package nl.orangeflamingo.controller; import nl.orangeflamingo.domain.Song; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest public class SongControllerTest { @Autowired private SongController songController; @Test public void testFindSongsByArtist() { List<Song> songsByArtist = songController.findSongsByArtist("Dolly Parton"); assertEquals(1, songsByArtist.size()); } @Test public void testFindSongsByTitle() { List<Song> songsByTitle = songController.findSongsByTitle("Jolene"); assertEquals(1, songsByTitle.size()); } @Test public void testFindSongsByQuery() { List<Song> songsByQuery = songController.findSongsByQuery("olly"); assertEquals(2, songsByQuery.size()); } @Test public void testFindSongsByPage() { Page<Song> songsByPage = songController.findSongsByPage(0, 1); assertEquals(1, songsByPage.getSize()); } }
package nl.orangeflamingo.controller; import nl.orangeflamingo.domain.Song; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest public class SongControllerTest { @Autowired private SongController songController; @Test public void testFindSongsByArtist() { List<Song> songsByArtist = songController.findSongsByArtist("Dolly Parton"); assertEquals(1, songsByArtist.size()); } @Test public void testFindSongsByTitle() { List<Song> songsByTitle = songController.findSongsByTitle("Jolene"); assertEquals(1, songsByTitle.size()); } @Test public void testFindSongsByPage() { Page<Song> songsByPage = songController.findSongsByPage(0, 1); assertEquals(1, songsByPage.getSize()); } }
Replace lodash with native calls, part 1
// Static file handler. Serves all of the files from `public/root` directory // under the main application root path. 'use strict'; const path = require('path'); const send = require('send'); const stream = require('stream'); module.exports = function (N) { let root = path.join(__dirname, '../../../../static'); N.validate('server_bin:nodeca-site.static', { // DON'T validate unknown params - those can exists, // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/ additionalProperties: true, properties: { path: { type: 'string', required: true } } }); N.wire.on('server_bin:nodeca-site.static', async function static_file_send(env) { let req = env.origin.req, res = env.origin.res; if (req.method !== 'GET' && req.method !== 'HEAD') throw N.io.BAD_REQUEST; await new Promise((resolve, reject) => { let ss = send(req, env.params.path, { root, index: false, maxAge: '1y' }); // Errors with status are not fatal, // rethrow those up as code, not as Error ss.on('error', err => reject(err.status || err)); stream.finished(res, () => { if (res.statusCode) env.status = res.statusCode; resolve(); }); ss.pipe(res); }); }); };
// Static file handler. Serves all of the files from `public/root` directory // under the main application root path. 'use strict'; const path = require('path'); const send = require('send'); const stream = require('stream'); module.exports = function (N) { var root = path.join(__dirname, '../../../../static'); N.validate('server_bin:nodeca-site.static', { // DON'T validate unknown params - those can exists, // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/ additionalProperties: true, properties: { path: { type: 'string', required: true } } }); N.wire.on('server_bin:nodeca-site.static', async function static_file_send(env) { var req = env.origin.req, res = env.origin.res; if (req.method !== 'GET' && req.method !== 'HEAD') throw N.io.BAD_REQUEST; await new Promise((resolve, reject) => { let ss = send(req, env.params.path, { root, index: false, maxAge: '1y' }); // Errors with status are not fatal, // rethrow those up as code, not as Error ss.on('error', err => reject(err.status || err)); stream.finished(res, () => { if (res.statusCode) env.status = res.statusCode; resolve(); }); ss.pipe(res); }); }); };
Call addControl instead of passing map to control
goog.require('ol.Map'); goog.require('ol.View2D'); goog.require('ol.control.ZoomSlider'); goog.require('ol.layer.TileLayer'); goog.require('ol.source.MapQuestOpenAerial'); /** * Helper method for map-creation. * * @param {string} divId The id of the div for the map. * @return {ol.Map} The ol.Map instance. */ var createMap = function(divId) { var source, layer, map, zoomslider, resolutions; source = new ol.source.MapQuestOpenAerial(); layer = new ol.layer.TileLayer({ source: source }); map = new ol.Map({ layers: [layer], target: divId, view: new ol.View2D({ center: [0, 0], zoom: 2 }) }); zoomslider = new ol.control.ZoomSlider(); map.addControl(zoomslider); return map; }; var map1 = createMap('map1'); var map2 = createMap('map2'); var map3 = createMap('map3');
goog.require('ol.Map'); goog.require('ol.View2D'); goog.require('ol.control.ZoomSlider'); goog.require('ol.layer.TileLayer'); goog.require('ol.source.MapQuestOpenAerial'); /** * Helper method for map-creation. * * @param {string} divId The id of the div for the map. * @return {ol.Map} The ol.Map instance. */ var createMap = function(divId) { var source, layer, map, zoomslider, resolutions; source = new ol.source.MapQuestOpenAerial(); layer = new ol.layer.TileLayer({ source: source }); map = new ol.Map({ layers: [layer], target: divId, view: new ol.View2D({ center: [0, 0], zoom: 2 }) }); zoomslider = new ol.control.ZoomSlider({ map: map }); return map; }; var map1 = createMap('map1'); var map2 = createMap('map2'); var map3 = createMap('map3');
Make sure the bundle can work without DoctrineBundle
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\GeneratorBundle\Command; use Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; abstract class GenerateDoctrineCommand extends ContainerAwareCommand { public function isEnabled() { return class_exists('Doctrine\\Bundle\\DoctrineBundle\\DoctrineBundle'); } protected function parseShortcutNotation($shortcut) { $entity = str_replace('/', '\\', $shortcut); if (false === $pos = strpos($entity, ':')) { throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity)); } return array(substr($entity, 0, $pos), substr($entity, $pos + 1)); } protected function getEntityMetadata($entity) { $factory = new MetadataFactory($this->getContainer()->get('doctrine')); return $factory->getClassMetadata($entity)->getMetadata(); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\GeneratorBundle\Command; use Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory; use Doctrine\Bundle\DoctrineBundle\Command\DoctrineCommand; abstract class GenerateDoctrineCommand extends DoctrineCommand { protected function parseShortcutNotation($shortcut) { $entity = str_replace('/', '\\', $shortcut); if (false === $pos = strpos($entity, ':')) { throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity)); } return array(substr($entity, 0, $pos), substr($entity, $pos + 1)); } protected function getEntityMetadata($entity) { $factory = new MetadataFactory($this->getContainer()->get('doctrine')); return $factory->getClassMetadata($entity)->getMetadata(); } }
Set the version name for the default branch to mercurial so we can tell when we run from the repository
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = 'mercurial' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = '0.10' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
Remove superfluous check for None baggage
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage or opentracing.SpanContext.EMPTY_BAGGAGE def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
Make sure all tests pass for Travis
/** * * Application or Website name * * Copyright 2015, Author Name * Some information on the license. * * Tests > Unit > Sample * * Jasmine test examples: http://evanhahn.com/how-do-i-jasmine/ * **/ /* ======================================================== */ /* Libraries /* ======================================================== */ // Import libraries needed to perform this test. window.$ = require('jquery'); /* ======================================================== */ /* Data /* ======================================================== */ // Define function. var helloWorld = function(){ return 'Hello world!'; } // Get module. // var Module = require('../../src/dist/js/public/module.sample'); /* ======================================================== */ /* Tests /* ======================================================== */ // Suite. describe('Hello world', function(){ // Spec. it('says hello', function(){ expect(helloWorld()).toEqual('Hello world!'); }); // Spec. it('says hello', function(){ expect(helloWorld()).toNotEqual('Hi!'); }); // Spec. it('says world', function(){ expect(helloWorld()).toContain('world'); }); // Spec. // it('says close', function(){ // expect(Module.test()).toEqual('close'); // }); });
/** * * Application or Website name * * Copyright 2015, Author Name * Some information on the license. * * Tests > Unit > Sample * * Jasmine test examples: http://evanhahn.com/how-do-i-jasmine/ * **/ /* ======================================================== */ /* Libraries /* ======================================================== */ // Import libraries needed to perform this test. window.$ = require('jquery'); /* ======================================================== */ /* Data /* ======================================================== */ // Define function. var helloWorld = function(){ return 'Hello world!'; } // Get module. // var Module = require('../../src/dist/js/public/module.sample'); /* ======================================================== */ /* Tests /* ======================================================== */ // Suite. describe('Hello world', function(){ // Spec. it('says hello', function(){ expect(helloWorld()).toEqual('Hello world!'); }); // Spec. it('says hello', function(){ expect(helloWorld()).toEqual('Hellox world!'); }); // Spec. it('says world', function(){ expect(helloWorld()).toContain('world'); }); // Spec. // it('says close', function(){ // expect(Module.test()).toEqual('close'); // }); });
Throw errors that cause a redirect to make debugging easier
import Ember from 'ember'; const { Controller, computed, inject, run, observer } = Ember; export default Controller.extend({ config: inject.service(), error: null, errorStr: computed('error', function() { return this.get('error').toString(); }), errorCodes: computed('error', function() { const error = this.get('error'); const codes = [error.code]; if (error.errors) { error.errors.forEach(err => { codes.push(err.status); }); } return codes .compact() .uniq() .map(code => '' + code); }), is404: computed('errorCodes.[]', function() { return this.get('errorCodes').includes('404'); }), is500: computed('errorCodes.[]', function() { return this.get('errorCodes').includes('500'); }), throwError: observer('error', function() { if (this.get('config.isDev')) { run.next(() => { throw this.get('error'); }); } }), });
import Ember from 'ember'; const { Controller, computed } = Ember; export default Controller.extend({ error: null, errorStr: computed('error', function() { return this.get('error').toString(); }), errorCodes: computed('error', function() { const error = this.get('error'); const codes = [error.code]; if (error.errors) { error.errors.forEach(err => { codes.push(err.status); }); } return codes .compact() .uniq() .map(code => '' + code); }), is404: computed('errorCodes.[]', function() { return this.get('errorCodes').includes('404'); }), is500: computed('errorCodes.[]', function() { return this.get('errorCodes').includes('500'); }), });
Add getPlane-method. Returns the plane which the ant moves on Add getAnt-method. Returns the position of the ant Remove main-method
package langton; import java.awt.Point; import java.util.HashMap; public class LangtonsAnt { private final Point[] directions = { new Point(1, 0), new Point(0, 1), new Point(-1, 0), new Point(0, -1) }; private Point ant; // The ant's position private int direction = 0; // The ant's direction private HashMap<Point, Boolean> plane; // The plane which the ant moves on public LangtonsAnt() { // Create a new Map to hold coordinates for ant plane = new HashMap<Point, Boolean>(); } public Point getAnt() { return ant; } public HashMap<Point, Boolean> getPlane() { return plane; } public void step() { // If the ant is on a black square if (plane.get(ant)) { direction = (direction - 1) % 4; plane.put(ant, false); } else // If the ant is on a white spot { direction = (direction + 1) % 4; plane.put(ant, true); } ant.translate(directions[direction].x, directions[direction].y); } }
package langton; import java.awt.Point; import java.util.HashMap; public class LangtonsAnt { private final Point[] directions = { new Point(1, 0), new Point(0, 1), new Point(-1, 0), new Point(0, -1) }; private Point ant; // The ant's position private int direction = 0; // The ant's direction private HashMap<Point, Boolean> field; // The field which the ant moves on public LangtonsAnt() { // Create a new Map to hold coordinates for ant field = new HashMap<Point, Boolean>(); } public void step() { // If the ant is on a black square if (field.get(ant)) { direction = (direction - 1) % 4; field.put(ant, false); } else // If the ant is on a white spot { direction = (direction + 1) % 4; field.put(ant, true); } ant.translate(directions[direction].x, directions[direction].y); } public static void main(String[] args) { } }
Set currentUser to req.user before redirecting after login
const express = require('express'), router = express.Router(), passport = require('passport'), User = require('../models/user'); router.get('/', function(req, res, next) { res.redirect('/user'); }); // AUTH ROUTES // sign up router.get('/new', function(req, res, next) { res.render('users/new'); }); router.post('/', function(req, res, next) { var newUser = new User({username: req.body.username}); User.register(newUser, req.body.password, function(err, user) { if (err) { console.log(err); return res.render('users/new'); } passport.authenticate('local')(req, res, function() { res.redirect('/user/'); }); }); }); // log in router.get('/login', function(req, res, next) { res.render('users/login'); }); router.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), (req, res) => { res.locals.currentUser = req.user; res.redirect(`/user/${req.user.username}/collection`); } ); // log out router.get('/logout', function(req, res, next) { req.logout(); res.redirect('/'); }); function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/user/login'); } module.exports = router;
const express = require('express'), router = express.Router(), passport = require('passport'), User = require('../models/user'); router.get('/', function(req, res, next) { res.redirect('/user'); }); // AUTH ROUTES // sign up router.get('/new', function(req, res, next) { res.render('users/new'); }); router.post('/', function(req, res, next) { var newUser = new User({username: req.body.username}); User.register(newUser, req.body.password, function(err, user) { if (err) { console.log(err); return res.render('users/new'); } passport.authenticate('local')(req, res, function() { res.redirect('/user/'); }); }); }); // log in router.get('/login', function(req, res, next) { res.render('users/login'); }); router.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), (req, res) => { // res.locals.currentUser = req.user; res.redirect(`/user/${req.user.username}/collection`); } ); // log out router.get('/logout', function(req, res, next) { req.logout(); res.redirect('/'); }); function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/user/login'); } module.exports = router;
Use shlex to split parameters
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os import shlex from ..quokka import ExternalProcess, PluginException class ConsoleApplication(ExternalProcess): def __init__(self, conf): super(ConsoleApplication, self).__init__() self.quokka = conf.quokka self.plugin = conf.plugin_kargs def start(self): binary = self.plugin['binary'] if not binary or not os.path.exists(binary): raise PluginException('%s not found.' % binary) params = self.plugin['params'] environ = self.set_environ(self.quokka['environ']) cmd = [binary] if params: cmd.extend(shlex.split(params)) self.process = self.open(cmd, environ)
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os from ..quokka import ExternalProcess, PluginException class ConsoleApplication(ExternalProcess): def __init__(self, conf): super(ConsoleApplication, self).__init__() self.quokka = conf.quokka self.plugin = conf.plugin_kargs def start(self): binary = self.plugin['binary'] if not binary or not os.path.exists(binary): raise PluginException('%s not found.' % binary) params = self.plugin['params'] environ = self.set_environ(self.quokka['environ']) cmd = [binary] if params: cmd.append(params) self.process = self.open(cmd, environ)
Select first network interface IP for localAddress display
var express = require('express'); var os = require('os'); var router = express.Router(); var ifaces = os.networkInterfaces(); var localAddress = ''; var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development'; var environmentNotice = environment === 'production' ? '' : environment + ' environment'; Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false || localAddress !== '') { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } localAddress = iface.address; }); }); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Accumulator', environment: environment, environmentNotice: environmentNotice, localAddress: localAddress }); }); module.exports = router;
var express = require('express'); var os = require('os'); var router = express.Router(); var ifaces = os.networkInterfaces(); var localAddress = ''; var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development'; var environmentNotice = environment === 'production' ? '' : environment + ' environment'; Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } localAddress = iface.address; }); }); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Accumulator', environment: environment, environmentNotice: environmentNotice, localAddress: localAddress }); }); module.exports = router;
Add sharingSettings to the modules datastore.
/** * `core/modules` data store * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import settingsPanel from './settings-panel'; import settings from './settings'; import modules from './modules'; import sharingSettings from './sharing-settings'; import { createErrorStore } from '../../data/create-error-store'; import { CORE_MODULES } from './constants'; const store = Data.combineStores( Data.commonStore, modules, createErrorStore(), settingsPanel, settings, sharingSettings ); export const initialState = store.initialState; export const actions = store.actions; export const controls = store.controls; export const reducer = store.reducer; export const resolvers = store.resolvers; export const selectors = store.selectors; export const registerStore = ( registry ) => { registry.registerStore( CORE_MODULES, store ); }; export default store;
/** * `core/modules` data store * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import settingsPanel from './settings-panel'; import settings from './settings'; import modules from './modules'; import { createErrorStore } from '../../data/create-error-store'; import { CORE_MODULES } from './constants'; const store = Data.combineStores( Data.commonStore, modules, createErrorStore(), settingsPanel, settings ); export const initialState = store.initialState; export const actions = store.actions; export const controls = store.controls; export const reducer = store.reducer; export const resolvers = store.resolvers; export const selectors = store.selectors; export const registerStore = ( registry ) => { registry.registerStore( CORE_MODULES, store ); }; export default store;
Change how method is exported.
const fs = require('fs'); const path = require('path'); /** * Finds package.json file from either the directory the script was called from or a supplied path. * * console.log(findPackageFileInPath()); * console.log(findPackageFileInPath('./package.json')); * console.log(findPackageFileInPath('~/git/github/doxdox/')); * * @param {String} [input] Directory or file. * @return {String} Path to package.json file. * @public */ const findPackageFileInPath = input => { if (!input) { input = process.cwd(); } if (fs.existsSync(input)) { const stat = fs.statSync(input); if (stat.isDirectory()) { return path.resolve(path.join(input, '/package.json')); } else if (stat.isFile()) { return path.resolve(path.join(path.dirname(input), '/package.json')); } } return null; }; module.exports = { findPackageFileInPath };
const fs = require('fs'); const path = require('path'); /** * Finds package.json file from either the directory the script was called from or a supplied path. * * console.log(findPackageFileInPath()); * console.log(findPackageFileInPath('./package.json')); * console.log(findPackageFileInPath('~/git/github/doxdox/')); * * @param {String} [input] Directory or file. * @return {String} Path to package.json file. * @public */ module.exports.findPackageFileInPath = input => { if (!input) { input = process.cwd(); } if (fs.existsSync(input)) { const stat = fs.statSync(input); if (stat.isDirectory()) { return path.resolve(path.join(input, '/package.json')); } else if (stat.isFile()) { return path.resolve(path.join(path.dirname(input), '/package.json')); } } return null; };
Test folder prefix separator should only be added to the path if prefix is not empty
package hu.bme.mit.codemodel.rifle.visualization; import java.io.File; public abstract class TestCase { protected static final String branchId = "dummyTestExport"; protected static final String sessionId = "dummyTestExport"; protected String testFolderPrefix = ""; protected String getTestResourcesFolderPath(String testMethodName) { try { String testResourceFolderWithinResources = this.getClass().getSimpleName() + File.separator + testMethodName; if (!this.testFolderPrefix.equals("")) { testResourceFolderWithinResources = this.testFolderPrefix + File.separator + testResourceFolderWithinResources; } String path = this.getClass().getClassLoader().getResource(testResourceFolderWithinResources).getPath(); return path; } catch (NullPointerException e) { e.printStackTrace(); return null; } } }
package hu.bme.mit.codemodel.rifle.visualization; import java.io.File; public abstract class TestCase { protected static final String branchId = "dummyTestExport"; protected static final String sessionId = "dummyTestExport"; protected String testFolderPrefix = ""; protected String getTestResourcesFolderPath(String testMethodName) { try { String testResourceFolderWithinResources = this.testFolderPrefix + File.separator + this.getClass().getSimpleName() + File.separator + testMethodName; String path = this.getClass().getClassLoader().getResource(testResourceFolderWithinResources).getPath(); return path; } catch (NullPointerException e) { e.printStackTrace(); return null; } } }
Remove import for type annotation
import datadog as dd class DataDogNotifier(object): def __init__(self, key, deploy_context): # type: (DeployContext) -> None super(DataDogNotifier, self).__init__() self.deploy_context = deploy_context dd.initialize(api_key=key) def notify_event(self, title, type, message): dd.api.Event.create(title=title, text=message, alert_type=type, tags=self._get_tags()) def _get_tags(self): return ['application:{app},role:{role},environment:{env}'.format( app=self.deploy_context.application, role=self.deploy_context.role, env=self.deploy_context.environment)]
from infra_buddy.context.deploy_ctx import DeployContext import datadog as dd class DataDogNotifier(object): def __init__(self, key, deploy_context): # type: (DeployContext) -> None super(DataDogNotifier, self).__init__() self.deploy_context = deploy_context dd.initialize(api_key=key) def notify_event(self, title, type, message): dd.api.Event.create(title=title, text=message, alert_type=type, tags=self._get_tags()) def _get_tags(self): return ['application:{app},role:{role},environment:{env}'.format( app=self.deploy_context.application, role=self.deploy_context.role, env=self.deploy_context.environment)]
Fix rename of `TracerImage` to `TraceImage`
package grayt import ( "image/png" "log" "os" ) // Runner is a convenience struct to help run grayt from a main() function. type Runner struct { PxWide, PxHigh int BaseName string Quality float64 } func NewRunner() *Runner { return &Runner{ PxWide: 640, PxHigh: 480, BaseName: "default", Quality: 10, } } func (r *Runner) Run(scene Scene) { world := newWorld(scene.Entities) acc := newAccumulator(r.PxWide, r.PxHigh) for i := 0; i < int(r.Quality); i++ { log.Print(i) TraceImage(scene.Camera, world, acc) } img := acc.toImage(1.0) // XXX should be configurable f, err := os.Create(r.BaseName + ".png") r.checkErr(err) defer f.Close() err = png.Encode(f, img) r.checkErr(err) } func (r *Runner) checkErr(err error) { if err != nil { log.Fatal("Fatal: ", err) } }
package grayt import ( "image/png" "log" "os" ) // Runner is a convenience struct to help run grayt from a main() function. type Runner struct { PxWide, PxHigh int BaseName string Quality float64 } func NewRunner() *Runner { return &Runner{ PxWide: 640, PxHigh: 480, BaseName: "default", Quality: 10, } } func (r *Runner) Run(scene Scene) { world := newWorld(scene.Entities) acc := newAccumulator(r.PxWide, r.PxHigh) for i := 0; i < int(r.Quality); i++ { log.Print(i) TracerImage(scene.Camera, world, acc) } img := acc.toImage(1.0) // XXX should be configurable f, err := os.Create(r.BaseName + ".png") r.checkErr(err) defer f.Close() err = png.Encode(f, img) r.checkErr(err) } func (r *Runner) checkErr(err error) { if err != nil { log.Fatal("Fatal: ", err) } }
FIX windows BS paths containing a slash in the freaking wrong direction, total BS
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import { configure } from '@storybook/react'; import { setOptions } from '@storybook/addon-options'; import 'react-chromatic/storybook-addon'; import addHeadWarning from './head-warning'; addHeadWarning('Preview'); setOptions({ hierarchySeparator: /\/|\.|\\/, hierarchyRootSeparator: /\|/, }); function loadStories() { let req; req = require.context('../../lib/ui/src', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); req = require.context('../../lib/components/src', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); req = require.context('./stories', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import { configure } from '@storybook/react'; import { setOptions } from '@storybook/addon-options'; import 'react-chromatic/storybook-addon'; import addHeadWarning from './head-warning'; addHeadWarning('Preview'); setOptions({ hierarchySeparator: /\/|\./, hierarchyRootSeparator: /\|/, }); function loadStories() { let req; req = require.context('../../lib/ui/src', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); req = require.context('../../lib/components/src', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); req = require.context('./stories', true, /\.stories\.js$/); req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
Change export format name to mzmine
/* * Copyright (c) 2004-2022 The MZmine Development Team * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package io.github.mzmine.modules.io.spectraldbsubmit.batch; public enum SpectralLibraryExportFormats { json, msp; @Override public String toString() { return switch (this) { case json -> "MZmine json (recommended)"; case msp -> "NIST msp"; }; } public String getExtension() { return switch (this) { case json -> "json"; case msp -> "msp"; }; } }
/* * Copyright 2006-2022 The MZmine Development Team * * This file is part of MZmine. * * MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.io.spectraldbsubmit.batch; public enum SpectralLibraryExportFormats { json, msp; @Override public String toString() { return switch (this) { case json -> "GNPS json (recommended)"; case msp -> "NIST msp"; }; } public String getExtension() { return switch (this) { case json -> "json"; case msp -> "msp"; }; } }
Mark Log4j 2.15 as vulnerable Follows publication of https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45046 Issue #19300
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.logging.util; /** * This class contains references to log4j-core which had a critical vulnerability, * see <a url="https://nvd.nist.gov/vuln/detail/CVE-2021-44228">CVE-2021-44228</a>. */ public class Log4jBannedVersion { public static final String LOG4J2_CORE_COORDINATES = "org.apache.logging.log4j:log4j-core"; public static final String LOG4J2_CORE_VULNERABLE_VERSION_RANGE = "[2.0, 2.16)"; public static final String LOG4J2_CORE_REQUIRED_VERSION = "2.16.0"; }
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.logging.util; /** * This class contains references to log4j-core which had a critical vulnerability, * see <a url="https://nvd.nist.gov/vuln/detail/CVE-2021-44228">CVE-2021-44228</a>. */ public class Log4jBannedVersion { public static final String LOG4J2_CORE_COORDINATES = "org.apache.logging.log4j:log4j-core"; public static final String LOG4J2_CORE_VULNERABLE_VERSION_RANGE = "[2.0, 2.15["; public static final String LOG4J2_CORE_REQUIRED_VERSION = "2.16.0"; }
Add previously undeclared PyObjC Quartz dependency.
# -*- coding: utf-8 -*- from setuptools import setup with open('README.rst', 'r') as f: long_desc = f.read().decode('utf-8') setup(name='dmgbuild', version='1.0.0', description='Mac OS X command line utility to build disk images', long_description=long_desc, author='Alastair Houghton', author_email='alastair@alastairs-place.net', url='http://alastairs-place.net/projects/dmgbuild', license='MIT License', platforms='darwin', packages=['dmgbuild'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Topic :: Desktop Environment', ], package_data = { 'dmgbuild': ['resources/*'] }, scripts=['scripts/dmgbuild'], install_requires=['ds_store >= 1.0.1', 'mac_alias >= 1.0.0', 'six >= 1.4.1', 'pyobjc-framework-Quartz >= 3.0.4'], provides=['dmgbuild'] )
# -*- coding: utf-8 -*- from setuptools import setup with open('README.rst', 'r') as f: long_desc = f.read().decode('utf-8') setup(name='dmgbuild', version='1.0.0', description='Mac OS X command line utility to build disk images', long_description=long_desc, author='Alastair Houghton', author_email='alastair@alastairs-place.net', url='http://alastairs-place.net/projects/dmgbuild', license='MIT License', platforms='darwin', packages=['dmgbuild'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Topic :: Desktop Environment', ], package_data = { 'dmgbuild': ['resources/*'] }, scripts=['scripts/dmgbuild'], install_requires=['ds_store >= 1.0.1', 'mac_alias >= 1.0.0', 'six >= 1.4.1'], provides=['dmgbuild'] )
Fix for empty file when writing cache
<?php namespace Grav\Common\Twig; use Grav\Common\GravTrait; /** * A trait to add some custom processing to the identifyLink() method in Parsedown and ParsedownExtra */ trait WriteCacheFileTrait { use GravTrait; protected static $umask; /** * This exists so template cache files use the same * group between apache and cli * * @param $file * @param $content */ protected function writeCacheFile($file, $content) { if (empty($file)) { return; } if (!isset(self::$umask)) { self::$umask = self::getGrav()['config']->get('system.twig.umask_fix', false); } if (self::$umask) { if (!is_dir(dirname($file))) { $old = umask(0002); mkdir(dirname($file), 0777, true); umask($old); } parent::writeCacheFile($file, $content); chmod($file, 0775); } else { parent::writeCacheFile($file, $content); } } }
<?php namespace Grav\Common\Twig; use Grav\Common\GravTrait; /** * A trait to add some custom processing to the identifyLink() method in Parsedown and ParsedownExtra */ trait WriteCacheFileTrait { use GravTrait; protected static $umask; /** * This exists so template cache files use the same * group between apache and cli * * @param $file * @param $content */ protected function writeCacheFile($file, $content) { if (!isset(self::$umask)) { self::$umask = self::getGrav()['config']->get('system.twig.umask_fix', false); } if (self::$umask) { if (!is_dir(dirname($file))) { $old = umask(0002); mkdir(dirname($file), 0777, true); umask($old); } parent::writeCacheFile($file, $content); chmod($file, 0775); } else { parent::writeCacheFile($file, $content); } } }
Use README.rst instead of README.md as long description
from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='cozify', version = '0.2.4', author = 'artanicus', author_email = 'python-cozify@nocturnal.fi', url = 'https://github.com/Artanicus/python-cozify', description = 'Unofficial Python bindings and helpers for the unpublished Cozify API.', long_description = long_description, license = 'MIT', packages = ['cozify'], classifiers = [ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ] )
from distutils.core import setup with open('README.md') as file: long_description = file.read() setup(name='cozify', version = '0.2.4', author = 'artanicus', author_email = 'python-cozify@nocturnal.fi', url = 'https://github.com/Artanicus/python-cozify', description = 'Unofficial Python bindings and helpers for the unpublished Cozify API.', long_description = long_description, license = 'MIT', packages = ['cozify'], classifiers = [ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ] )
Cut dupe admin display fields
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): """ Custom admin for the RawDataVersion model. """ list_display = ( "id", "release_datetime", "pretty_download_size", "download_file_count", "download_record_count", "clean_file_count", "clean_record_count", "pretty_clean_size", ) list_display_links = ('release_datetime',) list_filter = ("release_datetime",) @admin.register(models.RawDataFile) class RawDataFileAdmin(BaseAdmin): """ Custom admin for the RawDataFile model. """ list_display = ( "id", "version", "file_name", "download_records_count", "clean_records_count", "load_records_count", "error_count" ) list_display_links = ('id', 'file_name',) list_filter = ("version__release_datetime",)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): """ Custom admin for the RawDataVersion model. """ list_display = ( "id", "release_datetime", "pretty_download_size", "download_file_count", "download_record_count", "clean_file_count", "clean_record_count", "pretty_clean_size", "download_file_count", "clean_record_count" ) list_display_links = ('release_datetime',) list_filter = ("release_datetime",) @admin.register(models.RawDataFile) class RawDataFileAdmin(BaseAdmin): """ Custom admin for the RawDataFile model. """ list_display = ( "id", "version", "file_name", "download_records_count", "clean_records_count", "load_records_count", "error_count" ) list_display_links = ('id', 'file_name',) list_filter = ("version__release_datetime",)
Remove script crash when no sonos is found
#!/usr/bin/env python3 # # By Henrik Lilleengen (mail@ithenrik.com) # # Released under the MIT License: https://opensource.org/licenses/MIT import soco, sys speakers = list(soco.discover()) if len(speakers) > 0: state = speakers[0].get_current_transport_info()['current_transport_state'] if state == 'PLAYING': if len(sys.argv) > 1 and sys.argv[1] == "1": speakers[0].stop() print("") else: track = speakers[0].get_current_track_info() print(" " + track['title'] + " - " + track['artist']) else: if len(sys.argv) > 1 and sys.argv[1] == "1": speakers[0].play() track = speakers[0].get_current_track_info() print(" " + track['title'] + " - " + track['artist']) else: print("")
#!/usr/bin/env python3 # # By Henrik Lilleengen (mail@ithenrik.com) # # Released under the MIT License: https://opensource.org/licenses/MIT import soco, sys speakers = list(soco.discover()) state = speakers[0].get_current_transport_info()['current_transport_state'] if state == 'PLAYING': if len(sys.argv) > 1 and sys.argv[1] == "1": speakers[0].stop() print("") else: track = speakers[0].get_current_track_info() print(" " + track['title'] + " - " + track['artist']) else: if len(sys.argv) > 1 and sys.argv[1] == "1": speakers[0].play() track = speakers[0].get_current_track_info() print(" " + track['title'] + " - " + track['artist']) else: print("")
Disable other citation style tests which fail for some unknown reason
package org.jabref.logic.citationstyle; import org.jabref.logic.util.TestEntry; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @Disabled("For some reason, instead of vol and pp we get null. No idea about the origin of this problem.") class CitationStyleTest { @Test void getDefault() throws Exception { assertNotNull(CitationStyle.getDefault()); } @Test void testDefaultCitation() { String citation = CitationStyleGenerator.generateCitation(TestEntry.getTestEntry(), CitationStyle.getDefault()); // if the default citation style changes this has to be modified String expected = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">" + "B. Smith, B. Jones, and J. Williams, “Title of the test entry,” " + "<i>BibTeX Journal</i>, vol. 34, no. 3, pp. 45–67, Jul. 2016.</div>\n" + " </div>\n"; assertEquals(expected, citation); } }
package org.jabref.logic.citationstyle; import org.jabref.logic.util.TestEntry; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class CitationStyleTest { @Test public void getDefault() throws Exception { assertNotNull(CitationStyle.getDefault()); } @Test public void testDefaultCitation() { String citation = CitationStyleGenerator.generateCitation(TestEntry.getTestEntry(), CitationStyle.getDefault()); // if the default citation style changes this has to be modified String expected = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">" + "B. Smith, B. Jones, and J. Williams, “Title of the test entry,” " + "<i>BibTeX Journal</i>, vol. 34, no. 3, pp. 45–67, Jul. 2016.</div>\n" + " </div>\n"; assertEquals(expected, citation); } }
:one: Use mutliple returns to improve clarity
const OpeningTimes = require('moment-opening-times'); const timezone = require('../../config/config').timezone; const getOpeningHoursMessage = require('../lib/getOpeningTimesMessage'); const midnightSpanCorrector = require('../lib/midnightSpanCorrector'); function getOpeningInfo(openingTimes, now) { const openingTimesMoment = new OpeningTimes( openingTimes.general, timezone, openingTimes.alterations ); let status = openingTimesMoment.getStatus(now, { next: true }); status = midnightSpanCorrector(openingTimesMoment, status); return { isOpen: status.isOpen, nextOpen: status.nextOpen, openingTimesMessage: getOpeningHoursMessage(status), }; } function getDefault(msg) { return { isOpen: false, openingTimesMessage: msg, }; } function addMessage(openingTimes, hasTelephoneNumber, now) { if (openingTimes) { return getOpeningInfo(openingTimes, now); } if (hasTelephoneNumber) { return getDefault('Call for opening times'); } return getDefault('We can\'t find any opening times'); } module.exports = addMessage;
const OpeningTimes = require('moment-opening-times'); const timezone = require('../../config/config').timezone; const getOpeningHoursMessage = require('../lib/getOpeningTimesMessage'); const midnightSpanCorrector = require('../lib/midnightSpanCorrector'); function getOpeningInfo(openingTimes, now) { const openingTimesMoment = new OpeningTimes( openingTimes.general, timezone, openingTimes.alterations ); let status = openingTimesMoment.getStatus(now, { next: true }); status = midnightSpanCorrector(openingTimesMoment, status); return { isOpen: status.isOpen, nextOpen: status.nextOpen, openingTimesMessage: getOpeningHoursMessage(status), }; } function getDefault(msg) { return { isOpen: false, openingTimesMessage: msg, }; } function addMessage(openingTimes, hasTelephoneNumber, now) { let openingInfo; if (openingTimes) { openingInfo = getOpeningInfo(openingTimes, now); } else if (hasTelephoneNumber) { openingInfo = getDefault('Call for opening times'); } else { openingInfo = getDefault('We can\'t find any opening times'); } return openingInfo; } module.exports = addMessage;
Add some final trove classifiers to help document the project Development Status :: 5 - Production/Stable Intended Audience :: Developers Operating System :: OS Independent
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="William Pearson", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="MIT", long_description=readme_string, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="William Pearson", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="MIT", long_description=readme_string, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
Include modules to test through Bluegel, not individually
var expect = require('expect.js'); var utils = require("../lib/bluegel").Utils; describe("Utils", function() { describe("dominantMovement", function() { it("returns the dominant movement as a direction and distance", function() { var movementOne = [1, 2, 3]; var movementTwo = [2, -4, 4]; expect(utils.dominantMovement(movementOne, movementTwo)).to.eql({direction: "y", distance: -6}); }) it("throws an exception if one or both values are null", function() { expect(function() { utils.dominantMovement(null, [1, 2, 3]) }).to.throwException(); expect(function() { utils.dominantMovement([1, 2, 3], null) }).to.throwException(); expect(function() { utils.dominantMovement(null, null) }).to.throwException(); }) }) })
var expect = require('expect.js'); var utils = require("../lib/utils"); describe("Utils", function() { describe("dominantMovement", function() { it("returns the dominant movement as a direction and distance", function() { var movementOne = [1, 2, 3]; var movementTwo = [2, -4, 4]; expect(utils.dominantMovement(movementOne, movementTwo)).to.eql({direction: "y", distance: -6}); }) it("throws an exception if one or both values are null", function() { expect(function() { utils.dominantMovement(null, [1, 2, 3]) }).to.throwException(); expect(function() { utils.dominantMovement([1, 2, 3], null) }).to.throwException(); expect(function() { utils.dominantMovement(null, null) }).to.throwException(); }) }) })
Add param for turning on date formating.
import logging from django.http import HttpResponse from django.utils import simplejson as json from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found from myuw_mobile.dao.library import get_account_info_for_current_user from myuw_mobile.logger.timer import Timer from myuw_mobile.logger.logresp import log_data_not_found_response, log_success_response class MyLibInfo(RESTDispatch): """ Performs actions on resource at /api/v1/library/. """ def GET(self, request): """ GET returns 200 with the library account balances of the current user """ timer = Timer() logger = logging.getLogger(__name__) myaccount = get_account_info_for_current_user() if myaccount is None: log_data_not_found_response(logger, timer) return data_not_found() log_success_response(logger, timer) resp_json = myaccount.json_data(full_name_format=True) logger.debug(resp_json) return HttpResponse(json.dumps(resp_json))
import logging from django.http import HttpResponse from django.utils import simplejson as json from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found from myuw_mobile.dao.library import get_account_info_for_current_user from myuw_mobile.logger.timer import Timer from myuw_mobile.logger.logresp import log_data_not_found_response, log_success_response class MyLibInfo(RESTDispatch): """ Performs actions on resource at /api/v1/library/. """ def GET(self, request): """ GET returns 200 with the library account balances of the current user """ timer = Timer() logger = logging.getLogger(__name__) myaccount = get_account_info_for_current_user() if myaccount is None: log_data_not_found_response(logger, timer) return data_not_found() log_success_response(logger, timer) resp_json = myaccount.json_data() logger.debug(resp_json) return HttpResponse(json.dumps(resp_json))
Update the model to include the suspect
package com.bignerdranch.android.criminalintent; import java.util.Date; import java.util.UUID; public class Crime { private UUID mId; private String mTitle; private Date mDate; private boolean mSolved; private String mSuspect; public Crime() { this(UUID.randomUUID()); } public Crime(UUID id) { mId = id; mDate = new Date(); } // Accesors public UUID getId() { return mId; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public boolean isSolved() { return mSolved; } public void setSolved(boolean solved) { mSolved = solved; } public Date getDate() { return mDate; } public void setDate(Date date) { mDate = date; } public String getSuspect() { return mSuspect; } public void setSuspect(String suspect) { mSuspect = suspect; } }
package com.bignerdranch.android.criminalintent; import java.util.Date; import java.util.UUID; public class Crime { private UUID mId; private String mTitle; private Date mDate; private boolean mSolved; public Crime() { this(UUID.randomUUID()); } public Crime(UUID id) { mId = id; mDate = new Date(); } // Accesors public UUID getId() { return mId; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public boolean isSolved() { return mSolved; } public void setSolved(boolean solved) { mSolved = solved; } public Date getDate() { return mDate; } public void setDate(Date date) { mDate = date; } }
Add Python 3.2 to package classifiers
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-handlebars', version='0.1.2', url='https://github.com/gears/gears-handlebars', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='Handlebars compiler for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', ], )
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-handlebars', version='0.1.2', url='https://github.com/gears/gears-handlebars', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='Handlebars compiler for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )