text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add return types to trait methods
<?php namespace DanDMartin\LoggerAware\Traits; use Psr\Log\LoggerInterface as PsrLogger; use DanDMartin\LoggerAware\Logger\NullLogger; trait LoggerAware { /** * @var PsrLogger */ protected $logger; /** * @param PsrLogger $l * @required */ public function setLogger(PsrLogger $l): void { $this->logger = $l; } /** * @return PsrLogger */ public function getLogger(): PsrLogger { if(is_null($this->logger)) { $this->logger = new NullLogger(); } return $this->logger; } }
<?php namespace DanDMartin\LoggerAware\Traits; use Psr\Log\LoggerInterface as PsrLogger; use DanDMartin\LoggerAware\Logger\NullLogger; trait LoggerAware { /** * @var PsrLogger */ protected $logger; /** * @param PsrLogger $l * @required */ public function setLogger(PsrLogger $l) { $this->logger = $l; } /** * @return PsrLogger */ public function getLogger() { if(is_null($this->logger)) { $this->logger = new NullLogger(); } return $this->logger; } }
Use beforeEach in property test
import assert from "power-assert"; import Component from "../src/Component"; import * as property from "../src/property"; describe("property", () => { describe(".bind", () => { let c1, c2; beforeEach(() => { c1 = new Component(); property.define(c1, "p1"); c2 = new Component(); property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2); }); it("binds a property", () => { c1.p1 = 123; assert(c2.p2 === 246); }); it("discard binding on source component disposal", () => { c1.dispose(); assert(c1.changes.listeners("p1").length === 0); }); it("discard binding on dest component disposal", () => { c2.dispose(); assert(c1.changes.listeners("p1").length === 0); }); }); });
import assert from "power-assert"; import Component from "../src/Component"; import * as property from "../src/property"; describe("property", () => { describe(".bind", () => { const c1 = new Component(); property.define(c1, "p1"); const c2 = new Component(); property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2); it("binds a property", () => { c1.p1 = 123; assert(c2.p2 === 246); }); it("discard binding on source component disposal", () => { c1.dispose(); assert(c1.changes.listeners("p1").length === 0); }); it("discard binding on dest component disposal", () => { c2.dispose(); assert(c1.changes.listeners("p1").length === 0); }); }); });
Return retcode properly iff erroring fixes #13
#!/usr/bin/env python import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger() def yield_packages(handle, meta=False, retcode=None): for lineno, line in enumerate(handle): if line.startswith('#'): continue try: data = line.split('\t') keys = ['id', 'version', 'platform', 'arch', 'url', 'sha', 'size', 'alt_url', 'comment'] if len(data) != len(keys): log.error('[%s] data has wrong number of columns. %s != %s', lineno + 1, len(data), len(keys)) retcode = 1 ld = {k: v for (k, v) in zip(keys, line.split('\t'))} if meta: yield ld, lineno, line, retcode else: yield ld except Exception, e: log.error(str(e))
#!/usr/bin/env python import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger() def yield_packages(handle, meta=False, retcode=None): for lineno, line in enumerate(handle): if line.startswith('#'): continue try: data = line.split('\t') keys = ['id', 'version', 'platform', 'arch', 'url', 'sha', 'size', 'alt_url', 'comment'] if len(data) != len(keys): log.error('[%s] data has wrong number of columns. %s != %s', lineno + 1, len(data), len(keys)) ld = {k: v for (k, v) in zip(keys, line.split('\t'))} if meta: yield ld, lineno, line, retcode else: yield ld except Exception, e: log.error(str(e))
Add Panes for the display only component also
/** A layer for an adjust speed modification */ import React from 'react' import {Pane} from 'react-leaflet' import colors from 'lib/constants/colors' import PatternLayer from './pattern-layer' import HopLayer from './hop-layer' export default function AdjustSpeedLayer(p) { if (p.modification.hops) { return ( <> <Pane zIndex={500}> <PatternLayer color={colors.NEUTRAL} dim={p.dim} feed={p.feed} modification={p.modification} /> </Pane> <Pane zIndex={501}> <HopLayer color={colors.MODIFIED} dim={p.dim} feed={p.feed} modification={p.modification} /> </Pane> </> ) } else { return ( <PatternLayer color={colors.MODIFIED} dim={p.dim} feed={p.feed} modification={p.modification} /> ) } }
/** A layer for an adjust speed modification */ import React from 'react' import colors from 'lib/constants/colors' import PatternLayer from './pattern-layer' import HopLayer from './hop-layer' export default function AdjustSpeedLayer(p) { if (p.modification.hops) { return ( <> <PatternLayer color={colors.NEUTRAL} dim={p.dim} feed={p.feed} modification={p.modification} /> <HopLayer color={colors.MODIFIED} dim={p.dim} feed={p.feed} modification={p.modification} /> </> ) } else { return ( <PatternLayer color={colors.MODIFIED} dim={p.dim} feed={p.feed} modification={p.modification} /> ) } }
Fix in the unit tests.
<?php /* * Bear CMS addon for Bear Framework * https://bearcms.com/ * Copyright (c) 2016 Amplilabs Ltd. * Free to use under the MIT license. */ /** * @runTestsInSeparateProcesses */ class DefaultThemeTest extends BearFrameworkAddonTestCase { /** * */ public function testBlogPostsElement() { $app = $this->getApp(); $context = $app->getContext(\BearFramework\Addons::get('bearcms/bearframework-addon')['dir'] . '/index.php'); $result = $app->components->process('<component src="file:' . $context->dir . '/themes/default1/components/defaultTemplate.php" />'); //echo $result;exit; //$this->assertTrue($settings['title'] === ''); } }
<?php /* * Bear CMS addon for Bear Framework * https://bearcms.com/ * Copyright (c) 2016 Amplilabs Ltd. * Free to use under the MIT license. */ /** * @runTestsInSeparateProcesses */ class DefaultThemeTest extends BearFrameworkAddonTestCase { /** * */ public function testBlogPostsElement() { $app = $this->getApp(); $context = $app->getContext(\BearFramework\Addons::get('bearcms/bearframework-addon')['dir'] . '/index.php'); $result = $app->components->process('<component src="file:' . $context->dir . '/themes/default1/components/template.php" />'); //echo $result;exit; //$this->assertTrue($settings['title'] === ''); } }
Use fetch column to be independent from the alias
<?php namespace Doctrine\Tests\DBAL\Functional; use Doctrine\Tests\DbalFunctionalTestCase; final class LikeWildcardsEscapingTest extends DbalFunctionalTestCase { public function testFetchLikeExpressionResult() : void { $string = '_25% off_ your next purchase \o/'; $escapeChar = '!'; $stmt = $this->_conn->prepare(sprintf( "SELECT '%s' LIKE '%s' ESCAPE '%s' as it_matches", $string, $this->_conn->getDatabasePlatform()->escapeStringForLike($string, $escapeChar), $escapeChar )); $stmt->execute(); $this->assertTrue((bool) $stmt->fetchColumn()); } }
<?php namespace Doctrine\Tests\DBAL\Functional; use Doctrine\Tests\DbalFunctionalTestCase; final class LikeWildcardsEscapingTest extends DbalFunctionalTestCase { public function testFetchLikeExpressionResult() : void { $string = '_25% off_ your next purchase \o/'; $escapeChar = '!'; $stmt = $this->_conn->prepare(sprintf( "SELECT '%s' LIKE '%s' ESCAPE '%s' as it_matches", $string, $this->_conn->getDatabasePlatform()->escapeStringForLike($string, $escapeChar), $escapeChar )); $stmt->execute(); $this->assertTrue((bool) $stmt->fetch()['it_matches']); } }
Use proper filename for http.ServeContent
package controllers import ( "github.com/julienschmidt/httprouter" "github.com/raggaer/castro/app/util" "net/http" ) func ExtensionStatic(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { // Get extension identifier id := ps.ByName("id") // Check if static file exists dir, exists := util.ExtensionStatic.FileExists(id) if !exists { w.WriteHeader(404) return } // Open desired file f, err := dir.Open(ps.ByName("filepath")) if err != nil { w.WriteHeader(404) return } // Close file handle defer f.Close() // Get file information fi, err := f.Stat() if err != nil { w.WriteHeader(404) return } // Check if file is directory if fi.IsDir() { w.WriteHeader(404) return } // Serve file http.ServeContent(w, req, fi.Name(), fi.ModTime(), f) }
package controllers import ( "github.com/julienschmidt/httprouter" "github.com/raggaer/castro/app/util" "net/http" ) func ExtensionStatic(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { // Get extension identifier id := ps.ByName("id") // Check if static file exists dir, exists := util.ExtensionStatic.FileExists(id) if !exists { w.WriteHeader(404) return } // Open desired file f, err := dir.Open(ps.ByName("filepath")) if err != nil { w.WriteHeader(404) return } // Close file handle defer f.Close() // Get file information fi, err := f.Stat() if err != nil { w.WriteHeader(404) return } // Check if file is directory if fi.IsDir() { w.WriteHeader(404) return } // Serve file http.ServeContent(w, req, ps.ByName("filepath"), fi.ModTime(), f) }
Convert type check targets in thrift/test to use configuration Summary: Migrating buck integration to use configurations. For more information about this migration, please see: https://fb.workplace.com/groups/295311271085134/permalink/552700215346237/ Reviewed By: dkgi Differential Revision: D30708385 fbshipit-source-id: 4d65f711d129dc87f1b87aad342783f09dca0d2d
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict from .adapter_bar.ttypes import Bar class AdapterTestStructToDict: Type = Dict[str, int] @staticmethod # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def from_thrift(thrift_value): return {k: v for k, v in thrift_value.__dict__.items() if v is not None} @staticmethod # pyre-fixme[3]: Return type must be annotated. # pyre-fixme[2]: Parameter must be annotated. def to_thrift(py_value): return Bar(**py_value)
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict from .adapter_bar.ttypes import Bar class AdapterTestStructToDict: Type = Dict[str, int] @staticmethod def from_thrift(thrift_value): return {k: v for k, v in thrift_value.__dict__.items() if v is not None} @staticmethod def to_thrift(py_value): return Bar(**py_value)
Fix ListProperties to be compatible with buildbot 0.8.4p1. The duplicated code will be removed once 0.7.12 is removed. Review URL: http://codereview.chromium.org/7193037 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@91477 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility classes to enhance process.properties.Properties usefulness.""" from buildbot.process.properties import WithProperties class ListProperties(WithProperties): """Act like a list but skip over items that are None. This class doesn't use WithProperties methods but inherits from it since it is used as a flag in Properties.render() to defer the actual work to self.render().""" compare_attrs = ('items') def __init__(self, items): """items should be a list.""" # Dummy initialization. WithProperties.__init__(self, '') self.items = items # For buildbot 8.4 and below. def render(self, pmap): results = [] # For each optional item, look up the corresponding property in the # PropertyMap. for item in self.items: if isinstance(item, WithProperties): item = item.render(pmap) # Skip over None items. if item is not None and item != '': results.append(item) return results # For buildbot 8.4p1 and above. def getRenderingFor(self, build): results = [] # For each optional item, look up the corresponding property in the # PropertyMap. for item in self.items: if isinstance(item, WithProperties): item = item.getRenderingFor(build) # Skip over None items. if item is not None and item != '': results.append(item) return results
# Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility classes to enhance process.properties.Properties usefulness.""" from buildbot.process.properties import WithProperties class ListProperties(WithProperties): """Act like a list but skip over items that are None. This class doesn't use WithProperties methods but inherits from it since it is used as a flag in Properties.render() to defer the actual work to self.render().""" compare_attrs = ('items') def __init__(self, items): """items should be a list.""" # Dummy initialization. WithProperties.__init__(self, '') self.items = items def render(self, pmap): results = [] # For each optional item, look up the corresponding property in the # PropertyMap. for item in self.items: if isinstance(item, WithProperties): item = item.render(pmap) # Skip over None items. if item is not None and item != '': results.append(item) return results
Change repeating alarm to be ELAPSED_REALTIME type Change repeating alarms scheduled by AlarmManager in BootReceiver to be AlarmManager.ELAPSED_REALTIME type instead of RTC type, since we don't need alarms to be fired at particular time, only at particular interval; following best practices here: https://developer.android.com/training/scheduling/alarms.html
package com.marakana.android.yamba; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private static final String TAG = BootReceiver.class.getSimpleName(); private static final long DEFAULT_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES; @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); long interval = Long.parseLong(prefs.getString("interval", Long.toString(DEFAULT_INTERVAL))); PendingIntent operation = PendingIntent.getService(context, -1, new Intent(context, RefreshService.class), PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); if (interval == 0) { alarmManager.cancel(operation); Log.d(TAG, "cancelling repeat operation"); } else { alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), interval, operation); Log.d(TAG, "setting repeat operation for: " + interval); } Log.d(TAG, "onReceived"); } }
package com.marakana.android.yamba; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private static final String TAG = BootReceiver.class.getSimpleName(); private static final long DEFAULT_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES; @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); long interval = Long.parseLong(prefs.getString("interval", Long.toString(DEFAULT_INTERVAL))); PendingIntent operation = PendingIntent.getService(context, -1, new Intent(context, RefreshService.class), PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); if (interval == 0) { alarmManager.cancel(operation); Log.d(TAG, "cancelling repeat operation"); } else { alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), interval, operation); Log.d(TAG, "setting repeat operation for: " + interval); } Log.d(TAG, "onReceived"); } }
Improve page title for experts [WAL-1041]
// @ngInject export default function expertRequestsRoutes($stateProvider) { $stateProvider .state('appstore.expert', { url: 'experts/:category/', template: '<expert-request-create></expert-request-create>', data: { category: 'experts', pageTitle: gettext('Create expert request'), sidebarState: 'project.resources', feature: 'experts', } }) .state('organization.experts', { url: 'experts/', template: '<expert-requests-list/>', data: { pageTitle: gettext('Requests for experts'), feature: 'experts' } }) .state('project.resources.experts', { url: 'experts/', template: '<expert-requests-project-list/>', data: { pageTitle: gettext('Requests for experts'), feature: 'experts' } }) .state('expertRequestDetails', { url: '/experts/:uuid/', template: '<expert-request-details/>', data: { feature: 'experts', pageTitle: gettext('Expert request details'), } }); }
// @ngInject export default function expertRequestsRoutes($stateProvider) { $stateProvider .state('appstore.expert', { url: 'experts/:category/', template: '<expert-request-create></expert-request-create>', data: { category: 'experts', pageTitle: gettext('Create expert request'), sidebarState: 'project.resources', feature: 'experts', } }) .state('organization.experts', { url: 'experts/', template: '<expert-requests-list/>', data: { pageTitle: gettext('Expert requests list'), feature: 'experts' } }) .state('project.resources.experts', { url: 'experts/', template: '<expert-requests-project-list/>', data: { pageTitle: gettext('Expert requests list'), feature: 'experts' } }) .state('expertRequestDetails', { url: '/experts/:uuid/', template: '<expert-request-details/>', data: { feature: 'experts', pageTitle: gettext('Expert request details'), } }); }
Update tests to add option test
module.exports = function (grunt) { grunt.initConfig({ nugetpack: { options: { verbose: true }, dist: { src: 'tests/Package.nuspec', dest: 'tests/' } }, nugetrestore: { restore: { src: 'tests/packages.config', dest: 'packages/' } }, clean: { pack: { src: 'tests/PackageTest.1.0.0.nupkg' }, restore: { src: 'packages' } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadTasks('tasks'); grunt.registerTask('default', ['clean', 'nugetpack', 'nugetrestore']); };
module.exports = function (grunt) { grunt.initConfig({ nugetpack: { dist: { src: 'tests/Package.nuspec', dest: 'tests/' } }, nugetrestore: { restore: { src: 'tests/packages.config', dest: 'packages/' } }, clean: { pack: { src: 'tests/PackageTest.1.0.0.nupkg' }, restore: { src: 'packages' } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadTasks('tasks'); grunt.registerTask('default', ['clean', 'nugetpack', 'nugetrestore']); };
Include autoload.php if it exists
<?php $template_directory = get_template_directory(); if (file_exists("{$template_directory}/functions/autoload.php")) { require_once("{$template_directory}/functions/autoload.php"); } require_once("{$template_directory}/functions/vendor.php"); require_once("{$template_directory}/functions/custom-functions.php"); require_once("{$template_directory}/functions/filters.php"); require_once("{$template_directory}/functions/htaccess.php"); require_once("{$template_directory}/functions/image-sizes.php"); require_once("{$template_directory}/functions/menus.php"); require_once("{$template_directory}/functions/meta.php"); require_once("{$template_directory}/functions/page-speed.php"); require_once("{$template_directory}/functions/post-types.php"); require_once("{$template_directory}/functions/progressive-web-app.php"); require_once("{$template_directory}/functions/rewrite-rules.php"); require_once("{$template_directory}/functions/shortcodes.php"); require_once("{$template_directory}/functions/styles-scripts.php"); require_once("{$template_directory}/functions/theme-features.php"); require_once("{$template_directory}/functions/advanced-custom-fields.php"); require_once("{$template_directory}/functions/ninja-forms.php"); require_once("{$template_directory}/functions/tribe-events.php");
<?php $template_directory = get_template_directory(); require_once("{$template_directory}/functions/vendor.php"); require_once("{$template_directory}/functions/custom-functions.php"); require_once("{$template_directory}/functions/filters.php"); require_once("{$template_directory}/functions/htaccess.php"); require_once("{$template_directory}/functions/image-sizes.php"); require_once("{$template_directory}/functions/menus.php"); require_once("{$template_directory}/functions/meta.php"); require_once("{$template_directory}/functions/page-speed.php"); require_once("{$template_directory}/functions/post-types.php"); require_once("{$template_directory}/functions/progressive-web-app.php"); require_once("{$template_directory}/functions/rewrite-rules.php"); require_once("{$template_directory}/functions/shortcodes.php"); require_once("{$template_directory}/functions/styles-scripts.php"); require_once("{$template_directory}/functions/theme-features.php"); require_once("{$template_directory}/functions/advanced-custom-fields.php"); require_once("{$template_directory}/functions/ninja-forms.php"); require_once("{$template_directory}/functions/tribe-events.php");
Fix social media icon links.
<?php $options = get_option('plugin_options'); $social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss'); ?> <div class="social-media-wrapper"> <ul class="social-media-links"> <?php foreach ($social_media as $i => $name) { if (!empty( $options['vobe_' . $name . '_link'] )) { echo '<li><a href="' . $options['vobe_'.$name.'_link'] . '" target="_blank" class="fa fa-' . $name . '"></a></li>'; } } ?> </ul> <?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?> </div>
<?php $options = get_option('plugin_options'); $social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss'); ?> <div class="social-media-wrapper"> <ul class="social-media-links"> <?php foreach ($social_media as $i => $name) { if (!empty( $options['vobe_' . $name . '_link'] )) { echo '<li><a href="' . $options['tf_'.$name.'_link'] . '" target="_blank" class="fa fa-' . $name . '"></a></li>'; } } ?> </ul> <?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?> </div>
Remove the alert message on addition of string
var Trie = require('trie'); trie = new Trie(); trie.add('bat'); trie.add('bad'); var searchInput = document.getElementById('search-input'); var searchResults = document.getElementById('search-results'); var addButton = document.getElementById('add-button'); addButton.style.display = 'none'; addButton.disabled = true; searchInput.oninput = function() { searchResults.innerHTML = ''; var results = trie.search(this.value); var exists = trie.find(this.value); if (results) { for (var result in results) { var el = document.createElement('li'); var elText = document.createTextNode(results[result]); el.appendChild(elText); searchResults.appendChild(el); } } if (exists || !this.value) { addButton.style.display = 'none'; addButton.disabled = true; } else { addButton.style.display = 'inline-block'; addButton.disabled = false; } }; searchInput.onkeyup = function(event) { if (event.which === 13) { addButton.click(); } }; addButton.onclick = function() { trie.add(searchInput.value); var result = trie.find(searchInput.value); if (result) { searchInput.oninput(); } }; console.log(trie);
var Trie = require('trie'); trie = new Trie(); trie.add('bat'); trie.add('bad'); var searchInput = document.getElementById('search-input'); var searchResults = document.getElementById('search-results'); var addButton = document.getElementById('add-button'); addButton.style.display = 'none'; addButton.disabled = true; searchInput.oninput = function() { searchResults.innerHTML = ''; var results = trie.search(this.value); var exists = trie.find(this.value); if (results) { for (var result in results) { var el = document.createElement('li'); var elText = document.createTextNode(results[result]); el.appendChild(elText); searchResults.appendChild(el); } } if (exists || !this.value) { addButton.style.display = 'none'; addButton.disabled = true; } else { addButton.style.display = 'inline-block'; addButton.disabled = false; } }; searchInput.onkeyup = function(event) { if (event.which === 13) { addButton.click(); } }; addButton.onclick = function() { trie.add(searchInput.value); var result = trie.find(searchInput.value); if (result) { searchInput.oninput(); alert(result + ' was added!'); } }; console.log(trie);
Fix PHP HHVM 'A void return value is being used'...
<?php namespace CrudGenerator\Tests\General\FileManager; use CrudGenerator\Utils\FileManager; class FilePutsContentTest extends \PHPUnit_Framework_TestCase { public function testRender() { $filePath = __DIR__ . '/test.phtml'; $content = 'toto'; $sUT = new FileManager(); $sUT->filePutsContent($filePath, $content); $this->assertEquals( $content, file_get_contents($filePath) ); unlink($filePath); } public function testFail() { $filePath = __DIR__ . '/toto/test.phtml'; $content = 'toto'; $sUT = new FileManager(); $this->setExpectedException('RuntimeException'); $sUT->filePutsContent($filePath, $content); } }
<?php namespace CrudGenerator\Tests\General\FileManager; use CrudGenerator\Utils\FileManager; class FilePutsContentTest extends \PHPUnit_Framework_TestCase { public function testRender() { $filePath = __DIR__ . '/test.phtml'; $content = 'toto'; $sUT = new FileManager(); $fileContent = $sUT->filePutsContent($filePath, $content); $this->assertEquals( $content, file_get_contents($filePath) ); unlink($filePath); } public function testFail() { $filePath = __DIR__ . '/toto/test.phtml'; $content = 'toto'; $sUT = new FileManager(); $this->setExpectedException('RuntimeException'); $sUT->filePutsContent($filePath, $content); } }
Change the live users endpoint
var isOpen = false; function checkStatus(text) { let num = parseInt(text, 10); if (num > 0) { chrome.browserAction.setTitle({ title: 'λspace is open' }); chrome.browserAction.setBadgeText({ text: num.toString() }); chrome.browserAction.setBadgeBackgroundColor({ color: '#808080' }); chrome.browserAction.setIcon({ path: { 48: 'icons/o_48x48.png', 96: 'icons/o_96x96.png' } }); } else { chrome.browserAction.setTitle({ title: 'λspace is closed' }); chrome.browserAction.setBadgeText({ text: '' }); chrome.browserAction.setIcon({ path: { 48: 'icons/c_48x48.png', 96: 'icons/c_96x96.png' } }); } } function timer() { fetch('https://api.lambdaspace.gr/api/v2.0/status') .then(response => response.json()) .then(data => checkStatus(data.people_now_present)) .catch(e => console.error(e)); } timer(); setInterval(timer, 300000);
var isOpen = false; function checkStatus(text) { let num = parseInt(text, 10); if (num > 0) { chrome.browserAction.setTitle({ title: 'λspace is open' }); chrome.browserAction.setBadgeText({ text: num.toString() }); chrome.browserAction.setBadgeBackgroundColor({ color: '#808080' }); chrome.browserAction.setIcon({ path: { 48: 'icons/o_48x48.png', 96: 'icons/o_96x96.png' } }); } else { chrome.browserAction.setTitle({ title: 'λspace is closed' }); chrome.browserAction.setBadgeText({ text: '' }); chrome.browserAction.setIcon({ path: { 48: 'icons/c_48x48.png', 96: 'icons/c_96x96.png' } }); } } function timer() { fetch('https://www.lambdaspace.gr/hackers.txt') .then(response => response.text()) // Get the text of the response .then(data => checkStatus(data)) .catch(e => console.error(e)); // Handle exeptions } timer(); setInterval(timer, 300000);
Develop here. Belongs in top level Orthologs Project.
# Used: # https://github.com/pypa/sampleproject/blob/master/setup.py # https://github.com/biopython/biopython/blob/master/setup.py from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) PACKAGES = [ 'lib', 'lib.scripts', 'lib.scripts.biosql', 'lib.scripts.blast', 'lib.scripts.ftp', 'lib.scripts.genbank', 'lib.scripts.manager', 'lib.scripts.multiprocessing', 'lib.scripts.phylogenetic_analyses' ] # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='orthologs', description="A project that will help to analyze orthologous gense.", version='0.1.0', long_description=long_description, url='https://github.com/robear22890/Orthologs-Project', license='?', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Visualization', 'Programming Language :: Python :: 3', 'Operating System :: Unix', 'Natural Language :: English' ], packages=PACKAGES, install_requires=[], )
from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) PACKAGES = [ 'lib', 'lib.scripts', 'lib.scripts.biosql', 'lib.scripts.blast', 'lib.scripts.ftp', 'lib.scripts.genbank', 'lib.scripts.manager', 'lib.scripts.multiprocessing', 'lib.scripts.phylogenetic_analyses' ] # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='orthologs', description="A project that will help to analyze orthologous gense.", version='0.1.0', long_description=long_description, url='https://github.com/robear22890/Orthologs-Project', license='?', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Visualization', 'Programming Language :: Python :: 3', 'Operating System :: Unix', 'Natural Language :: English' ], packages= )
Update code to be compliant with node 0.10
var serilog = require('../src/core/structured-log.js'); var serilogCompactSink = require('../src/npm/serilog-compact-console-sink.js'); var assert = require('assert'); describe('SerilogCompactConsoleSink', function() { var consoleInfoOutput = [] var originalConsoleInfo = console.info beforeEach(function() { console.info = function() { consoleInfoOutput.push([].slice.call(arguments)) } }) afterEach(function() { console.info = originalConsoleInfo }) it('should output logs to console as JSON', function(done) { var log = serilog.configure() .writeTo(serilogCompactSink()) .create() var messageTemplate = 'Hello, {Name}!' var name = 'world' log.info(messageTemplate, name) assert(consoleInfoOutput[0][0]['@mt'] === messageTemplate) assert(consoleInfoOutput[0][0]['Name'] === name) done() }) })
'use strict' const serilog = require('../src/core/structured-log.js'); const serilogCompactSink = require('../src/npm/serilog-compact-console-sink.js'); const assert = require('assert'); require('mocha-sinon'); describe('SerilogCompactConsoleSink', function() { const consoleInfoOutput = [] const originalConsoleInfo = console.info beforeEach(function() { console.info = function() { consoleInfoOutput.push([].slice.call(arguments)) } }) afterEach(() => { console.info = originalConsoleInfo }) it('should output logs to console as JSON', (done) => { const log = serilog.configure() .writeTo(serilogCompactSink()) .create() const messageTemplate = 'Hello, {Name}!' const name = 'world' log.info(messageTemplate, name) assert(consoleInfoOutput[0][0]['@mt'] === messageTemplate) assert(consoleInfoOutput[0][0]['Name'] === name) done() }) })
Adjust dummy data to better fit new template.
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }); yourCollection.add({ id: 0, name: "Test Item", price: "5.00 (USD)", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "25.00 (USD)", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }); yourCollection.add({ id: 0, name: "Test Item", price: "(USD) $5", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "(USD) $25", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
Make sure this value is always an integer
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=int(100 * settings.PAYMENTS_PLANS[plan]["price"]), interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["name"], currency=settings.PAYMENTS_PLANS[plan]["currency"], id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for {0}".format(plan)
from django.conf import settings from django.core.management.base import BaseCommand import stripe class Command(BaseCommand): help = "Make sure your Stripe account has the plans" def handle(self, *args, **options): stripe.api_key = settings.STRIPE_SECRET_KEY for plan in settings.PAYMENTS_PLANS: if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"): stripe.Plan.create( amount=100 * settings.PAYMENTS_PLANS[plan]["price"], interval=settings.PAYMENTS_PLANS[plan]["interval"], name=settings.PAYMENTS_PLANS[plan]["name"], currency=settings.PAYMENTS_PLANS[plan]["currency"], id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id") ) print "Plan created for {0}".format(plan)
Include solrBaseURL in 'connect-src' content security policy too. Allows normal JSON or JSON-P.
/* jshint node: true */ 'use strict'; var path = require('path'); module.exports = { name: 'ember-solr', _appendPolicy: function(csp, key, value) { var v = csp[key] || ''; if (v) { v += ' '; } csp[key] = v + value; }, config: function(environment, appConfig) { if (!appConfig.solrBaseURL || appConfig.solrBaseURL.indexOf(':') === -1) { return; } var solrSchemeAndHost = appConfig.solrBaseURL; var solrHostEnd = solrSchemeAndHost.indexOf('/', solrSchemeAndHost.indexOf('://') + 3); if (solrHostEnd > 0) { solrSchemeAndHost = solrSchemeAndHost.substring(0, solrHostEnd); } var csp = appConfig.contentSecurityPolicy || {}; this._appendPolicy(csp, 'connect-src', solrSchemeAndHost); this._appendPolicy(csp, 'script-src', solrSchemeAndHost); var ENV = { contentSecurityPolicy: csp }; return ENV; }, included: function json_bignum_included(app) { this._super.included(app); app.import(path.join(app.bowerDirectory, 'json-bignum', 'lib', 'json-bignum.js')); } };
/* jshint node: true */ 'use strict'; var path = require('path'); module.exports = { name: 'ember-solr', config: function(environment, appConfig) { if (!appConfig.solrBaseURL || appConfig.solrBaseURL.indexOf(':') === -1) { return; } var solrSchemeAndHost = appConfig.solrBaseURL; var solrHostEnd = solrSchemeAndHost.indexOf('/', solrSchemeAndHost.indexOf('://') + 3); if (solrHostEnd > 0) { solrSchemeAndHost = solrSchemeAndHost.substring(0, solrHostEnd); } var ENV = { contentSecurityPolicy: { 'script-src': "'self' " + solrSchemeAndHost } } return ENV; }, included: function json_bignum_included(app) { this._super.included(app); app.import(path.join(app.bowerDirectory, 'json-bignum', 'lib', 'json-bignum.js')); } };
Fix the yield infinite loop error Because Blade uses the footer variable to store the template information, has to be initialized as an empty array.
<?php namespace Bkwld\LaravelHaml; // Dependencies use Illuminate\View\Compilers\BladeCompiler; use Illuminate\View\Compilers\CompilerInterface; use Illuminate\Filesystem\Filesystem; use MtHaml\Environment; class HamlBladeCompiler extends BladeCompiler implements CompilerInterface { /** * The MtHaml instance. * * @var \MtHaml\Environment */ protected $mthaml; /** * Create a new compiler instance. * * @param \MtHaml\Environment $mthaml * @param \Illuminate\Filesystem\Filesystem $files * @param string $cachePath * @return void */ public function __construct(Environment $mthaml, Filesystem $files, $cachePath) { $this->mthaml = $mthaml; parent::__construct($files, $cachePath); } /** * Compile the view at the given path. * * @param string $path * @return void */ public function compile($path) { if (is_null($this->cachePath)) return; $this->footer = array(); // First compile the Haml $contents = $this->mthaml->compileString($this->files->get($path), $path); // Then the Blade syntax $contents = $this->compileString($contents); // Save $this->files->put($this->getCompiledPath($path), $contents); } }
<?php namespace Bkwld\LaravelHaml; // Dependencies use Illuminate\View\Compilers\BladeCompiler; use Illuminate\View\Compilers\CompilerInterface; use Illuminate\Filesystem\Filesystem; use MtHaml\Environment; class HamlBladeCompiler extends BladeCompiler implements CompilerInterface { /** * The MtHaml instance. * * @var \MtHaml\Environment */ protected $mthaml; /** * Create a new compiler instance. * * @param \MtHaml\Environment $mthaml * @param \Illuminate\Filesystem\Filesystem $files * @param string $cachePath * @return void */ public function __construct(Environment $mthaml, Filesystem $files, $cachePath) { $this->mthaml = $mthaml; parent::__construct($files, $cachePath); } /** * Compile the view at the given path. * * @param string $path * @return void */ public function compile($path) { if (is_null($this->cachePath)) return; // First compile the Haml $contents = $this->mthaml->compileString($this->files->get($path), $path); // Then the Blade syntax $contents = $this->compileString($contents); // Save $this->files->put($this->getCompiledPath($path), $contents); } }
Remove img task from grunt build As it takes ages, and it always seems to change the images every time someone else runs it. Probably no one else will ever need to update the images, or very rarely, in which case they can manually run the build img task.
module.exports = function(grunt) { // load all tasks from package.json require('load-grunt-config')(grunt); require('time-grunt')(grunt); /** * TASKS */ // build everything ready for a commit grunt.registerTask('build', ['css', 'js']); // just CSS grunt.registerTask('css', ['sass', 'cssmin']); // just images grunt.registerTask('img', ['responsive_images:retina', 'exec:evenizer', 'responsive_images:regular', 'sprite', 'imagemin']); // just javascript (babel must go before we add the wrapper, to keep it's generated methods inside, so not globals) grunt.registerTask('js', ['eslint', 'template:jsAddVersion', 'babel', 'concat', 'uglify', 'replace']); // build examples grunt.registerTask('examples', ['template']); // Travis CI grunt.registerTask('travis', ['jasmine']); // bump version number in 3 files, rebuild js to update headers, then commit, tag and push grunt.registerTask('version', ['bump-only', 'js', 'bump-commit', 'shell:publish']); };
module.exports = function(grunt) { // load all tasks from package.json require('load-grunt-config')(grunt); require('time-grunt')(grunt); /** * TASKS */ // build everything ready for a commit grunt.registerTask('build', ['img', 'css', 'js']); // just CSS grunt.registerTask('css', ['sass', 'cssmin']); // just images grunt.registerTask('img', ['responsive_images:retina', 'exec:evenizer', 'responsive_images:regular', 'sprite', 'imagemin']); // just javascript (babel must go before we add the wrapper, to keep it's generated methods inside, so not globals) grunt.registerTask('js', ['eslint', 'template:jsAddVersion', 'babel', 'concat', 'uglify', 'replace']); // build examples grunt.registerTask('examples', ['template']); // Travis CI grunt.registerTask('travis', ['jasmine']); // bump version number in 3 files, rebuild js to update headers, then commit, tag and push grunt.registerTask('version', ['bump-only', 'js', 'bump-commit', 'shell:publish']); };
Make sure shard key is a string
/* Copyright (c) 2014 Chico Charlesworth, MIT License */ 'use strict'; var sharder = require('sharder'); var async = require('async'); var name = 'seneca-shard-cache'; module.exports = function( options ) { var seneca = this; var shards = sharder(options); var role = 'cache'; seneca.add({role: role, cmd: 'set'}, act); seneca.add({role: role, cmd: 'get'}, act); seneca.add({role: role, cmd: 'add'}, act); seneca.add({role: role, cmd: 'delete'}, act); seneca.add({role: role, cmd: 'incr'}, act); seneca.add({role: role, cmd: 'decr'}, act); function act(args, done) { var toact = Object.create(args) toact.shard = shards.resolve('' + args.key); seneca.act(toact, function(err, result) { if (err) {return done(err);} done(null, result); }); } return { name:name }; }
/* Copyright (c) 2014 Chico Charlesworth, MIT License */ 'use strict'; var sharder = require('sharder'); var async = require('async'); var name = 'seneca-shard-cache'; module.exports = function( options ) { var seneca = this; var shards = sharder(options); var role = 'cache'; seneca.add({role: role, cmd: 'set'}, act); seneca.add({role: role, cmd: 'get'}, act); seneca.add({role: role, cmd: 'add'}, act); seneca.add({role: role, cmd: 'delete'}, act); seneca.add({role: role, cmd: 'incr'}, act); seneca.add({role: role, cmd: 'decr'}, act); function act(args, done) { var toact = Object.create(args) toact.shard = shards.resolve(args.key); seneca.act(toact, function(err, result) { if (err) {return done(err);} done(null, result); }); } return { name:name }; }
Revert "be more explicit when importing files"
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { checkout } from '../actions' import { getTotal, getCartProducts } from '../reducers' import Cart from '../components/Cart' class CartContainer extends Component { render() { const { products, total } = this.props return ( <Cart products={products} total={total} onCheckoutClicked={() => this.props.checkout()} /> ) } } CartContainer.propTypes = { products: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, title: PropTypes.string.isRequired, price: PropTypes.number.isRequired, quantity: PropTypes.number.isRequired })).isRequired, total: PropTypes.string, checkout: PropTypes.func.isRequired } const mapStateToProps = (state) => { return { products: getCartProducts(state), total: getTotal(state) } } export default connect( mapStateToProps, { checkout } )(CartContainer)
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { checkout } from '../actions/index' import { getTotal, getCartProducts } from '../reducers/index' import Cart from '../components/Cart' class CartContainer extends Component { render() { const { products, total } = this.props return ( <Cart products={products} total={total} onCheckoutClicked={() => this.props.checkout()} /> ) } } CartContainer.propTypes = { products: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, title: PropTypes.string.isRequired, price: PropTypes.number.isRequired, quantity: PropTypes.number.isRequired })).isRequired, total: PropTypes.string, checkout: PropTypes.func.isRequired } const mapStateToProps = (state) => { return { products: getCartProducts(state), total: getTotal(state) } } export default connect( mapStateToProps, { checkout } )(CartContainer)
Fix the license header regex. Most of the files are attributed to Google Inc so I used this instead of Chromium Authors. R=mark@chromium.org BUG= TEST= Review URL: http://codereview.chromium.org/7108074 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@936 78cadc50-ecff-11dd-a971-7dbc132099af
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for GYP. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] license = ( r'.*? Copyright \(c\) %(year)s Google Inc\. All rights reserved\.\n' r'.*? Use of this source code is governed by a BSD-style license that ' r'can be\n' r'.*? found in the LICENSE file\.\n' ) % { 'year': input_api.time.strftime('%Y'), } report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api, license_header=license)) report.extend(input_api.canned_checks.CheckTreeIsOpen( input_api, output_api, 'http://gyp-status.appspot.com/status', 'http://gyp-status.appspot.com/current')) return report def GetPreferredTrySlaves(): return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for GYP. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) report.extend(input_api.canned_checks.CheckTreeIsOpen( input_api, output_api, 'http://gyp-status.appspot.com/status', 'http://gyp-status.appspot.com/current')) return report def GetPreferredTrySlaves(): return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
Set the timezone on MySQL formatted dates.
'use strict'; /* * Number Filters * * In HTML Template Binding * {{ filter_expression | filter : expression : comparator}} * * In JavaScript * $filter('filter')(array, expression, comparator) * * https://docs.angularjs.org/api/ng/filter/filter */ var app = angular.module('app.filters.number', []); app.filter("formatPrice", function () { return function (value) { if (!value) { return value; } return '$' + value; }; }); app.filter("formatMySQLDate", function () { return function (value) { if (!value) { return value; } return moment(value, 'YYYY-MM-DD HH:mm:ss').tz('America/New_York').format('M/D/YYYY h:mm a'); }; });
'use strict'; /* * Number Filters * * In HTML Template Binding * {{ filter_expression | filter : expression : comparator}} * * In JavaScript * $filter('filter')(array, expression, comparator) * * https://docs.angularjs.org/api/ng/filter/filter */ var app = angular.module('app.filters.number', []); app.filter("formatPrice", function () { return function (value) { if (!value) { return value; } return '$' + value; }; }); app.filter("formatMySQLDate", function () { return function (value) { if (!value) { return value; } return moment(value, 'YYYY-MM-DD HH:mm:ss').format('M/D/YYYY h:mm a'); }; });
Use correct kwarg for requests.post()
import os import pytest import requests REGISTER_TITLE_URL = os.environ['DIGITAL_REGISTER_URL'] USERNAME = os.environ['SMOKE_USERNAME'] PASSWORD = os.environ['SMOKE_PASSWORD'] TITLE_NUMBER = os.environ['SMOKE_TITLE_NUMBER'] PARTIAL_ADDRESS = os.environ['SMOKE_PARTIAL_ADDRESS'] POSTCODE = os.environ['SMOKE_POSTCODE'] def test_frontend_up(): # login stuff response = requests.post('{}/login?next=titles'.format(REGISTER_TITLE_URL), data={'username': USERNAME, 'password': PASSWORD}, allow_redirects=False) import pdb; pdb.set_trace()
import os import pytest import requests REGISTER_TITLE_URL = os.environ['DIGITAL_REGISTER_URL'] USERNAME = os.environ['SMOKE_USERNAME'] PASSWORD = os.environ['SMOKE_PASSWORD'] TITLE_NUMBER = os.environ['SMOKE_TITLE_NUMBER'] PARTIAL_ADDRESS = os.environ['SMOKE_PARTIAL_ADDRESS'] POSTCODE = os.environ['SMOKE_POSTCODE'] def test_frontend_up(): # login stuff response = requests.post('{}/login?next=titles'.format(REGISTER_TITLE_URL), data={'username': USERNAME, 'password': PASSWORD}, follow_redirects=False) import pdb; pdb.set_trace()
Mask Service is pending the completed object model SVN-Revision: 396
package gov.nih.nci.calab.service.workflow; /** * Generalizes Mask functionality for masking Aliquot, File, etc. * @author doswellj * @param strType Type of Mask (e.g., aliquot, file, run, etc.) * @param strId The id associated to the type * @param strDescription The mask description associated to the mask type and Id. * */ public class MaskService { //This functionality is pending the completed Object Model public void setMask(String strType, String strId, String strDescription) { if (strType.equals("aliquot")) { //TODO Find Aliquot record based on the strID //TODO Set File Status record to "Masked". } if (strType.equals("file")) { //TODO Find File record based on the its strID //TODO Set File Status record to "Masked". } } }
package gov.nih.nci.calab.service.workflow; /** * Generalizes Mask functionality for masking Aliquot, File, etc. * @author doswellj * @param strType Type of Mask (e.g., aliquot, file, run, etc.) * @param strId The id associated to the type * @param strDescription The mask description associated to the mask type and Id. * */ public class MaskService { public void setMask(String strType, String strId, String strDescription) { if (strType.equals("aliquot")) { //TODO Find Aliquot record based on the its id and set the status to "Masked" and its Description } if (strType.equals("file")) { //TODO Find File record based on the its id and set the status to "Masked" and its Description } } }
Fix bug showing the wrong date when creating a new lotto because it depended on the current time
Template.lottoAdd.created = function() { Session.set('lottoAddErrors', {}); }; Template.lottoAdd.rendered = function() { var nextSaturday = moment().startOf('day').day(6).utcOffset(0); this.find('#date').value = nextSaturday.format('YYYY-MM-DD'); this.find('#date').valueAsDate = nextSaturday.toDate(); }; Template.lottoAdd.helpers({ errorMessage: function(field) { return Session.get('lottoAddErrors')[field]; }, errorClass: function (field) { return !!Session.get('lottoAddErrors')[field] ? 'has-error' : ''; } }); Template.lottoAdd.events({ 'submit form': function(e) { e.preventDefault(); var lotto = { date: moment(e.target.date.value).toDate() }; if (!lotto.date) { var errors = {}; errors.date = "Please select a date"; return Session.set('lottoAddErrors', errors); } //var autofill = e.target.autofill.checked; Meteor.call('lottoInsert', lotto, false, function(error, result) { if(error) { return throwError(error.reason); } if(result.lottoExists) { throwError('Lotto for this date already exists'); } Router.go('lottoPage', {_id: result._id}); }); } });
Template.lottoAdd.created = function() { Session.set('lottoAddErrors', {}); }; Template.lottoAdd.rendered = function() { var nextSaturday = moment().day(5).utcOffset(0); this.find('#date').value = nextSaturday.format('YYYY-MM-DD'); this.find('#date').valueAsDate = nextSaturday.toDate(); }; Template.lottoAdd.helpers({ errorMessage: function(field) { return Session.get('lottoAddErrors')[field]; }, errorClass: function (field) { return !!Session.get('lottoAddErrors')[field] ? 'has-error' : ''; } }); Template.lottoAdd.events({ 'submit form': function(e) { e.preventDefault(); var lotto = { date: moment(e.target.date.value).toDate() }; if (!lotto.date) { var errors = {}; errors.date = "Please select a date"; return Session.set('lottoAddErrors', errors); } //var autofill = e.target.autofill.checked; Meteor.call('lottoInsert', lotto, false, function(error, result) { if(error) { return throwError(error.reason); } if(result.lottoExists) { throwError('Lotto for this date already exists'); } Router.go('lottoPage', {_id: result._id}); }); } });
Fix up failing boilerplate test
#!/usr/bin/env python # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import boilerplate import unittest from io import StringIO import os import sys class TestBoilerplate(unittest.TestCase): """ Note: run this test from the hack/boilerplate directory. $ python -m unittest boilerplate_test """ def test_boilerplate(self): os.chdir("test/") class Args(object): def __init__(self): self.filenames = [] self.rootdir = "." self.boilerplate_dir = "../" self.verbose = True # capture stdout old_stdout = sys.stdout sys.stdout = StringIO.StringIO() boilerplate.args = Args() ret = boilerplate.main() output = sorted(sys.stdout.getvalue().split()) sys.stdout = old_stdout self.assertEquals( output, ['././fail.go', '././fail.py'])
#!/usr/bin/env python # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import boilerplate import unittest import StringIO import os import sys class TestBoilerplate(unittest.TestCase): """ Note: run this test from the hack/boilerplate directory. $ python -m unittest boilerplate_test """ def test_boilerplate(self): os.chdir("test/") class Args(object): def __init__(self): self.filenames = [] self.rootdir = "." self.boilerplate_dir = "../" self.verbose = True # capture stdout old_stdout = sys.stdout sys.stdout = StringIO.StringIO() boilerplate.args = Args() ret = boilerplate.main() output = sorted(sys.stdout.getvalue().split()) sys.stdout = old_stdout self.assertEquals( output, ['././fail.go', '././fail.py'])
Disable Redux DevTools in prod
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index', output: { filename: './dist/index.js' }, module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') // Must be an absolute path }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]__[local]___[hash:base64:5]!autoprefixer!less'), exclude: /node_modules/ }] }, resolve: { modulesDirectories: ['node_modules', 'components'] }, plugins: [ new ExtractTextPlugin('./dist/app.css'), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') }, __DEVTOOLS__: false }), new webpack.optimize.UglifyJsPlugin({ output: { comments: false }, compress: { warnings: false } }) ] };
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index', output: { filename: './dist/index.js' }, module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') // Must be an absolute path }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]__[local]___[hash:base64:5]!autoprefixer!less'), exclude: /node_modules/ }] }, resolve: { modulesDirectories: ['node_modules', 'components'] }, plugins: [ new ExtractTextPlugin('./dist/app.css'), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ output: { comments: false }, compress: { warnings: false } }) ] };
Fix weird issue with craft price calculation in some cases
// Update the tree prices function treePrices (tree, itemPrices) { tree = {...tree} // Either use the "used quantity" which gets set when the user uses // own materials, or the base "total quantity" of this tree segment let quantity = tree.usedQuantity !== undefined ? tree.usedQuantity : tree.totalQuantity // Calculate the buy prices tree.buyPriceEach = itemPrices[tree.id] || false tree.buyPrice = tree.buyPriceEach ? quantity * tree.buyPriceEach : false tree.bestPrice = tree.buyPrice if (!tree.components) { return tree } // Calculate the tree prices traversal for the sub-components tree.components = tree.components.map(component => treePrices(component, itemPrices)) // Calculate the craft price out of the best prices tree.craftPrice = tree.components.map(c => c.bestPrice).reduce((a, b) => a + b) // If we explicitly don't craft this, keep the buy price as the best price if (tree.craft === false) { return tree } // Update the best price of this tree segment, used to // determine the craft price of the higher-up recipe if (!tree.buyPrice || tree.craftPrice < tree.buyPrice) { tree.bestPrice = tree.craftPrice } return tree } module.exports = treePrices
// Update the tree prices function treePrices (tree, itemPrices) { tree = {...tree} // Either use the "used quantity" which gets set when the user uses // own materials, or the base "total quantity" of this tree segment let quantity = tree.usedQuantity !== undefined ? tree.usedQuantity : tree.totalQuantity // Calculate the buy prices tree.buyPriceEach = itemPrices[tree.id] || false tree.buyPrice = tree.buyPriceEach ? quantity * tree.buyPriceEach : false tree.bestPrice = tree.buyPrice if (!tree.components) { return tree } // Calculate the tree prices traversal for the sub-components tree.components = tree.components.map(component => treePrices(component, itemPrices)) // Calculate the craft price out of the best prices tree.craftPrice = tree.components.reduce((a, b) => a.bestPrice + b.bestPrice) // If we explicitly don't craft this, keep the buy price as the best price if (tree.craft === false) { return tree } // Update the best price of this tree segment, used to // determine the craft price of the higher-up recipe if (!tree.buyPrice || tree.craftPrice < tree.buyPrice) { tree.bestPrice = tree.craftPrice } return tree } module.exports = treePrices
Remove the default maximum parsing limit of 1,000 keys
var querystring = require("querystring"); var list = /L_([A-Za-z]+)(\d+)/; module.exports = function(input) { var data; var output = {}; if (typeof input === "string") { // Parse without limits on the maximum number of keys, see: // https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options data = querystring.parse(input, null, null, { maxKeys: 0 }); } else { data = input; } Object.keys(data).forEach(function(key) { var list_match = key.match(list); if (!list_match) { return output[key] = data[key]; } if (!Array.isArray(output.L)) { output.L = []; } if (!output.L[list_match[2]]) { output.L[list_match[2]] = {}; } output.L[list_match[2]][list_match[1]] = data[key]; }); return output; };
var querystring = require("querystring"); var list = /L_([A-Za-z]+)(\d+)/; module.exports = function(input) { var data; var output = {}; if (typeof input === "string") { data = querystring.parse(input); } else { data = input; } Object.keys(data).forEach(function(key) { var list_match = key.match(list); if (!list_match) { return output[key] = data[key]; } if (!Array.isArray(output.L)) { output.L = []; } if (!output.L[list_match[2]]) { output.L[list_match[2]] = {}; } output.L[list_match[2]][list_match[1]] = data[key]; }); return output; };
Load storybook page to ensure everything is ok before proceeding with the tests
describe('Entire feed', () => { it('should render the entire feed component correctly', () => { cy.visit('/') cy.visit('/iframe.html?id=activityfeed--entire-feed') cy.get('#root').should('be.visible').compareSnapshot('entire-feed') }) }) describe('Empty feed', () => { it('should render the entire feed component correctly', () => { cy.visit('/iframe.html?id=activityfeed--empty-feed') cy.get('#root').should('be.visible').compareSnapshot('empty-feed') }) }) describe('Company feed', () => { it('should render the company feed component correctly', () => { cy.visit('/iframe.html?id=activityfeed--data-hub-company-page') cy.get('[data-test="activity-feed"]').should('be.visible') cy.get('#root').should('be.visible').compareSnapshot('company-feed') }) }) describe('With error', () => { it('should render the with error component correctly', () => { cy.visit('/iframe.html?id=activityfeed--with-error') cy.get('#root').should('be.visible').compareSnapshot('with-error') }) })
describe('Entire feed', () => { it('should render the entire feed component correctly', () => { cy.visit('/iframe.html?id=activityfeed--entire-feed') cy.get('#root').should('be.visible').compareSnapshot('entire-feed') }) }) describe('Empty feed', () => { it('should render the entire feed component correctly', () => { cy.visit('/iframe.html?id=activityfeed--empty-feed') cy.get('#root').should('be.visible').compareSnapshot('empty-feed') }) }) describe('Company feed', () => { it('should render the company feed component correctly', () => { cy.visit('/iframe.html?id=activityfeed--data-hub-company-page') cy.get('[data-test="activity-feed"]').should('be.visible') cy.get('#root').should('be.visible').compareSnapshot('company-feed') }) }) describe('With error', () => { it('should render the with error component correctly', () => { cy.visit('/iframe.html?id=activityfeed--with-error') cy.get('#root').should('be.visible').compareSnapshot('with-error') }) })
Use dato data instead of contentful
import React from 'react'; import Img from 'gatsby-image'; import { Container, Section, Title } from 'bloomer'; import Markdown from 'react-markdown'; function SpeakerTemplate(props) { const speaker = props.data.datoCmsSpeaker; return ( <Section> <Container> <Title>{speaker.name}</Title> <Img className="bio-image" alt={speaker.name} resolutions={speaker.photo.resolutions} /> <Markdown source={speaker.blurb} /> </Container> </Section> ); } export default SpeakerTemplate; export const pageQuery = graphql` query SpeakerByPath($slug: String!) { datoCmsSpeaker(slug: { eq: $slug }) { name slug title blurb photo { id resolutions(width: 250) { width height src srcSet } } } } `;
import React from 'react'; import Img from 'gatsby-image'; import { Container, Section, Title } from 'bloomer'; import Markdown from 'react-markdown'; function SpeakerTemplate(props) { const speaker = props.data.contentfulSpeaker; return ( <Section> <Container> <Title>{speaker.name}</Title> <Img className="bio-image" alt={speaker.name} resolutions={speaker.photo.resolutions} /> <Markdown source={speaker.blurb.blurb}/> </Container> </Section> ); } export default SpeakerTemplate; export const pageQuery = graphql` query SpeakerByPath($slug: String!) { contentfulSpeaker(slug: {eq: $slug}) { name slug title blurb { id blurb } photo { id title resolutions(width: 250) { width height src srcSet } } } } `;
Fix pattern matching for multiline comments. fixes kkemple/grunt-stripcomments#1
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var mulitlineComment = /\/\*[\s\S]*?\*\//g; var singleLineComment = /\/\/.+/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(mulitlineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
/* * grunt-strip-comments * https://github.com/kkemple/grunt-strip-comments * * Copyright (c) 2013 Kurtis Kemple * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('comments', 'Remove comments from production code', function() { var mulitlineComment = /\/\*(.|\n|\t|\r)+\*\//gm; var singleLineComment = /\/\/.+/g; var options = this.options({ singleline: true, multiline: true }); this.files[0].src.forEach(function (file) { var contents = grunt.file.read(file); if ( options.multiline ) { contents = contents.replace(mulitlineComment, ''); } if ( options.singleline ) { contents = contents.replace(singleLineComment, ''); } grunt.file.write(file, contents); }); }); };
Order cancel - don't pass mutli-D array
<?php namespace CartRover; class Orders extends APIObject { /** * Insert one or more orders into CartRover * @param string $api_user * @param string $api_key * @param array $orders_array Array of orders, even if only one * @return array */ public static function CreateOrders($api_user, $api_key, $orders_array){ $endpoint = '/cart/orders/cartrover'; return APIObject::make_api_call($api_user, $api_key, $endpoint, $orders_array); } /** * Cancel an order in CartRover. This may fail if you wait too long to cancel the order after its creation * @param string $api_user * @param string $api_key * @param array $cust_ref cust_ref of order to cancel * @return array */ public static function CancelOrder($api_user, $api_key, $cust_ref){ $endpoint = '/cart/orders/cancel/cartrover'; $post_array = array( 'cust_ref' => $cust_ref ); return APIObject::make_api_call($api_user, $api_key, $endpoint, $post_array); } }
<?php namespace CartRover; class Orders extends APIObject { /** * Insert one or more orders into CartRover * @param string $api_user * @param string $api_key * @param array $orders_array Array of orders, even if only one * @return array */ public static function CreateOrders($api_user, $api_key, $orders_array){ $endpoint = '/cart/orders/cartrover'; return APIObject::make_api_call($api_user, $api_key, $endpoint, $orders_array); } /** * Cancel an order in CartRover. This may fail if you wait too long to cancel the order after its creation * @param string $api_user * @param string $api_key * @param array $cust_ref cust_ref of order to cancel * @return array */ public static function CancelOrder($api_user, $api_key, $cust_ref){ $endpoint = '/cart/orders/cancel/cartrover'; $post_array = array( array( 'cust_ref' => $cust_ref ) ); return APIObject::make_api_call($api_user, $api_key, $endpoint, $post_array); } }
Add semicolons to avoid generating typos
/*! { "name": "Unicode characters", "property": "unicode", "tags": ["encoding"], "warnings": [ "positive Unicode support doesn't mean you can use it inside <title>, this seems more related to OS & Language packs" ] } !*/ /* DOC Detects if unicode characters are supported in the current document. */ define(['Modernizr', 'createElement', 'testStyles', 'isSVG'], function(Modernizr, createElement, testStyles, isSVG) { /** * Unicode special character support * * Detection is made by testing missing glyph box rendering against star character * If widths are the same, this "probably" means the browser didn't support the star character and rendered a glyph box instead * Just need to ensure the font characters have different widths */ Modernizr.addTest('unicode', function() { var bool; var missingGlyph = createElement('span'); var star = createElement('span'); testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) { missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987;'; star.innerHTML = isSVG ? '\u2606' : '&#9734;'; node.appendChild(missingGlyph); node.appendChild(star); bool = 'offsetWidth' in missingGlyph && missingGlyph.offsetWidth !== star.offsetWidth; }); return bool; }); });
/*! { "name": "Unicode characters", "property": "unicode", "tags": ["encoding"], "warnings": [ "positive Unicode support doesn't mean you can use it inside <title>, this seems more related to OS & Language packs" ] } !*/ /* DOC Detects if unicode characters are supported in the current document. */ define(['Modernizr', 'createElement', 'testStyles', 'isSVG'], function(Modernizr, createElement, testStyles, isSVG) { /** * Unicode special character support * * Detection is made by testing missing glyph box rendering against star character * If widths are the same, this "probably" means the browser didn't support the star character and rendered a glyph box instead * Just need to ensure the font characters have different widths */ Modernizr.addTest('unicode', function() { var bool; var missingGlyph = createElement('span'); var star = createElement('span'); testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) { missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987'; star.innerHTML = isSVG ? '\u2606' : '&#9734'; node.appendChild(missingGlyph); node.appendChild(star); bool = 'offsetWidth' in missingGlyph && missingGlyph.offsetWidth !== star.offsetWidth; }); return bool; }); });
Allow for minus signs in project slug.
import re MODULE_REGEX = r"^[-_a-zA-Z0-9]*$" ENVIRON_REGEX = r"^[-_a-zA-Z0-9]*$" PYTHONVERSION_REGEX = r"^(3)\.[6-9]$" module_name = "{{ cookiecutter.project_slug}}" if not re.match(MODULE_REGEX, module_name): raise ValueError( f""" ERROR: The project slug ({module_name}) is not a valid name. Please do not use anything other than letters, numbers, underscores '_', and minus signs '-'. """ ) environment_name = "{{ cookiecutter.create_conda_environment_with_name }}" if not re.match(ENVIRON_REGEX, environment_name): raise ValueError( f""" ERROR: The project slug ({module_name}) is not a valid name. Please do not use anything other than letters, numbers, underscores '_', and minus signs '-'. """ ) python_version = "{{ cookiecutter.python_version }}" if not re.match(PYTHONVERSION_REGEX, python_version): raise ValueError( f""" ERROR: The python version must be >= 3.6 """ )
import re MODULE_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" ENVIRON_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" PYTHONVERSION_REGEX = r"^(3)\.[6-9]$" module_name = "{{ cookiecutter.project_slug}}" if not re.match(MODULE_REGEX, module_name): raise ValueError( f""" ERROR: The project slug ({module_name}) is not a valid Python module name. Please do not use anything other than letters, numbers and '_', and do not start with a number. """ ) environment_name = "{{ cookiecutter.create_conda_environment_with_name }}" if not re.match(ENVIRON_REGEX, environment_name): raise ValueError( f""" ERROR: The project slug ({environment_name}) is not a valid Python module name. Please do not use anything other than letters, numbers and '_', and do not start with a number. """ ) python_version = "{{ cookiecutter.python_version }}" if not re.match(PYTHONVERSION_REGEX, python_version): raise ValueError( f""" ERROR: The python version must be >= 3.6 """ )
Fix JS tests for mocking modals with correct API.
describe('Utils.OPAL._run', function (){ it('Should add open_modal to the root scope.', function () { var mock_scope = { $on: function(){} }; var mock_modal = { open: function(){} }; OPAL._run(mock_scope, {}, mock_modal) expect(mock_scope.open_modal).toBeDefined(); }); it('Should open a modal with the arguments', function () { var mock_scope = { $on: function(){} }; var mock_then = { result: { then: function(){} } }; var mock_modal = { open: function(){ return mock_then } }; spyOn(mock_modal, 'open').and.callThrough(); spyOn(mock_then, 'result'); OPAL._run(mock_scope, {}, mock_modal) mock_scope.open_modal('TestCtrl', 'template.html', 'lg', {episode: {}}) var call_args = mock_modal.open.calls.mostRecent().args[0]; expect(call_args.controller).toBe('TestCtrl'); expect(call_args.templateUrl).toBe('template.html'); expect(call_args.size).toBe('lg'); expect(call_args.resolve.episode()).toEqual({}); }); });
describe('Utils.OPAL._run', function (){ it('Should add open_modal to the root scope.', function () { var mock_scope = { $on: function(){} }; var mock_modal = { open: function(){} }; OPAL._run(mock_scope, {}, mock_modal) expect(mock_scope.open_modal).toBeDefined(); }); it('Should open a modal with the arguments', function () { var mock_scope = { $on: function(){} }; var mock_then = { then: function(){} }; var mock_modal = { open: function(){ return mock_then } }; spyOn(mock_modal, 'open').and.callThrough(); spyOn(mock_then, 'then'); OPAL._run(mock_scope, {}, mock_modal) mock_scope.open_modal('TestCtrl', 'template.html', 'lg', {episode: {}}) var call_args = mock_modal.open.calls.mostRecent().args[0]; expect(call_args.controller).toBe('TestCtrl'); expect(call_args.templateUrl).toBe('template.html'); expect(call_args.size).toBe('lg'); expect(call_args.resolve.episode()).toEqual({}); }); });
Make dfp library path come first on include path
<?php /** * PHP Datafeed Library * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.opensource.org/licenses/bsd-license.php * * @category Dfp * @package UnitTest * @subpackage Bootstrap * @copyright Copyright (c) 2012 PHP Datafeed Library * @version $Id: Bootstrap.php 15 2012-04-04 14:08:43Z mail@henryhayes.co.uk $ * @since 2012-04-04 */ /** * Bootstrap file for the PHP Datafeed Library. * * @category Dfp * @package UnitTest * @subpackage Bootstrap * @copyright Copyright (c) 2012 PHP Datafeed Library * @author Henry Hayes <mail@henryhayes.co.uk> * @since 2012-04-04 */ define('BASE_PATH', dirname(dirname(realpath(__FILE__)))); define('LIBRARY_PATH', BASE_PATH . DIRECTORY_SEPARATOR . 'library'); set_include_path(implode(PATH_SEPARATOR, array(LIBRARY_PATH, get_include_path()))); require_once('Zend/Loader/Autoloader.php'); $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->setFallbackAutoloader(true);
<?php /** * PHP Datafeed Library * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.opensource.org/licenses/bsd-license.php * * @category Dfp * @package UnitTest * @subpackage Bootstrap * @copyright Copyright (c) 2012 PHP Datafeed Library * @version $Id: Bootstrap.php 15 2012-04-04 14:08:43Z mail@henryhayes.co.uk $ * @since 2012-04-04 */ /** * Bootstrap file for the PHP Datafeed Library. * * @category Dfp * @package UnitTest * @subpackage Bootstrap * @copyright Copyright (c) 2012 PHP Datafeed Library * @author Henry Hayes <mail@henryhayes.co.uk> * @since 2012-04-04 */ define('BASE_PATH', dirname(dirname(realpath(__FILE__)))); define('LIBRARY_PATH', BASE_PATH . DIRECTORY_SEPARATOR . 'library'); set_include_path(implode(PATH_SEPARATOR, array(get_include_path(), LIBRARY_PATH))); require_once('Zend/Loader/Autoloader.php'); $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->setFallbackAutoloader(true);
Remove unused function. [rev: matthew.gordon]
define([ 'js-whatever/js/base-page', 'text!about-page/templates/about-page.html', 'datatables.net-bs' ], function(BasePage, template) { return BasePage.extend({ template: _.template(template), initialize: function(options) { this.options = options; this.options.icon = this.options.icon || 'fa fa-cog'; }, render: function() { this.$el.html(this.template(this.options)); this.$('table.table').dataTable({ autoWidth: false, language: { search: '' } }); this.$('.dataTables_filter input') .prop('placeholder', this.options.strings.search); } }); });
define([ 'js-whatever/js/base-page', 'text!about-page/templates/about-page.html', 'datatables.net-bs' ], function(BasePage, template) { return BasePage.extend({ template: _.template(template), initialize: function(options) { this.options = options; this.options.icon = this.options.icon || 'fa fa-cog'; }, render: function() { this.$el.html(this.template(this.options)); this.$('table.table').dataTable({ autoWidth: false, language: { search: '' } }); this.$('.dataTables_filter input') .prop('placeholder', this.options.strings.search); }, getTemplateParameters: $.noop }); });
Exclude node_modules from Babel processing
var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: { index: './src/demo/index.js' }, output: { path: './target/demo', filename: '[name].js' }, plugins: [ new HtmlWebpackPlugin({ template: './src/demo/index.html', minify: {collapseWhitespace: true} }), new ExtractTextPlugin('[name].css') ], module: { loaders: [ {test: /\.js$/, loader: 'babel', exclude: /node_modules/}, {test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less?strictUnits=true&strictMath=true')}, {test: /\.(png|jpg)$/, loader: 'file-loader?name=[name].[ext]'} ] } };
var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: { index: './src/demo/index.js' }, output: { path: './target/demo', filename: '[name].js' }, plugins: [ new HtmlWebpackPlugin({ template: './src/demo/index.html', minify: {collapseWhitespace: true} }), new ExtractTextPlugin('[name].css') ], module: { loaders: [ {test: /\.js$/, loader: 'babel'}, {test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less?strictUnits=true&strictMath=true')}, {test: /\.(png|jpg)$/, loader: 'file-loader?name=[name].[ext]'} ] } };
Document difference between ID and virtual ID
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.provision.zone; import com.yahoo.config.provision.CloudName; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.SystemName; /** * @author hakonhall */ public interface ZoneApi { SystemName getSystemName(); /** * Returns the ID of the zone. * * WARNING: The ID of a controller zone is equal to the ID of a prod zone in the same region. * @see #getVirtualId() */ ZoneId getId(); /** Returns the SYSTEM.ENVIRONMENT.REGION string. */ default String getFullName() { return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value(); } /** * Returns {@link #getId()} for all zones except the controller zone. Unlike {@link #getId()}, * the virtual ID of a controller is distinct from all other zones. */ default ZoneId getVirtualId() { return getId(); } default Environment getEnvironment() { return getId().environment(); } default RegionName getRegionName() { return getId().region(); } CloudName getCloudName(); /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */ String getCloudNativeRegionName(); }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.provision.zone; import com.yahoo.config.provision.CloudName; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.SystemName; /** * @author hakonhall */ public interface ZoneApi { SystemName getSystemName(); ZoneId getId(); /** Returns the SYSTEM.ENVIRONMENT.REGION string. */ default String getFullName() { return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value(); } /** * Returns the virtual ID of this zone. For ordinary zones this is the same as {@link ZoneApi#getId()}, for a * system represented as a zone this is a fixed ID that is independent of the actual zone ID. */ default ZoneId getVirtualId() { return getId(); } default Environment getEnvironment() { return getId().environment(); } default RegionName getRegionName() { return getId().region(); } CloudName getCloudName(); /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */ String getCloudNativeRegionName(); }
Add service name to embedded Job representations Change-Id: I7bb7e8dcbb85f563267dcd9ad823365c8a4efa9c
package com.cgi.eoss.ftep.api.projections; import com.cgi.eoss.ftep.api.security.FtepPermission; import com.cgi.eoss.ftep.model.Job; import com.cgi.eoss.ftep.model.JobStatus; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; import java.time.LocalDateTime; /** * <p>Default JSON projection for embedded {@link Job}s. Embeds the owner as a ShortUser.</p> */ @Projection(name = "shortFtepService", types = {Job.class}) public interface ShortJob extends EmbeddedId { String getExtId(); ShortUser getOwner(); JobStatus getStatus(); String getGuiUrl(); String getStage(); LocalDateTime getStartTime(); LocalDateTime getEndTime(); @Value("#{target.config.service.name}") String getServiceName(); @Value("#{@ftepSecurityService.getCurrentPermission(target.class, target.id)}") FtepPermission getAccessLevel(); }
package com.cgi.eoss.ftep.api.projections; import com.cgi.eoss.ftep.api.security.FtepPermission; import com.cgi.eoss.ftep.model.Job; import com.cgi.eoss.ftep.model.JobStatus; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; import java.time.LocalDateTime; /** * <p>Default JSON projection for embedded {@link Job}s. Embeds the owner as a ShortUser.</p> */ @Projection(name = "shortFtepService", types = {Job.class}) public interface ShortJob extends EmbeddedId { String getExtId(); ShortUser getOwner(); JobStatus getStatus(); String getGuiUrl(); String getStage(); LocalDateTime getStartTime(); LocalDateTime getEndTime(); @Value("#{@ftepSecurityService.getCurrentPermission(target.class, target.id)}") FtepPermission getAccessLevel(); }
Add "it" as locale alias for it_IT
<?php return array( // Native language name 'language' => array('it_IT' => 'Italiano'), 'englishlang' => array('it_IT' => 'Italian'), // Possible locale for language 'locale' => array('it_IT' => 'it,it_IT,it_IT.utf8,it_IT.utf-8,it_IT.UTF-8,it_IT@euro,italian,Italian_Italy.1252'), // Encoding of the language 'encoding' => array('it_IT' => 'UTF-8'), // Direction of the language 'direction' => array('it_IT' => 'ltr'), // Possible aliases for language 'alias' => array( 'it' => 'it_IT', 'italiano' => 'it_IT', 'ita' => 'it_IT', 'italian' => 'it_IT', 'it_IT.ISO8859-1' => 'it_IT', 'it_IT.ISO8859-15' => 'it_IT', ), );
<?php return array( // Native language name 'language' => array('it_IT' => 'Italiano'), 'englishlang' => array('it_IT' => 'Italian'), // Possible locale for language 'locale' => array('it_IT' => 'it_IT,it_IT.utf8,it_IT.utf-8,it_IT.UTF-8,it_IT@euro,italian,Italian_Italy.1252'), // Encoding of the language 'encoding' => array('it_IT' => 'UTF-8'), // Direction of the language 'direction' => array('it_IT' => 'ltr'), // Possible aliases for language 'alias' => array( 'it' => 'it_IT', 'italiano' => 'it_IT', 'ita' => 'it_IT', 'italian' => 'it_IT', 'it_IT.ISO8859-1' => 'it_IT', 'it_IT.ISO8859-15' => 'it_IT', ), );
Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_parts(source=source, writer_name='html') return html['html_body'] def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus() return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_parts(source=source, writer_name='html') return html['html_body'] def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus(plugins={'nib':{}}) return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
Set id on page frame and comment frame.
function receiveMessage(event) { var commentPath, iframeURL; // get url of comment commentPath = event.data.commentURL; iframeURL = "https://news.ycombinator.com/" + commentPath; } var drawIframe = function( URL ) { var frameset, pageURL, pageFrame, commentFrame, html, body; html = document.querySelector( "html" ); body = document.querySelector( "body" ); frameset = document.createElement( "frameset" ); pageFrame = document.createElement( "frame" ); commentFrame = document.createElement( "frame" ); pageFrame.setAttribute( "id", "page-frame" ); commentFrame.setAttribute( "id", "comment-frame" ); pageURL = document.URL; if ( body ) body.parentNode.removeChild( body ); frameset.appendChild( pageFrame ); frameset.appendChild( commentFrame ); html.appendChild( frameset ); pageFrame.setAttribute( "src", pageURL ); } console.log(document.body); drawIframe(); window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) { var commentPath, iframeURL; // get url of comment commentPath = event.data.commentURL; iframeURL = "https://news.ycombinator.com/" + commentPath; } var drawIframe = function( URL ) { var frameset, pageURL, pageFrame, commentFrame, html, body; console.log("drawing iframe"); html = document.querySelector( "html" ); body = document.querySelector( "body" ); frameset = document.createElement( "frameset" ) pageFrame = document.createElement( "frame" ); commentFrame = document.createElement( "frame" ); pageURL = document.URL; if ( body ) body.parentNode.removeChild( body ); frameset.appendChild( pageFrame ); frameset.appendChild( commentFrame ); html.appendChild( frameset ); pageFrame.setAttribute( "src", pageURL ); } drawIframe( ); window.addEventListener("message", receiveMessage, false);
Remove cartocss, not used anymore
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBWebglLayerGroupView = L.Class.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function () {}, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta change:visible', function (e) { self.tangram.addLayer(e.attributes); }); }, setZIndex: function () {}, _onURLsChanged: function (e, res) { var url = res.tiles[0] .replace('{layerIndexes}', 'mapnik') .replace('.png', '.mvt'); this.tangram.addDataSource(url); } }); module.exports = LeafletCartoDBWebglLayerGroupView;
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBWebglLayerGroupView = L.Class.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function () {}, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta change:visible change:cartocss', function (e) { self.tangram.addLayer(e.attributes); }); }, setZIndex: function () {}, _onURLsChanged: function (e, res) { var url = res.tiles[0] .replace('{layerIndexes}', 'mapnik') .replace('.png', '.mvt'); this.tangram.addDataSource(url); } }); module.exports = LeafletCartoDBWebglLayerGroupView;
Fix typoe items vs items()
import time, gevent seen = None def used(url, http_pool): __patch() seen[(url, http_pool)] = time.time() def __patch(): global seen if seen is None: seen = {} gevent.spawn(clean) def clean(): while True: for k, last_seen in seen.items(): if time.time()-last_seen < 0.3: continue url, pool = k pool.request(url, 'GET', headers = {'Connection':'close'}) gevent.sleep(0.3)
import time, gevent seen = None def used(url, http_pool): __patch() seen[(url, http_pool)] = time.time() def __patch(): global seen if seen is None: seen = {} gevent.spawn(clean) def clean(): while True: for k, last_seen in seen.items: if time.time()-last_seen < 0.3: continue url, pool = k pool.request(url, 'GET', headers = {'Connection':'close'}) gevent.sleep(0.3)
[Flow] Use "Promise<any>" instead of "Promise<*>" to avoid inference `Promise<*>` is getting inferred to be `Promise<Map | Set>` but we actually want `Promise<any>`.
// @flow import isPlainObject from 'lodash/isPlainObject'; import zip from 'lodash/zip'; import zipObject from 'lodash/zipObject'; export default async function mux(promises: any): Promise<any> { if (promises == null) { return promises; } if (typeof promises.then === 'function') { let value = await promises; return mux(value); } if (Array.isArray(promises)) { return Promise.all(promises.map(mux)); } if (promises instanceof Map) { let keys = [...promises.keys()]; let values = await Promise.all([...promises.values()].map(mux)); return new Map(zip(keys, values)); } if (promises instanceof Set) { let values = await Promise.all([...promises.values()].map(mux)); return new Set(values); } if (isPlainObject(promises)) { let keys = Object.keys(promises); let values = []; for (let key of keys) { values.push(promises[key]); } values = await Promise.all(values.map(mux)); return zipObject(keys, values); } return promises; }
// @flow import isPlainObject from 'lodash/isPlainObject'; import zip from 'lodash/zip'; import zipObject from 'lodash/zipObject'; export default async function mux(promises: any): Promise<*> { if (promises == null) { return promises; } if (typeof promises.then === 'function') { let value = await promises; return mux(value); } if (Array.isArray(promises)) { return Promise.all(promises.map(mux)); } if (promises instanceof Map) { let keys = [...promises.keys()]; let values = await Promise.all([...promises.values()].map(mux)); return new Map(zip(keys, values)); } if (promises instanceof Set) { let values = await Promise.all([...promises.values()].map(mux)); return new Set(values); } if (isPlainObject(promises)) { let keys = Object.keys(promises); let values = []; for (let key of keys) { values.push(promises[key]); } values = await Promise.all(values.map(mux)); return zipObject(keys, values); } return promises; }
Change to new setter-less date time method
<?php namespace Becklyn\RadBundle\Entity\Traits; use Doctrine\ORM\Mapping as ORM; /** * */ trait TimestampsTrait { /** * @var \DateTimeImmutable * @ORM\Column(name="time_created", type="datetime_immutable") */ private $timeCreated; /** * @var \DateTimeImmutable|null * @ORM\Column(name="time_modified", type="datetime_immutable", nullable=true) */ private $timeModified; /** * @return \DateTimeImmutable */ public function getTimeCreated () : \DateTimeImmutable { return $this->timeCreated; } /** * @return \DateTimeImmutable|null */ public function getTimeModified () : ?\DateTimeImmutable { return $this->timeModified; } /** * @param \DateTimeImmutable $timeModified */ public function markAsModified () { $this->timeModified = new \DateTimeImmutable(); } /** * Returns the most recent modification time * * @return \DateTimeImmutable */ public function getLastModificationTime () : \DateTimeImmutable { return $this->getTimeModified() ?? $this->getTimeCreated(); } }
<?php namespace Becklyn\RadBundle\Entity\Traits; use Doctrine\ORM\Mapping as ORM; /** * */ trait TimestampsTrait { /** * @var \DateTimeImmutable * @ORM\Column(name="time_created", type="datetime_immutable") */ private $timeCreated; /** * @var \DateTimeImmutable|null * @ORM\Column(name="time_modified", type="datetime_immutable", nullable=true) */ private $timeModified; /** * @return \DateTimeImmutable */ public function getTimeCreated () : \DateTimeImmutable { return $this->timeCreated; } /** * @return \DateTimeImmutable|null */ public function getTimeModified () : ?\DateTimeImmutable { return $this->timeModified; } /** * @param \DateTimeImmutable $timeModified */ public function setTimeModified (\DateTimeImmutable $timeModified) { $this->timeModified = $timeModified; } /** * Returns the most recent modification time * * @return \DateTimeImmutable */ public function getLastModificationTime () : \DateTimeImmutable { return $this->getTimeModified() ?? $this->getTimeCreated(); } }
Fix empty Path not removing files correctly
<?php use Codeception\Configuration; use Codeception\Util\Debug; use Illuminate\Filesystem\Filesystem; /** * Output Path * * @author Alin Eugen Deac <aedart@gmail.com> */ trait OutputPath { /** * Creates an output path, if it does not already exist */ public function createOutputPath() { if(!file_exists($this->outputPath())){ mkdir($this->outputPath(), 0755, true); Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath())); } } /** * Deletes all files and folders inside the given path * * @param string $path */ public function emptyPath($path) { // Remove all created folders inside output path $fs = new Filesystem(); $fs->cleanDirectory($path); // Not all files might have been removed by // the delete directory method. Therefore, we // search the dir for files and remove those as well. $files = $fs->files($path); $fs->delete($files); } /** * Returns the output directory path * * @return string * @throws \Codeception\Exception\ConfigurationException */ public function outputPath() { return Configuration::outputDir(); } }
<?php use Codeception\Configuration; use Codeception\Util\Debug; use Illuminate\Filesystem\Filesystem; /** * Output Path * * @author Alin Eugen Deac <aedart@gmail.com> */ trait OutputPath { /** * Creates an output path, if it does not already exist */ public function createOutputPath() { if(!file_exists($this->outputPath())){ mkdir($this->outputPath(), 0755, true); Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath())); } } /** * Deletes all files and folders inside the given path * * @param string $path */ public function emptyPath($path) { // Remove all created folders inside output path $fs = new Filesystem(); $folders = $fs->directories($path); foreach($folders as $directory){ $fs->deleteDirectory($directory); } } /** * Returns the output directory path * * @return string * @throws \Codeception\Exception\ConfigurationException */ public function outputPath() { return Configuration::outputDir(); } }
Add parse param type test
/*! * wef.cssParser tests * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ module("cssParser"); test("namespace", function() { notEqual(wef.cssParser , undefined, "is wef.cssParser namespace defined?"); equal(typeof wef.cssParser, "function", "is wef.cssParser a function?"); }); test("constructor", function() { equal(typeof wef.cssParser(), "object", "empty constructor returns an object"); }); test("public properties", function() { equal(typeof wef.cssParser().version, "string", "wef.cssParser().version"); }); test("pubic methods", function() { var text = 'body { height: 100%; display: "a.b.c" /2em "....." /1em "d.e.f" "....." /1em "g.h.i" /2em 5em 1em * 1em 10em}'; ok(wef.cssParser().parse(text) != null, "parse(string) ok"); ok(wef.cssParser().parse(444) == null, "parse(number) returns null"); });
/*! * wef.cssParser tests * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ module("cssParser"); test("namespace", function() { notEqual(wef.cssParser , undefined, "is wef.cssParser namespace defined?"); equal(typeof wef.cssParser, "function", "is wef.cssParser a function?"); }); test("constructor", function() { equal(typeof wef.cssParser(), "object", "empty constructor returns an object"); }); test("public properties", function() { equal(typeof wef.cssParser().version, "string", "wef.cssParser().version"); }); test("pubic methods", function() { var text = 'body { height: 100%; display: "a.b.c" /2em "....." /1em "d.e.f" "....." /1em "g.h.i" /2em 5em 1em * 1em 10em}'; ok(wef.cssParser().parse(text) != null, "parse()"); });
Fix azure terraform fixture filename.
package azure_test import ( "io/ioutil" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/terraform/azure" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("TemplateGenerator", func() { var ( templateGenerator azure.TemplateGenerator ) BeforeEach(func() { templateGenerator = azure.NewTemplateGenerator() }) Describe("Generate", func() { It("generates a terraform template for azure", func() { expectedTemplate, err := ioutil.ReadFile("fixtures/azure_template.tf") Expect(err).NotTo(HaveOccurred()) template := templateGenerator.Generate(storage.State{ EnvID: "azure-environment", Azure: storage.Azure{ SubscriptionID: "subscription-id", TenantID: "tenant-id", ClientID: "client-id", ClientSecret: "client-secret", }, }) Expect(template).To(Equal(string(expectedTemplate))) }) }) })
package azure_test import ( "io/ioutil" "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/terraform/azure" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("TemplateGenerator", func() { var ( templateGenerator azure.TemplateGenerator ) BeforeEach(func() { templateGenerator = azure.NewTemplateGenerator() }) Describe("Generate", func() { It("generates a terraform template for azure", func() { expectedTemplate, err := ioutil.ReadFile("fixtures/azure_template_rg.tf") Expect(err).NotTo(HaveOccurred()) template := templateGenerator.Generate(storage.State{ EnvID: "azure-environment", Azure: storage.Azure{ SubscriptionID: "subscription-id", TenantID: "tenant-id", ClientID: "client-id", ClientSecret: "client-secret", }, }) Expect(template).To(Equal(string(expectedTemplate))) }) }) })
Reduce visibility where `public` is not required
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.transport.memory; import io.spine.server.transport.ChannelId; import io.spine.server.transport.Subscriber; /** * An in-memory implementation of the {@link Subscriber}. * * <p>To use only in scope of the same JVM as {@linkplain InMemoryPublisher publishers}. */ class InMemorySubscriber extends Subscriber { InMemorySubscriber(ChannelId id) { super(id); } }
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.transport.memory; import io.grpc.Internal; import io.spine.server.transport.ChannelId; import io.spine.server.transport.Subscriber; /** * An in-memory implementation of the {@link Subscriber}. * * <p>To use only in scope of the same JVM as {@linkplain InMemoryPublisher publishers}. */ @Internal public class InMemorySubscriber extends Subscriber { public InMemorySubscriber(ChannelId id) { super(id); } }
Add default for 'initial' parameter on Select monkeypatch
from django.apps import AppConfig class DjangoCmsSpaConfig(AppConfig): name = 'djangocms_spa' def ready(self): from django.forms import CheckboxInput, RadioSelect, Select, SelectMultiple from .form_helpers import get_placeholder_for_choices_field, get_serialized_choices_for_field CheckboxInput.render_spa = lambda self, field, initial: { 'items': get_serialized_choices_for_field(field=field), 'type': 'checkbox', 'multiline': True, } RadioSelect.render_spa = lambda self, field, initial: { 'items': get_serialized_choices_for_field(field=field), 'type': 'radio', 'multiline': True, } Select.render_spa = lambda self, field, initial=None: { 'items': get_serialized_choices_for_field(field=field), 'placeholder': get_placeholder_for_choices_field(field) } SelectMultiple.render_spa = lambda self, field, initial=None: { 'items': get_serialized_choices_for_field(field=field), }
from django.apps import AppConfig class DjangoCmsSpaConfig(AppConfig): name = 'djangocms_spa' def ready(self): from django.forms import CheckboxInput, RadioSelect, Select, SelectMultiple from .form_helpers import get_placeholder_for_choices_field, get_serialized_choices_for_field CheckboxInput.render_spa = lambda self, field, initial: { 'items': get_serialized_choices_for_field(field=field), 'type': 'checkbox', 'multiline': True, } RadioSelect.render_spa = lambda self, field, initial: { 'items': get_serialized_choices_for_field(field=field), 'type': 'radio', 'multiline': True, } Select.render_spa = lambda self, field, initial: { 'items': get_serialized_choices_for_field(field=field), 'placeholder': get_placeholder_for_choices_field(field) } SelectMultiple.render_spa = lambda self, field, initial = None: { 'items': get_serialized_choices_for_field(field=field), }
Add uglify2 minification to build
({ mainConfigFile: '../requirejs.conf.js', paths: { almond: 'lib/almond/almond' }, baseUrl: '..', name: "streamhub-permalink", include: [ 'almond', 'streamhub-permalink/default-permalink-content-renderer' ], stubModules: ['text', 'hgn', 'json'], out: "../dist/streamhub-permalink.min.js", buildCSS: true, separateCSS: true, pragmasOnSave: { excludeHogan: true }, cjsTranslate: true, optimize: "uglify2", preserveLicenseComments: false, uglify2: { compress: { unsafe: true }, mangle: true }, generateSourceMaps: true, wrap: { startFile: 'wrap-start.frag', endFile: 'wrap-end.frag' }, onBuildRead: function(moduleName, path, contents) { switch (moduleName) { case "jquery": // case "base64": contents = "define([], function(require, exports, module) {" + contents + "});"; } return contents; } })
({ mainConfigFile: '../requirejs.conf.js', paths: { almond: 'lib/almond/almond' }, baseUrl: '..', name: "streamhub-permalink", include: [ 'almond', 'streamhub-permalink/default-permalink-content-renderer' ], stubModules: ['text', 'hgn', 'json'], out: "../dist/streamhub-permalink.min.js", buildCSS: true, separateCSS: true, pragmasOnSave: { excludeHogan: true }, cjsTranslate: true, optimize: "none", preserveLicenseComments: false, uglify2: { compress: { unsafe: true }, mangle: true }, generateSourceMaps: true, wrap: { startFile: 'wrap-start.frag', endFile: 'wrap-end.frag' }, onBuildRead: function(moduleName, path, contents) { switch (moduleName) { case "jquery": // case "base64": contents = "define([], function(require, exports, module) {" + contents + "});"; } return contents; } })
Hide the label component for table editing.
export default [ { key: 'label', ignore: true }, { type: 'number', label: 'Number of Rows', key: 'numRows', input: true, weight: 1, placeholder: 'Number of Rows', tooltip: 'Enter the number or rows that should be displayed by this table.' }, { type: 'number', label: 'Number of Columns', key: 'numCols', input: true, weight: 2, placeholder: 'Number of Columns', tooltip: 'Enter the number or columns that should be displayed by this table.' }, { type: 'checkbox', label: 'Striped', key: 'striped', tooltip: 'This will stripe the table if checked.', input: true, weight: 701 }, { type: 'checkbox', label: 'Bordered', key: 'bordered', input: true, tooltip: 'This will border the table if checked.', weight: 702 }, { type: 'checkbox', label: 'Hover', key: 'hover', input: true, tooltip: 'Highlight a row on hover.', weight: 703 }, { type: 'checkbox', label: 'Condensed', key: 'condensed', input: true, tooltip: 'Condense the size of the table.', weight: 704 } ];
export default [ { type: 'number', label: 'Number of Rows', key: 'numRows', input: true, weight: 0, placeholder: 'Number of Rows', tooltip: 'Enter the number or rows that should be displayed by this table.' }, { type: 'number', label: 'Number of Columns', key: 'numCols', input: true, weight: 1, placeholder: 'Number of Columns', tooltip: 'Enter the number or columns that should be displayed by this table.' }, { type: 'checkbox', label: 'Striped', key: 'striped', tooltip: 'This will stripe the table if checked.', input: true, weight: 701 }, { type: 'checkbox', label: 'Bordered', key: 'bordered', input: true, tooltip: 'This will border the table if checked.', weight: 702 }, { type: 'checkbox', label: 'Hover', key: 'hover', input: true, tooltip: 'Highlight a row on hover.', weight: 703 }, { type: 'checkbox', label: 'Condensed', key: 'condensed', input: true, tooltip: 'Condense the size of the table.', weight: 704 } ];
IMplement hashCode to eliminate warning
package arez.dom; import java.util.Objects; /** * A class containing width and height dimensions. */ public final class Dimension { private final int _width; private final int _height; /** * Create the dimension object. * * @param width the width. * @param height the height. */ public Dimension( final int width, final int height ) { _width = width; _height = height; } /** * Return the width. * * @return the width. */ public int getWidth() { return _width; } /** * Return the height. * * @return the height. */ public int getHeight() { return _height; } @Override public boolean equals( final Object o ) { if ( o instanceof Dimension ) { final Dimension other = (Dimension) o; return other._width == _width && other._height == _height; } else { return false; } } @Override public int hashCode() { return Objects.hash( _width, _height ); } }
package arez.dom; /** * A class containing width and height dimensions. */ public final class Dimension { private final int _width; private final int _height; /** * Create the dimension object. * * @param width the width. * @param height the height. */ public Dimension( final int width, final int height ) { _width = width; _height = height; } /** * Return the width. * * @return the width. */ public int getWidth() { return _width; } /** * Return the height. * * @return the height. */ public int getHeight() { return _height; } @Override public boolean equals( final Object o ) { if ( o instanceof Dimension ) { final Dimension other = (Dimension) o; return other._width == _width && other._height == _height; } else { return false; } } }
Add missing class to select
$( window ).load(function() { var togglePanel = function(panelId, link){ var panel = $(panelId); panel.toggle(); if(panel.is(":visible")){ $(link).html('<span class="glyphicon glyphicon-circle-arrow-up">Hide</span>'); }else{ $(link).html('<span class="glyphicon glyphicon-circle-arrow-down">Show</span>'); } }; $('#togglePanel').click(function(){ togglePanel('#input_panel', this); }); $('#toggleLegend').click(function(){ togglePanel('#zone_legend', this); }); $('#toggleMapLegend').click(function(){ togglePanel('#map_legend', this); }); $('select').addClass("form-control"); var initMap = function(){ if($(map).data('leaflet-map')){ // lMap is the leaflet map object see http://leafletjs.com/reference.html var lMap = $(map).data('leaflet-map'); L.control.scale().addTo(lMap); } else { setTimeout(initMap, 100); } }; initMap(); $("#printBtn").click(function(){ $('#map').print(); }); });
$( window ).load(function() { var togglePanel = function(panelId, link){ var panel = $(panelId); panel.toggle(); if(panel.is(":visible")){ $(link).html('<span class="glyphicon glyphicon-circle-arrow-up">Hide</span>'); }else{ $(link).html('<span class="glyphicon glyphicon-circle-arrow-down">Show</span>'); } }; $('#togglePanel').click(function(){ togglePanel('#input_panel', this); }); $('#toggleLegend').click(function(){ togglePanel('#zone_legend', this); }); $('#toggleMapLegend').click(function(){ togglePanel('#map_legend', this); }); var initMap = function(){ if($(map).data('leaflet-map')){ // lMap is the leaflet map object see http://leafletjs.com/reference.html var lMap = $(map).data('leaflet-map'); L.control.scale().addTo(lMap); } else { setTimeout(initMap, 100); } }; initMap(); $("#printBtn").click(function(){ $('#map').print(); }); });
Remove test item from config grabbing script
#!/usr/bin/env python2 import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
#!/usr/bin/env python2 import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator", "/bla.txt"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
Remove unnecessary error log from js module bundle
"use strict"; const Task = require('../Task'), gulp = require('gulp'), path = require('path'), ProjectType = require('../../ProjectType'), tsc = require('gulp-typescript'); class JSTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.command = "js"; this.availableTo = [ProjectType.FRONTEND_MODULE]; } action() { var tsConfig = tsc.createProject("tsconfig.json"); return gulp.src([ this._buildManager.options.scripts + "/**/*.{ts,tsx}" ]) .pipe(tsc(tsConfig)) .on("error", function (error) { process.exit(1); }) .pipe(gulp.dest(this._buildManager.options.distribution)); } } module.exports = JSTask;
"use strict"; const Task = require('../Task'), gulp = require('gulp'), path = require('path'), ProjectType = require('../../ProjectType'), tsc = require('gulp-typescript'); class JSTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.command = "js"; this.availableTo = [ProjectType.FRONTEND_MODULE]; } action() { var tsConfig = tsc.createProject("tsconfig.json"); return gulp.src([ this._buildManager.options.scripts + "/**/*.{ts,tsx}" ]) .pipe(tsc(tsConfig)) .on("error", function (error) { console.error(error); process.exit(1); }) .pipe(gulp.dest(this._buildManager.options.distribution)); } } module.exports = JSTask;
Convert double to single quotes
'use strict'; var Redis = require('ioredis'); var start = new Date(); // I can't get to 1,000,000 commands in one pipeline, not even to 120,000, because ioredis would just hang. // Therefore I use 100,000 and hope that this is precise enough. var N = 100*1000; var redis = new Redis(); redis.del('foo'); var pipeline = redis.pipeline(); for(var i = 0; i < N; i++) { pipeline.set('foo', 'bar'); } pipeline.exec(function (err, results) { // `err` is always null, and `results` is an array of responses // corresponding the sequence the commands where queued. // Each response follows the format `[err, result]`. var end = new Date(); var elapsedTime = end - start; console.log('Elapsed time: ' + elapsedTime + 'ms'); console.log('Commands per second: ' + Math.round(N * 1000 / elapsedTime)); redis.disconnect(); });
"use strict"; var Redis = require('ioredis'); var start = new Date(); // I can't get to 1,000,000 commands in one pipeline, not even to 120,000, because ioredis would just hang. // Therefore I use 100,000 and hope that this is precise enough. var N = 100*1000; var redis = new Redis(); redis.del("foo"); var pipeline = redis.pipeline(); for(var i = 0; i < N; i++) { pipeline.set('foo', 'bar'); } pipeline.exec(function (err, results) { // `err` is always null, and `results` is an array of responses // corresponding the sequence the commands where queued. // Each response follows the format `[err, result]`. var end = new Date(); var elapsedTime = end - start; console.log("Elapsed time: " + elapsedTime + "ms"); console.log("Commands per second: " + Math.round(N * 1000 / elapsedTime)); redis.disconnect(); });
Modify event listener should implement modify method with ItemPipelineEvent parameter in order to be able to stop propagation.
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <info@nfq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\ConnectionsBundle\EventListener; use ONGR\ConnectionsBundle\Pipeline\Item\AbstractImportItem; use ONGR\ConnectionsBundle\Log\EventLoggerAwareTrait; use ONGR\ConnectionsBundle\Pipeline\Event\ItemPipelineEvent; use Psr\Log\LoggerAwareInterface; use Psr\Log\LogLevel; /** * AbstractImportModifyEventListener - assigns data from entity to document. */ abstract class AbstractImportModifyEventListener implements LoggerAwareInterface { use EventLoggerAwareTrait; /** * Modify event. * * @param ItemPipelineEvent $event */ public function onModify(ItemPipelineEvent $event) { $item = $event->getItem(); if ($item instanceof AbstractImportItem) { $this->modify($item, $event); } else { $this->log('Item provided is not an AbstractImportItem', LogLevel::NOTICE); } } /** * Assigns raw data to given object. * * @param AbstractImportItem $eventItem * @param ItemPipelineEvent $event */ abstract protected function modify(AbstractImportItem $eventItem, ItemPipelineEvent $event); }
<?php /* * This file is part of the ONGR package. * * (c) NFQ Technologies UAB <info@nfq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\ConnectionsBundle\EventListener; use ONGR\ConnectionsBundle\Pipeline\Item\AbstractImportItem; use ONGR\ConnectionsBundle\Log\EventLoggerAwareTrait; use ONGR\ConnectionsBundle\Pipeline\Event\ItemPipelineEvent; use Psr\Log\LoggerAwareInterface; use Psr\Log\LogLevel; /** * AbstractImportModifyEventListener - assigns data from entity to document. */ abstract class AbstractImportModifyEventListener implements LoggerAwareInterface { use EventLoggerAwareTrait; /** * Modify event. * * @param ItemPipelineEvent $event */ public function onModify(ItemPipelineEvent $event) { $item = $event->getItem(); if ($item instanceof AbstractImportItem) { $this->modify($item); } else { $this->log('Item provided is not an AbstractImportItem', LogLevel::NOTICE); } } /** * Assigns raw data to given object. * * @param AbstractImportItem $eventItem */ abstract protected function modify(AbstractImportItem $eventItem); }
Update Encode documentation for golint.
package utilities import ( "errors" "unicode/utf8" ) // The string encoding options. Currently only support UTF-8. Don't really // see the merit in supporting anything else at the moment. const ( UTF8 = iota ) // ErrInvalidEncodingType is returned when the encoding type is not one that // is supported. var ErrInvalidEncodingType = errors.New("sdbot/utilities: invalid string encoding type") // Encode returns a strings that is encoded in the provided encoding // type. If the encoding type is invalid then we return the original string, // but also return an error. func Encode(s string, encoding int) (string, error) { switch encoding { case UTF8: if !utf8.ValidString(s) { v := make([]rune, 0, len(s)) for i, r := range s { if r == utf8.RuneError { _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { continue } } v = append(v, r) } s = string(v) } return s, nil default: return s, ErrInvalidEncodingType } }
package utilities import ( "errors" "unicode/utf8" ) // The string encoding options. Currently only support UTF-8. Don't really // see the merit in supporting anything else at the moment. const ( UTF8 = iota ) // ErrInvalidEncodingType is returned when the encoding type is not one that // is supported. var ErrInvalidEncodingType = errors.New("sdbot/utilities: invalid string encoding type") // EncodeIncoming returns a strings that is encoded in the provided encoding // type. If the encoding type is invalid then we return the original string, // but also return an error. func Encode(s string, encoding int) (string, error) { switch encoding { case UTF8: if !utf8.ValidString(s) { v := make([]rune, 0, len(s)) for i, r := range s { if r == utf8.RuneError { _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { continue } } v = append(v, r) } s = string(v) } return s, nil default: return s, ErrInvalidEncodingType } }
Make the AB test case more stable.
from . import TheInternetTestCase from helium.api import go_to, S, get_driver class AbTestingTest(TheInternetTestCase): def get_page(self): return "http://the-internet.herokuapp.com/abtest" def test_ab_variates(self): header = S("h3") first_variation = header.web_element.text self.assertIn( first_variation, [u"A/B Test Variation 1", u"A/B Test Control"] ) second_variation = first_variation while second_variation == first_variation: get_driver().delete_all_cookies() go_to("http://the-internet.herokuapp.com/abtest") header = S("h3") second_variation = header.web_element.text self.assertIn( second_variation, [u"A/B Test Variation 1", u"A/B Test Control"] ) self.assertNotEqual(first_variation, second_variation)
from . import TheInternetTestCase from helium.api import go_to, S, get_driver class AbTestingTest(TheInternetTestCase): def get_page(self): return "http://the-internet.herokuapp.com/abtest" def test_ab_variates(self): variation = S("h3") first_variation = variation.web_element.text self.assertIn( first_variation, [u"A/B Test Variation 1", u"A/B Test Control"] ) get_driver().delete_all_cookies() go_to("http://the-internet.herokuapp.com/abtest") variation = S("h3") second_variation = variation.web_element.text self.assertIn( second_variation, [u"A/B Test Variation 1", u"A/B Test Control"] ) self.assertNotEqual(first_variation, second_variation)
Add a register method and a getRegister Method
package info.u_team.u_team_core.util.registry; import java.util.function.Supplier; import net.minecraft.entity.*; import net.minecraft.entity.EntityType.Builder; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.ForgeRegistries; public class EntityTypeDeferredRegister { public static EntityTypeDeferredRegister create(String modid) { return new EntityTypeDeferredRegister(modid); } private final CommonDeferredRegister<EntityType<?>> register; protected EntityTypeDeferredRegister(String modid) { register = CommonDeferredRegister.create(ForgeRegistries.ENTITIES, modid); } public <E extends Entity, B extends Builder<E>> RegistryObject<EntityType<E>> register(String name, Supplier<? extends B> supplier) { return register.register(name, () -> supplier.get().build(register.getModid() + ":" + name)); } public void register(IEventBus bus) { register.register(bus); } public CommonDeferredRegister<EntityType<?>> getRegister() { return register; } }
package info.u_team.u_team_core.util.registry; import java.util.function.Supplier; import net.minecraft.entity.*; import net.minecraft.entity.EntityType.Builder; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.ForgeRegistries; public class EntityTypeDeferredRegister { public static EntityTypeDeferredRegister create(String modid) { return new EntityTypeDeferredRegister(modid); } private final CommonDeferredRegister<EntityType<?>> register; protected EntityTypeDeferredRegister(String modid) { register = CommonDeferredRegister.create(ForgeRegistries.ENTITIES, modid); } public <E extends Entity, B extends Builder<E>> RegistryObject<EntityType<E>> register(String name, Supplier<? extends B> supplier) { return register.register(name, () -> supplier.get().build(register.getModid() + ":" + name)); } }
Use storage sub-namespace for generic annex
from .base import AnnexBase from . import utils __all__ = ('Annex',) # ----------------------------------------------------------------------------- def get_annex_class(storage): if storage == 'file': from .file import FileAnnex return FileAnnex else: raise ValueError("unsupported storage {}".format(storage)) # ----------------------------------------------------------------------------- class Annex(AnnexBase): def __init__(self, storage, **kwargs): annex_class = get_annex_class(storage) # Proxy the actual implementation to prevent use of storage-specific # attributes when using the generic annex. self._impl = annex_class(**kwargs) @classmethod def from_env(cls, namespace): storage = utils.get_config_from_env(namespace)['storage'] # Use storage-specific env namespace when configuring a generic annex, # to avoid having unrecognized extra keys when changing storage. storage_namespace = '{}_{}'.format(namespace, storage.upper()) storage_config = utils.get_config_from_env(storage_namespace) return cls(storage, **storage_config) def save_file(self, key, filename): return self._impl.save_file(key, filename) def send_file(self, key, **options): return self._impl.send_file(key, **options)
from .base import AnnexBase __all__ = ('Annex',) # ----------------------------------------------------------------------------- def get_annex_class(storage): if storage == 'file': from .file import FileAnnex return FileAnnex else: raise ValueError("unsupported storage {}".format(storage)) # ----------------------------------------------------------------------------- class Annex(AnnexBase): def __init__(self, storage, **kwargs): annex_class = get_annex_class(storage) # Proxy the actual implementation to prevent use of storage-specific # attributes when using the generic annex. self._impl = annex_class(**kwargs) def save_file(self, key, filename): return self._impl.save_file(key, filename) def send_file(self, key, **options): return self._impl.send_file(key, **options)
Add solution to problem 70
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.problem70; /** * Given an integer passed as parameter, can you write a method to return the number equivalent to * the binary number with the reversed order? * * For example: * * Input = 5 = 101 * Output = 5 = 101 * * Input = 13 = 1101 * Output = 11 = 1011 * * @author Pedro Vicente Gómez Sánchez. */ public class ReverseOrderOfBinaryNumber { /** * Iterative algorithm to solve this problem. Shifting the input number until the value is equals * to zero and applying a simple mask we are going to create the reverted order binary number * using a constant complexity time in space terms O(1) and a linear complexity order in time * terms O(N) where N is equals to the number of digits of the input parameter into a binary * representation. */ public int reverse(int number) { int result = 0; while (number != 0) { result <<= 1; result |= number & 1; number >>= 1; } return result; } }
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.problem70; /** * Given an integer passed as parameter, can you write a method to return the number equivalent to * the binary number with the reversed order? * * For example: * * Input = 5 = 101 * Output = 5 = 101 * * Input = 13 = 1101 * Output = 11 = 1011 * * @author Pedro Vicente Gómez Sánchez. */ public class ReverseOrderOfBinaryNumber { }
Fix CORS allowed origin typo.
import express from 'express'; import leagueTips from 'league-tooltips'; import runTask from './cronTask'; import taskGenerator from './cronTasks/generator'; import config from './config'; import routes from './routes'; // ==== Server ==== const app = express(); app.use(leagueTips(config.key.riot, 'euw', { url: '/tooltips', fileName: 'league-tips.min.js', protocol: 'https', cors: { origin: 'https://lol-item-sets-generator.org', methods: 'GET', headers: 'Content-Type' } })); app.use('/sprites', routes.sprites); app.use('/tooltips', routes.tooltips); app.use('/', routes.index); app.listen(config.port, () => { console.log('[SERVER] Listening on port ' + config.port); }); // ==== Generator ==== const version = require('../package.json').version; console.log(`[GENERATOR] Generator version : ${version}.`); runTask(taskGenerator, config.cron);
import express from 'express'; import leagueTips from 'league-tooltips'; import runTask from './cronTask'; import taskGenerator from './cronTasks/generator'; import config from './config'; import routes from './routes'; // ==== Server ==== const app = express(); app.use(leagueTips(config.key.riot, 'euw', { url: '/tooltips', fileName: 'league-tips.min.js', protocol: 'https', cors: { origin: 'https://lol-item-sets-generator.org/', methods: 'GET', headers: 'Content-Type' } })); app.use('/sprites', routes.sprites); app.use('/tooltips', routes.tooltips); app.use('/', routes.index); app.listen(config.port, () => { console.log('[SERVER] Listening on port ' + config.port); }); // ==== Generator ==== const version = require('../package.json').version; console.log(`[GENERATOR] Generator version : ${version}.`); runTask(taskGenerator, config.cron);
Remove double quote characters when producing default SQL query.
/* * Copyright 2014 Josef Hardi <josef.hardi@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.johardi.r2rmlparser.document; public class SqlBaseTableOrView implements ITableView { private String mTableOrViewName; public void setBaseTable(String tableOrViewName) { mTableOrViewName = tableOrViewName; } /** * Returns the value specified by <code>rr:tableName</code> property. */ public String getBaseTable() { return mTableOrViewName; } @Override public String getSqlQuery() { return String.format("SELECT * FROM %s", mTableOrViewName); } }
/* * Copyright 2014 Josef Hardi <josef.hardi@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.johardi.r2rmlparser.document; public class SqlBaseTableOrView implements ITableView { private String mTableOrViewName; public void setBaseTable(String tableOrViewName) { mTableOrViewName = tableOrViewName; } /** * Returns the value specified by <code>rr:tableName</code> property. */ public String getBaseTable() { return mTableOrViewName; } @Override public String getSqlQuery() { return String.format("SELECT * FROM \"%s\"", mTableOrViewName); } }
Allow a commond replSetName for all shards
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.packaging.config.validation; import com.torodb.packaging.config.model.protocol.mongo.AbstractReplication; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class MutualExclusiveReplSetOrShardsValidator implements ConstraintValidator<MutualExclusiveReplSetOrShards, AbstractReplication<?>> { @Override public void initialize(MutualExclusiveReplSetOrShards constraintAnnotation) { } @Override public boolean isValid(AbstractReplication<?> value, ConstraintValidatorContext context) { if ((value.getShardList() != null && !value.getShardList().isEmpty()) && value.getSyncSource().notDefault()) { return false; } return true; } }
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.packaging.config.validation; import com.torodb.packaging.config.model.protocol.mongo.AbstractReplication; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class MutualExclusiveReplSetOrShardsValidator implements ConstraintValidator<MutualExclusiveReplSetOrShards, AbstractReplication> { @Override public void initialize(MutualExclusiveReplSetOrShards constraintAnnotation) { } @Override public boolean isValid(AbstractReplication value, ConstraintValidatorContext context) { if ((value.getShardList() != null && !value.getShardList().isEmpty()) && (value.getReplSetName().notDefault() || value.getSyncSource().notDefault())) { return false; } return true; } }
Use TCX coordinates to fetch local weather
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser t = '1984-06-02T19:05:00.000Z' # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky', 'key') tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx') run_time = tcx.completed_at def convert_time_to_unix(time): parsed_time = dateutil.parser.parse(time) time_in_unix = parsed_time.strftime('%s') return time_in_unix unix_run_time = convert_time_to_unix(run_time) darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/" + str(tcx.latitude) + "," + str(tcx.longitude) + "," + unix_run_time + "?exclude=currently,flags").read() print(darksky_request) class getWeather: def __init__(self, date, time): self.date = date self.time = time def goodbye(self, date): print("my name is " + date)
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser t = '1984-06-02T19:05:00.000Z' # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky', 'key') tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx') run_time = tcx.completed_at def convert_time_to_unix(time): parsed_time = dateutil.parser.parse(time) time_in_unix = parsed_time.strftime('%s') return time_in_unix unix_run_time = convert_time_to_unix(run_time) darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/42.3601,-71.0589," + unix_run_time + "?exclude=currently,flags").read() print(darksky_request) class getWeather: def __init__(self, date, time): self.date = date self.time = time def goodbye(self, date): print("my name is " + date)
Use the platform() in sublime.py rather than importing platform.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2015 jfcherng # # License: MIT # import sublime, sublime_plugin from SublimeLinter.lint import Linter, util class Iverilog (Linter): syntax = ('verilog') cmd = 'iverilog -t null' tempfile_suffix = 'verilog' # We are missing out on some errors by ignoring multiline messages. if sublime.platform() == 'windows': regex = ( r'^([^:]+):.*:(?P<line>\d*):' r'.((?P<error>error)|(?P<warning>warning))?' r'(?P<message>.*)' ) else: regex = ( r'^([^:]+):(?P<line>\d+): ' r'(?:(?P<error>error)|(?P<warning>warning): )?' r'(?P<message>.+)' ) error_stream = util.STREAM_BOTH
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2015 jfcherng # # License: MIT # from SublimeLinter.lint import Linter, util import platform class Iverilog (Linter): syntax = ('verilog') cmd = 'iverilog -t null' tempfile_suffix = 'verilog' # We are missing out on some errors by ignoring multiline messages. if platform.system() == 'Windows': regex = ( r'^([^:]+):.*:(?P<line>\d*):' r'.((?P<error>error)|(?P<warning>warning))?' r'(?P<message>.*)' ) else: regex = ( r'^([^:]+):(?P<line>\d+): ' r'(?:(?P<error>error)|(?P<warning>warning): )?' r'(?P<message>.+)' ) error_stream = util.STREAM_BOTH
Update output to render HTML Fixes #2
@if (Session::has('flashNotification.message')) @if (Session::has('flashNotification.modal')) @include('partials.modal', ['modalClass' => 'flashModal', 'title' => 'Notice', 'body' => Session::get('flashNotification.message')]) @else <div class="notification {{ Session::get('flashNotification.level') }}"> <div class="alert alert-dismissable alert-{{ Session::get('flashNotification.level') }}"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button> <p>{!! session('flashNotification.message') !!}</p> </div> </div> @endif @if (Session::get('flashNotification.autoHide')) <script> window.setTimeout(function() { $(".notification.success").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); }, 5000); window.setTimeout(function() { $(".notification.info").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); $(".notification.message").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); }, 10000); </script> @endif <?php Session::forget('flashNotification.message'); Session::forget('flashNotification.modal'); Session::forget('flashNotification.autoHide'); ?> @endif
@if (Session::has('flashNotification.message')) @if (Session::has('flashNotification.modal')) @include('partials.modal', ['modalClass' => 'flashModal', 'title' => 'Notice', 'body' => Session::get('flashNotification.message')]) @else <div class="notification {{ Session::get('flashNotification.level') }}"> <div class="alert alert-dismissable alert-{{ Session::get('flashNotification.level') }}"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button> <p>{{ Session::get('flashNotification.message') }}</p> </div> </div> @endif @if (Session::get('flashNotification.autoHide')) <script> window.setTimeout(function() { $(".notification.success").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); }, 5000); window.setTimeout(function() { $(".notification.info").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); $(".notification.message").fadeTo(750, 0).slideUp(750, function() { $(this).remove(); }); }, 10000); </script> @endif <?php Session::forget('flashNotification.message'); Session::forget('flashNotification.modal'); Session::forget('flashNotification.autoHide'); ?> @endif
docs: Fix simple typo, ussage -> usage There is a small typo in magicembed/templatetags/magicembed_tags.py. Should read `usage` rather than `ussage`.
# -*- coding: utf-8 -*- from django import template from django.utils.safestring import mark_safe from magicembed.providers import get_provider register = template.Library() @register.filter(is_safe=True) def magicembed(value, arg=None): '''value is the url and arg the size tuple usage: {% http://myurl.com/|magicembed:"640x480" %}''' arg = [int(item) for item in arg.split('x')] provider = get_provider(value, arg) return mark_safe(provider.render_video()) @register.filter def magicthumbnail(value): '''value is the url and arg the link_to another url usage: {% http://myurl.com/|magicthumbnail: '/some/url' %}''' provider = get_provider(value) return provider.render_thumbnail()
# -*- coding: utf-8 -*- from django import template from django.utils.safestring import mark_safe from magicembed.providers import get_provider register = template.Library() @register.filter(is_safe=True) def magicembed(value, arg=None): '''value is the url and arg the size tuple ussage: {% http://myurl.com/|magicembed:"640x480" %}''' arg = [int(item) for item in arg.split('x')] provider = get_provider(value, arg) return mark_safe(provider.render_video()) @register.filter def magicthumbnail(value): '''value is the url and arg the link_to another url ussage: {% http://myurl.com/|magicthumbnail: '/some/url' %}''' provider = get_provider(value) return provider.render_thumbnail()
Fix send email logging: return string instead of Mongo ObjectID
'use strict'; var _ = require('lodash'), nodemailer = require('nodemailer'), path = require('path'), config = require(path.resolve('./config/config')), log = require(path.resolve('./config/lib/logger')); module.exports = function(job, done) { var smtpTransport = nodemailer.createTransport(config.mailer.options); // Get job id from Agenda job attributes // Agenda stores Mongo `ObjectId` so turning that into a string here var jobId = _.get(job, 'attrs._id').toString(); // Log that we're sending an email log('debug', 'Starting `send email` job #wGcxmQ', { jobId: jobId }); smtpTransport.sendMail(job.attrs.data, function(err) { smtpTransport.close(); // close the connection pool if (err) { // Log the failure to send the message log('error', 'The `send email` job failed #VDKMbr', { jobId: jobId, error: err }); return done(err); } else { // Log the successful delivery of the message log('info', 'Successfully finished `send email` job #4vO5Vt', { jobId: jobId }); return done(); } }); };
'use strict'; var _ = require('lodash'), nodemailer = require('nodemailer'), path = require('path'), config = require(path.resolve('./config/config')), log = require(path.resolve('./config/lib/logger')); module.exports = function(job, done) { var smtpTransport = nodemailer.createTransport(config.mailer.options); // The agenda docs don't show the shape of `job` so we're guessing here... var jobId = _.get(job, 'attrs._id'); // Log that we're sending an email log('debug', 'Starting `send email` job #wGcxmQ', { jobId: jobId }); smtpTransport.sendMail(job.attrs.data, function(err) { smtpTransport.close(); // close the connection pool if (err) { // Log the failure to send the message log('error', 'The `send email` job failed #VDKMbr', { jobId: jobId, error: err }); return done(err); } else { // Log the successful delivery of the message log('info', 'Successfully finished `send email` job #4vO5Vt', { jobId: jobId }); return done(); } }); };
Load orgs inside location promise
import React, { Component } from 'react' import globalConfig from '../../config' import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import Location from '../../components/Location' export default class LocationPage extends Component { constructor(props) { super(props) this.state = { location: null, organization: null, } } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const locationId = match[1] fetchLocation(locationId) .then(location => { this.setState({ location }) fetchOrganization(location.organizationId) .then(organization => { this.setState({ organization }) }) }) } componentDidUpdate() { const { location } = this.state document.title = location ? location.name : globalConfig.title } render() { const { location, organization } = this.state return ( <Layout> {(location && organization) ? <Location location={location} organization={organization} /> : <Loading /> } </Layout> ) } }
import React, { Component } from 'react' import globalConfig from '../../config' import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import Location from '../../components/Location' export default class LocationPage extends Component { constructor(props) { super(props) this.state = { location: null, organization: null, } } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const locationId = match[1] fetchLocation(locationId) .then(location => { this.setState({ location }) }) fetchOrganization(location.organizationId) .then(organization => { this.setState({ organization }) }) } componentDidUpdate() { const { location } = this.state document.title = location ? location.name : globalConfig.title } render() { const { location, organization } = this.state return ( <Layout> {(location && organization) ? <Location location={location} organization={organization} /> : <Loading /> } </Layout> ) } }
Remove .render() - JSTransformer should do that
/** * jstransformer-toffee <https://github.com/jstransformers/jstransformer-toffee> * * Copyright (c) 2015 Charlike Mike Reagent, contributors. * Released under the MIT license. */ 'use strict'; var fs = require('fs'); var path = require('path'); var lodash = { template: require('lodash.template'), mixin: require('lodash.mixin'), assign: require('lodash.assign'), omit: require('lodash.omit') }; exports.name = 'lodash'; exports.inputFormats = ['lodash', 'html']; exports.outputFormat = 'html'; exports.compile = function _compile(str, options) { if (options.mixins) { Object.keys(options.mixins).forEach(function(key) { var value = options.mixins[key]; var mixin = {}; mixin[key] = value; lodash.mixin(mixin); }) } options = lodash.omit(options, ['mixins']); var compile = lodash.template(str, options); var context = lodash.omit(options, ['imports']); return function(locals) { context = lodash.assign(context, locals); return compile(context); }; };
/** * jstransformer-toffee <https://github.com/jstransformers/jstransformer-toffee> * * Copyright (c) 2015 Charlike Mike Reagent, contributors. * Released under the MIT license. */ 'use strict'; var fs = require('fs'); var path = require('path'); var lodash = { template: require('lodash.template'), mixin: require('lodash.mixin'), assign: require('lodash.assign'), omit: require('lodash.omit') }; exports.name = 'lodash'; exports.inputFormats = ['lodash', 'html']; exports.outputFormat = 'html'; exports.compile = function _compile(str, options) { if (options.mixins) { Object.keys(options.mixins).forEach(function(key) { var value = options.mixins[key]; var mixin = {}; mixin[key] = value; lodash.mixin(mixin); }) } options = lodash.omit(options, ['mixins']); var compile = lodash.template(str, options); var context = lodash.omit(options, ['imports']); return function(locals) { context = lodash.assign(context, locals); return compile(context); }; }; exports.render = function _render(str, options, locals) { var compile = exports.compile(str, options); return compile(locals); }
Use toDouble() method to convert values.
/* * Copyright (C) 2013 Conductor, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.opentsdb.contrib.tsquare.support; import java.util.Iterator; import net.opentsdb.core.Aggregator.Doubles; import net.opentsdb.core.DataPoint; import net.opentsdb.core.DataPoints; /** * Wraps a {@link DataPoints} object and exposes the data consistent * with the {@link Doubles} interface. * * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i> */ public class DataPointsAsDoubles implements Doubles { private final Iterator<DataPoint> iterator; public DataPointsAsDoubles(final DataPoints points) { this.iterator = points.iterator(); } @Override public boolean hasNextValue() { return iterator.hasNext(); } @Override public double nextDoubleValue() { return iterator.next().toDouble(); } }
/* * Copyright (C) 2013 Conductor, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.opentsdb.contrib.tsquare.support; import java.util.Iterator; import net.opentsdb.core.Aggregator.Doubles; import net.opentsdb.core.DataPoint; import net.opentsdb.core.DataPoints; /** * Wraps a {@link DataPoints} object and exposes the data consistent * with the {@link Doubles} interface. * * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i> */ public class DataPointsAsDoubles implements Doubles { private final Iterator<DataPoint> iterator; public DataPointsAsDoubles(final DataPoints points) { this.iterator = points.iterator(); } @Override public boolean hasNextValue() { return iterator.hasNext(); } @Override public double nextDoubleValue() { return iterator.next().doubleValue(); } }
Fix raw ender buckets not creating full fluid blocks in the world
package squeek.veganoption.blocks; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fluids.BlockFluidFinite; import net.minecraftforge.fluids.Fluid; public class BlockRawEnder extends BlockFluidFinite { public static Material materialRawEnder = Material.WATER; public BlockRawEnder(Fluid fluid) { super(fluid, materialRawEnder); this.setDefaultState(blockState.getBaseState().withProperty(LEVEL, 7)); } @Override public boolean canDisplace(IBlockAccess world, BlockPos pos) { //if (world.getBlock(x, y, z).getMaterial().isLiquid()) // return false; return super.canDisplace(world, pos); } @Override public boolean displaceIfPossible(World world, BlockPos pos) { //if (world.getBlock(x, y, z).getMaterial().isLiquid()) // return false; return super.displaceIfPossible(world, pos); } }
package squeek.veganoption.blocks; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fluids.BlockFluidFinite; import net.minecraftforge.fluids.Fluid; public class BlockRawEnder extends BlockFluidFinite { public static Material materialRawEnder = Material.WATER; public BlockRawEnder(Fluid fluid) { super(fluid, materialRawEnder); } @Override public boolean canDisplace(IBlockAccess world, BlockPos pos) { //if (world.getBlock(x, y, z).getMaterial().isLiquid()) // return false; return super.canDisplace(world, pos); } @Override public boolean displaceIfPossible(World world, BlockPos pos) { //if (world.getBlock(x, y, z).getMaterial().isLiquid()) // return false; return super.displaceIfPossible(world, pos); } }
Add type and id to script tag The current script tag recommended by inspectlet contains an ID and the type specified. I don't think it makes too much difference but I think it is interesting to keep the script tag as close as possible of what is recommended by inspectlet =D
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inspectlet', contentFor: function(type, config) { var wid = config.APP.INSPECTLET_WID; if (wid != null && type === 'head') { return "<script type='text/javascript' id='inspectletjs'>\n" + "window.__insp = window.__insp || [];\n" + "__insp.push(['wid', " + wid + "]);\n" + "(function() {\n" + "function ldinsp(){if(typeof window.__inspld != 'undefined') return; window.__inspld = 1; var insp = document.createElement('script'); insp.type = 'text/javascript'; insp.async = true; insp.id = 'inspsync'; insp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://cdn.inspectlet.com/inspectlet.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(insp, x); };\n" + " setTimeout(ldinsp, 500); document.readyState != 'complete' ? (window.attachEvent ? window.attachEvent('onload', ldinsp) : window.addEventListener('load', ldinsp, false)) : ldinsp();\n" + "})();" + "</script>" } } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inspectlet', contentFor: function(type, config) { var wid = config.APP.INSPECTLET_WID; if (wid != null && type === 'head') { return "<script>\n" + "window.__insp = window.__insp || [];\n" + "__insp.push(['wid', " + wid + "]);\n" + "(function() {\n" + "function ldinsp(){if(typeof window.__inspld != 'undefined') return; window.__inspld = 1; var insp = document.createElement('script'); insp.type = 'text/javascript'; insp.async = true; insp.id = 'inspsync'; insp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://cdn.inspectlet.com/inspectlet.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(insp, x); };\n" + " setTimeout(ldinsp, 500); document.readyState != 'complete' ? (window.attachEvent ? window.attachEvent('onload', ldinsp) : window.addEventListener('load', ldinsp, false)) : ldinsp();\n" + "})();" + "</script>" } } };
Use string representation of object when formatting error messages
'use strict'; exports.formatStr = function () { var args = Array.prototype.slice.call(arguments) , str = args.shift() , i = 0; return str.replace(/\{([0-9]*)\}/g, function (m, argI) { argI = argI || i; i += 1; return String(args[argI]); }); }; exports.stringListJoin = function (arr) { if (arr.length === 1) { return arr[0]; } if (arr.length === 2) { return arr.join(' and '); } if (arr.length >= 3) { return arr.slice(0, arr.length - 1).join(', ') + ', and ' + arr[arr.length - 1]; } }; exports.cloneObj = function (obj) { if (Object(obj) === obj) { var prop, clone = obj instanceof RegExp ? new RegExp(obj) : new obj.constructor(); for (prop in obj) { if (obj.hasOwnProperty(prop)) { clone[prop] = obj[prop]; } } return clone; } return obj; // Object must be basic type (String, Number, Boolean, Undefined or Null) };
'use strict'; exports.formatStr = function () { var args = Array.prototype.slice.call(arguments) , str = args.shift() , i = 0; return str.replace(/\{([0-9]*)\}/g, function (m, argI) { argI = argI || i; i += 1; return typeof(args[argI]) !== 'undefined' ? args[argI] : ''; }); }; exports.stringListJoin = function (arr) { if (arr.length === 1) { return arr[0]; } if (arr.length === 2) { return arr.join(' and '); } if (arr.length >= 3) { return arr.slice(0, arr.length - 1).join(', ') + ', and ' + arr[arr.length - 1]; } }; exports.cloneObj = function (obj) { if (Object(obj) === obj) { var prop, clone = obj instanceof RegExp ? new RegExp(obj) : new obj.constructor(); for (prop in obj) { if (obj.hasOwnProperty(prop)) { clone[prop] = obj[prop]; } } return clone; } return obj; // Object must be basic type (String, Number, Boolean, Undefined or Null) };
Add condition to only launch updater if -u or --updater is specified
import os import sys import time from multiprocessing import Process, Event import mfhclient import update from arguments import parse from settings import HONEYPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfhclient_process", target=mfhclient.main, ) if args.client is not None: mfhclient_process.start() if args.updater: trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive(): time.sleep(5) else: if args.updater: update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT main()
import os import sys import time from multiprocessing import Process, Event import mfhclient import update from arguments import parse from settings import HONEYPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfhclient_process", target=mfhclient.main, ) if args.client is not None: mfhclient_process.start() trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive(): time.sleep(5) else: update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT main()
Set the download link to the current version of django-request, not latest git.
#!/usr/bin/env python from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__, packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
#!/usr/bin/env python from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/master', packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Modify to handle ARtool output
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("}") itemset = tokens[0][1:-1] frequency = float((tokens[1].split(" "))[0][2:-3]) results.append((itemset + "\t" + str(frequency)+"\n", frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("\t") frequency = float(tokens[1]) results.append((line, frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
Fix relative import for py3
from __future__ import unicode_literals import datetime from django.http import HttpResponse, HttpResponseBadRequest from django.core.exceptions import ValidationError from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from . import models import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST @csrf_exempt def badge_issued_hook(request): # TODO validate Authorization header try: data = json.loads(request.body.decode(request.encoding or 'utf-8')) expected_keys = set(['action', 'uid', 'email', 'assertionUrl', 'issuedOn']) if type(data) != dict or set(data.keys()) != expected_keys: return HttpResponseBadRequest("Unexpected or Missing Fields") data['issuedOn'] = datetime.datetime.fromtimestamp(data['issuedOn']) del data['action'] obj = models.BadgeInstanceNotification.objects.create(**data) obj.full_clean() # throws ValidationError if fields are bad. obj.save() except (ValueError, TypeError, ValidationError) as e: return HttpResponseBadRequest("Bad JSON request: %s" % e.message) return HttpResponse(json.dumps({"status": "ok"}), content_type="application/json")
from __future__ import unicode_literals import datetime from django.http import HttpResponse, HttpResponseBadRequest from django.core.exceptions import ValidationError from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import models import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST @csrf_exempt def badge_issued_hook(request): # TODO validate Authorization header try: data = json.loads(request.body.decode(request.encoding or 'utf-8')) expected_keys = set(['action', 'uid', 'email', 'assertionUrl', 'issuedOn']) if type(data) != dict or set(data.keys()) != expected_keys: return HttpResponseBadRequest("Unexpected or Missing Fields") data['issuedOn'] = datetime.datetime.fromtimestamp(data['issuedOn']) del data['action'] obj = models.BadgeInstanceNotification.objects.create(**data) obj.full_clean() # throws ValidationError if fields are bad. obj.save() except (ValueError, TypeError, ValidationError) as e: return HttpResponseBadRequest("Bad JSON request: %s" % e.message) return HttpResponse(json.dumps({"status": "ok"}), content_type="application/json")
Fix checking against null, supposed to be NO_USER
package co.phoenixlab.discord.commands; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.api.entities.User; public class CommandUtil { static User findUser(MessageContext context, String username) { Message message = context.getMessage(); User user; Channel channel = context.getApiClient().getChannelById(message.getChannelId()); // Attempt to find the given user // If the user is @mentioned, try that first if (message.getMentions() != null && message.getMentions().length > 0) { user = message.getMentions()[0]; } else { user = context.getApiClient().findUser(username, channel.getParent()); } // Try matching by ID if (user == DiscordApiClient.NO_USER) { user = context.getApiClient().getUserById(username); } return user; } }
package co.phoenixlab.discord.commands; import co.phoenixlab.discord.MessageContext; import co.phoenixlab.discord.api.entities.Channel; import co.phoenixlab.discord.api.entities.Message; import co.phoenixlab.discord.api.entities.User; public class CommandUtil { static User findUser(MessageContext context, String username) { Message message = context.getMessage(); User user; Channel channel = context.getApiClient().getChannelById(message.getChannelId()); // Attempt to find the given user // If the user is @mentioned, try that first if (message.getMentions() != null && message.getMentions().length > 0) { user = message.getMentions()[0]; } else { user = context.getApiClient().findUser(username, channel.getParent()); } // Try matching by ID if (user == null) { user = context.getApiClient().getUserById(username); } return user; } }
Fix broken key generation code
package org.cru.godtools.s3; import com.google.common.base.Strings; /** * Created by ryancarlson on 7/11/15. */ public class AmazonS3GodToolsConfig { public static final String BUCKET_NAME = "cru-godtools"; private static final String META = "meta/"; private static final String PACKAGES = "packages/"; private static final String LANGUAGES = "languages/"; private static final String META_FILE = "meta"; private static final String ALL = "all/"; private static final String CURRENT = "current/"; private static final String XML = ".xml"; private static final String ZIP = ".zip"; public static String getMetaKey(String languageCode, String packageCode) { if(!Strings.isNullOrEmpty(languageCode) && !Strings.isNullOrEmpty(packageCode)) { return META + CURRENT + languageCode + "/" + packageCode + "/" + META_FILE + XML; } if(!Strings.isNullOrEmpty(languageCode)) { return META + CURRENT + languageCode + "/" + META_FILE + XML; } return META + CURRENT + META_FILE + XML; } public static String getPackagesKey(String languageCode, String packageCode) { return PACKAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP; } public static String getLanguagesKey(String languageCode, String packagesCode) { return LANGUAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP; } }
package org.cru.godtools.s3; import com.google.common.base.Strings; /** * Created by ryancarlson on 7/11/15. */ public class AmazonS3GodToolsConfig { public static final String BUCKET_NAME = "cru-godtools"; private static final String META = "meta"; private static final String PACKAGES = "packages/"; private static final String LANGUAGES = "languages/"; private static final String ALL = "all/"; private static final String CURRENT = "current/"; private static final String XML = ".XML"; private static final String ZIP = ".ZIP"; public static String getMetaKey(String languageCode, String packageCode) { if(!Strings.isNullOrEmpty(languageCode) && !Strings.isNullOrEmpty(packageCode)) { return META + CURRENT + languageCode + "/" + packageCode + "/" + META + XML; } if(!Strings.isNullOrEmpty(languageCode)) { return META + CURRENT + languageCode + "/" + META + XML; } return META + CURRENT + META + XML; } public static String getPackagesKey(String languageCode, String packageCode) { return PACKAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP; } public static String getLanguagesKey(String languageCode, String packagesCode) { return LANGUAGES + CURRENT + languageCode + "/" + ALL + languageCode + ZIP; } }
Remove wrong reference to quantum Change-Id: Ic3d8b26e061e85c1d128a79b115fd2da4412e705 Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Filter off the port on the mgt network ports = [api.neutron.Port(p) for p in router.ports if p['device_owner'] != 'network:router_management'] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Filter off the port on the mgt network ports = [api.quantum.Port(p) for p in router.ports if p['device_owner'] != 'network:router_management'] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
Fix `register` for 1.13.13 - 2.1 apps Also moved the register function above the call to `beforeEach` so you can register in a tests `beforeEach` if necessary.
import { module } from 'qunit'; import startApp from '../helpers/start-app'; import destroyApp from '../helpers/destroy-app'; export default function(name, options = {}) { module(name, { beforeEach() { this.application = startApp(); // BugFix: Can be removed after 2.1. If resolver is set then fallback doesn't happen properly // for more information: https://github.com/emberjs/ember.js/commit/e3ad9e2772e066459ddb3af78be45d9a6003f5ce var legacyRegistry = this.application.__deprecatedInstance__.registry; if (legacyRegistry) { legacyRegistry.resolver = function noOpResolverBugFix() {}; } this.register = (fullName, Factory) => { let instance = this.application.__deprecatedInstance__; let registry = instance.register ? instance : instance.registry; return registry.register(fullName, Factory); }; if (options.beforeEach) { options.beforeEach.apply(this, arguments); } }, afterEach() { destroyApp(this.application); if (options.afterEach) { options.afterEach.apply(this, arguments); } } }); }
import { module } from 'qunit'; import startApp from '../helpers/start-app'; import destroyApp from '../helpers/destroy-app'; export default function(name, options = {}) { module(name, { beforeEach() { this.application = startApp(); if (options.beforeEach) { options.beforeEach.apply(this, arguments); } this.register = (fullName, Factory) => { let instance = this.application.__deprecatedInstance__; let registry = instance.register ? instance : instance.registry; return registry.register(fullName, Factory); }; }, afterEach() { destroyApp(this.application); if (options.afterEach) { options.afterEach.apply(this, arguments); } } }); }
Remove mixins from namespace after monkey patching After their job is done, they can go home ;-)
# Copyright (c) 2014, German Neuroinformatics Node (G-Node) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. from nix.core import File, FileMode, Block, DataType, Section, Property, Value, \ Source, DataArray, RangeDimension, SetDimension, SampledDimension, \ DimensionType, Feature, LinkType, Tag, MultiTag from nix.block import BlockMixin from nix.file import FileMixin from nix.section import SectionMixin from nix.property import PropertyMixin, ValueMixin from nix.source import SourceMixin from nix.data_array import DataArrayMixin from nix.tag import TagMixin from nix.multi_tag import MultiTagMixin from nix.entity_with_sources import DataArrySourcesMixin, MultiTagSourcesMixin, \ TagSourcesMixin __all__ = ("File", "FileMode", "Block", "DataType", "Section", "Property", "Value", "Source", "DataArray", "RangeDimension", "SetDimension", "SampledDimension", "DimensionType", "Feature", "LinkType", "Tag", "MultiTag") del BlockMixin, FileMixin, SectionMixin, PropertyMixin, ValueMixin, SourceMixin, DataArrayMixin, TagMixin del MultiTagMixin, DataArrySourcesMixin, MultiTagSourcesMixin, TagSourcesMixin __author__ = 'Christian Kellner, Adrian Stoewer, Andrey Sobolev, Jan Grewe, Balint Morvai'
# Copyright (c) 2014, German Neuroinformatics Node (G-Node) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. from nix.core import File, FileMode, Block, DataType, Section, Property, Value, \ Source, DataArray, RangeDimension, SetDimension, SampledDimension, \ DimensionType, Feature, LinkType, Tag, MultiTag from nix.block import BlockMixin from nix.file import FileMixin from nix.section import SectionMixin from nix.property import PropertyMixin, ValueMixin from nix.source import SourceMixin from nix.data_array import DataArrayMixin from nix.tag import TagMixin from nix.multi_tag import MultiTagMixin from nix.entity_with_sources import DataArrySourcesMixin, MultiTagSourcesMixin, \ TagSourcesMixin __all__ = ("File", "FileMode", "Block", "DataType", "Section", "Property", "Value", "Source", "DataArray", "RangeDimension", "SetDimension", "SampledDimension", "DimensionType", "Feature", "LinkType", "Tag", "MultiTag") __author__ = "Christian Kellner"
Change to better argument name
from TestStack.White.UIItems import TextBox from WhiteLibrary.keywords.librarycomponent import LibraryComponent from WhiteLibrary.keywords.robotlibcore import keyword class TextBoxKeywords(LibraryComponent): @keyword def input_text_to_textbox(self, locator, input_value): """ Writes text to a textbox. ``locator`` is the locator of the text box. ``input_value`` is the text to write. """ textBox = self.state._get_typed_item_by_locator(TextBox, locator) textBox.Text = input_value @keyword def verify_text_in_textbox(self, locator, expected): """ Verifies text in a text box. ``locator`` is the locator of the text box. ``expected`` is the expected text of the text box. """ textbox = self.state._get_typed_item_by_locator(TextBox, locator) self.state._verify_value(expected, textbox.Text) @keyword def get_text_from_textbox(self, locator): """ Gets text from text box. ``locator`` is the locator of the text box. """ textbox = self.state._get_typed_item_by_locator(TextBox, locator) return textbox.Text
from TestStack.White.UIItems import TextBox from WhiteLibrary.keywords.librarycomponent import LibraryComponent from WhiteLibrary.keywords.robotlibcore import keyword class TextBoxKeywords(LibraryComponent): @keyword def input_text_to_textbox(self, locator, input): """ Writes text to a textbox. ``locator`` is the locator of the text box. ``input`` is the text to write. """ textBox = self.state._get_typed_item_by_locator(TextBox, locator) textBox.Text = input @keyword def verify_text_in_textbox(self, locator, expected): """ Verifies text in a text box. ``locator`` is the locator of the text box. ``expected`` is the expected text of the text box. """ textbox = self.state._get_typed_item_by_locator(TextBox, locator) self.state._verify_value(expected, textbox.Text) @keyword def get_text_from_textbox(self, locator): """ Gets text from text box. ``locator`` is the locator of the text box. """ textbox = self.state._get_typed_item_by_locator(TextBox, locator) return textbox.Text
Add test to check whether a variable is a number.
// Source: http://stackoverflow.com/a/1830844 function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function AppViewModel() { this.statStrength = ko.observable(); this.statEndurance = ko.observable(); this.statAgility = ko.observable(); this.statSpeed = ko.observable(); this.statWillpower = ko.observable(); this.statInsight = ko.observable(); this.statReasoning = ko.observable(); this.statPerception = ko.observable(); this.statPresence = ko.observable(); this.statComposure = ko.observable(); this.statManipulation = ko.observable(); this.statBeauty = ko.observable(); this.statBonusStrength = ko.computed(function() { return this.statStrength(); }, this); } // Activate knockout.js ko.applyBindings(new AppViewModel());
function AppViewModel() { this.statStrength = ko.observable(); this.statEndurance = ko.observable(); this.statAgility = ko.observable(); this.statSpeed = ko.observable(); this.statWillpower = ko.observable(); this.statInsight = ko.observable(); this.statReasoning = ko.observable(); this.statPerception = ko.observable(); this.statPresence = ko.observable(); this.statComposure = ko.observable(); this.statManipulation = ko.observable(); this.statBeauty = ko.observable(); this.statBonusStrength = ko.computed(function() { return this.statStrength(); }, this); } // Activate knockout.js ko.applyBindings(new AppViewModel());
config: Fix loading of default config values If RawConfigParser is not able to find config using get(), it doesn't return None, instead it raises an Exception. Signed-off-by: Vivek Anand <6cbec6cb1b0c30c91d3fca6c61ddeb9b64cef11c@gmail.com>
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper config file under /etc/autocloud/') default = {'host': '127.0.0.1', 'port': 5000} config = ConfigParser.RawConfigParser(default) config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') PORT = config.getint('autocloud', 'port') DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper config file under /etc/autocloud/') config = ConfigParser.RawConfigParser() config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
Fix up bad last commit
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip() time_to_hundo = time_to_hundo.replace(',', '.') time_to_hundo = float(time_to_hundo) # Points may or may not be present, default to 0 if absent points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract() if not points: points = 0 else: points = int(points[0].strip()) yield { 'title': title, 'time to 100%': time_to_hundo, 'points': points, } def parse_search_result_for_apps(response): for href in response.xpath('//table//table//a/@href'): relative_url = href.extract() if relative_url.startswith('Steam_Game_Info.php?AppID='): yield { 'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):] }
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip() time_to_hundo = time_to_hundo.replace(',', '.') time_to_hundo = float(time_to_hundo) # Points may or may not be present, default to 0 if absent points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract() if not points: points = 0 else: points = int(points[0].strip()) yield { 'title': title, 'time to 100%': time_to_hundo, 'points': points, } def parse_search_result_for_apps(response): for href in response.xpath('//table//table//a/@href'): relative_url = href.extract() if relative_url.startswith('Steam_Game_Info.php?AppID='): yield relative_url[:len('Steam_Game_Info.php?AppID=')]
Test of a vendor repository checkin.
<?php namespace Cerad\Module\AuthModule\Tests; require __DIR__ . '/../../../vendor/autoload.php'; use Cerad\Module\KernelModule\KernelContainer; use Cerad\Module\AuthModule\AuthServices; class AuthTests extends \PHPUnit_Framework_TestCase { protected $container; public static function setUpBeforeClass() { shell_exec(sprintf('mysql --login-path=tests < %s',__DIR__ . '/users_schema.sql')); } public function setUp() { $this->container = $container = new KernelContainer(); $container->set('secret','someSecret'); $container->set('cerad_user_master_password','testing'); $container->set('db_url_users','mysql://test:test123@localhost/tests'); new AuthServices($container); } public function test1() { } }
<?php namespace Cerad\Module\AuthModule\Tests; require __DIR__ . '/../../../vendor/autoload.php'; use Cerad\Module\KernelModule\KernelContainer; use Cerad\Module\AuthModule\AuthServices; class AuthTests extends \PHPUnit_Framework_TestCase { protected $container; public static function setUpBeforeClass() { shell_exec(sprintf('mysql --login-path=tests < %s',__DIR__ . '/users_schema.sql')); } public function setUp() { $this->container = $container = new KernelContainer(); $container->set('secret','someSecret'); $container->set('cerad_user_master_password','testing'); $container->set('db_url_users','mysql://test:test123@localhost/tests'); new AuthServices($container); } public function test1() { } }