text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove the `server:log` command if monolog is not loaded
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\WebServerBundle\DependencyInjection; use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; /** * @author Robin Chalas <robin.chalas@gmail.com> */ class WebServerExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('webserver.xml'); if (!class_exists(ConsoleFormatter::class)) { $container->removeDefinition('web_server.command.server_log'); } } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\WebServerBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; /** * @author Robin Chalas <robin.chalas@gmail.com> */ class WebServerExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('webserver.xml'); } }
Save action runs ember concurrency task
import Ember from 'ember'; import { task } from 'ember-concurrency'; var noteController = Ember.Controller.extend({ refreshEditorFlag: false, isTyping: false, isSaving: false, promptDelete: false, isTypingObserver: function() { if (!this.get('isTyping')) { this.send('save'); } }.observes('isTyping'), editorOptions: function() { return { buttons: ["bold", "italic"], allowMultiParagraphSelection: true, toolbar: false }; }.property(), saveNote: task(function *() { if (this.get('model.isNew')) { this.set('model.createdAt', new Date()); } this.set('model.updatedAt', new Date()); yield this.get('model').save(); }).drop(), actions: { save: function() { this.get('saveNote').perform(); // if (this.get('model.isNew')) { // this.set('model.createdAt', new Date()); // } // this.set('isSaving', true); // this.set('model.updatedAt', new Date()); // this.get('model').save().then(() => { // this.set('isSaving', false); // }); }, refreshEditor: function() { this.set('refreshEditorFlag', true); } } }); export default noteController;
import Ember from 'ember'; import { task } from 'ember-concurrency'; var noteController = Ember.Controller.extend({ refreshEditorFlag: false, isTyping: false, isSaving: false, promptDelete: false, isTypingObserver: function() { if (!this.get('isTyping')) { this.send('save'); } }.observes('isTyping'), editorOptions: function() { return { buttons: ["bold", "italic"], allowMultiParagraphSelection: true, toolbar: false }; }.property(), saveNote: task(function *() { if (this.get('model.isNew')) { this.set('model.createdAt', new Date()); } this.set('model.updatedAt', new Date()); yield this.get('model').save(); }).drop(), actions: { save: function() { if (this.get('model.isNew')) { this.set('model.createdAt', new Date()); } this.set('isSaving', true); this.set('model.updatedAt', new Date()); this.get('model').save().then(() => { this.set('isSaving', false); }); }, refreshEditor: function() { this.set('refreshEditorFlag', true); } } }); export default noteController;
Fix product attributes db structure
<?php namespace Octommerce\Octommerce\Updates; use Schema; use October\Rain\Database\Updates\Migration; class CreateProductAttributesTable extends Migration { public function up() { Schema::create('octommerce_octommerce_product_attributes', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name'); $table->string('type')->default('text'); $table->json('options')->nullable(); $table->text('default')->nullable(); $table->timestamps(); }); Schema::create('octommerce_octommerce_product_product_attribute', function($table) { $table->engine = 'InnoDB'; $table->integer('product_id')->unsigned()->nullable(); $table->integer('attribute_id')->unsigned(); $table->json('value')->nullable(); }); } public function down() { Schema::dropIfExists('octommerce_octommerce_product_product_attribute'); Schema::dropIfExists('octommerce_octommerce_product_attributes'); } }
<?php namespace Octommerce\Octommerce\Updates; use Schema; use October\Rain\Database\Updates\Migration; class CreateProductAttributesTable extends Migration { public function up() { Schema::create('octommerce_octommerce_product_attributes', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name'); $table->string('type')->default('text'); $table->json('options')->nullable(); $table->text('default')->nullable(); $table->timestamps(); }); Schema::create('octommerce_octommerce_product_product_attribute', function($table) { $table->engine = 'InnoDB'; $table->integer('product_id')->unsigned(); $table->integer('attribute_id')->unsigned(); $table->json('value')->nullable(); }); } public function down() { Schema::dropIfExists('octommerce_octommerce_product_product_attribute'); Schema::dropIfExists('octommerce_octommerce_product_attributes'); } }
Remove component scan for common package - not required obvs.
package uk.ac.ebi.quickgo.annotation; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * * The RESTful service configuration for Annotations * * @author Tony Wardell * Date: 26/04/2016 * Time: 14:41 * Created with IntelliJ IDEA. */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({"uk.ac.ebi.quickgo.annotation.controller", "uk.ac.ebi.quickgo.rest"}) @Import({SearchServiceConfig.class}) public class AnnotationREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(AnnotationREST.class, args); } }
package uk.ac.ebi.quickgo.annotation; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * * The RESTful service configuration for Annotations * * @author Tony Wardell * Date: 26/04/2016 * Time: 14:41 * Created with IntelliJ IDEA. */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({"uk.ac.ebi.quickgo.annotation.controller", "uk.ac.ebi.quickgo.rest","uk.ac.ebi.quickgo.common"}) @Import({SearchServiceConfig.class}) public class AnnotationREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(AnnotationREST.class, args); } }
Use dynamically allocated ports in unit tests Use dynamically allocated ports in unit tests so they won't unexpectedly fail if a port happens to be in use.
/** * Copyright 2011-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.informantproject.core; import java.util.Collection; import org.informantproject.core.util.Threads; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author Trask Stalnaker * @since 0.5 */ public class MainEntryPointTest { private Collection<Thread> preExistingThreads; @Before public void before() { preExistingThreads = Threads.currentThreads(); MainEntryPoint.start("ui.port:0"); } @After public void after() throws Exception { Threads.preShutdownCheck(preExistingThreads); MainEntryPoint.shutdown(); Threads.postShutdownCheck(preExistingThreads); } @Test public void testNoGuiceBindingErrorsEtc() { // all the work is done in before() and after() } }
/** * Copyright 2011-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.informantproject.core; import java.util.Collection; import org.informantproject.core.util.Threads; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author Trask Stalnaker * @since 0.5 */ public class MainEntryPointTest { private Collection<Thread> preExistingThreads; @Before public void before() { preExistingThreads = Threads.currentThreads(); MainEntryPoint.start(); } @After public void after() throws Exception { Threads.preShutdownCheck(preExistingThreads); MainEntryPoint.shutdown(); Threads.postShutdownCheck(preExistingThreads); } @Test public void testNoGuiceBindingErrorsEtc() { // all the work is done in before() and after() } }
Update dialog service to use defaults of angular ui-bootstrap.
/* * Spreed WebRTC. * Copyright (C) 2013-2014 struktur AG * * This file is part of Spreed WebRTC. * * 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/>. * */ define(["angular"], function(angular) { // dialogs return ["$window", "$modal", "$templateCache", "translation", function($window, $modal, $templateCache, translation) { return { create: function(url, controller, data, opts) { return $modal.open({ templateUrl: url, controller: controller, keyboard : opts.kb === undefined ? true : opts.kb, backdrop : opts.bd === undefined ? true : opts.bd, windowClass: opts.wc, size: opts.ws, resolve: { data: function() { return data; } } }); } } }]; });
/* * Spreed WebRTC. * Copyright (C) 2013-2014 struktur AG * * This file is part of Spreed WebRTC. * * 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/>. * */ define(["angular"], function(angular) { // dialogs return ["$window", "$modal", "$templateCache", "translation", function($window, $modal, $templateCache, translation) { return { create: function(url, controller, data, opts) { return $modal.open({ templateUrl: url, controller: controller, keyboard : opts.kb, backdrop : opts.bd, windowClass: opts.wc, size: opts.ws, resolve: { data: function() { return data; } } }); } } }]; });
Fix `ns` decorator. Don't return a value.
import App from "./App"; export default class Action { dispatchAction(...args) { return App.dispatchAction(...args); } get logger() { return App.logger(this.ns); } get events() { return App.events; } publish(ev, ...args) { return App.events.publish(`${this.ns}.${ev}`, ...args); } get ns() { return this._ns || "app"; } set ns(namespace) { this._ns = namespace; } static ns(key) { // Decorator for easily adding namespace. return (ActionWithNS) => { ActionWithNS.prototype.ns = key; }; } }
import App from "./App"; export default class Action { dispatchAction(...args) { return App.dispatchAction(...args); } get logger() { return App.logger(this.ns); } get events() { return App.events; } publish(ev, ...args) { return App.events.publish(`${this.ns}.${ev}`, ...args); } get ns() { return this._ns || "app"; } set ns(namespace) { this._ns = namespace; } static ns(key) { // Decorator for easily adding namespace. return (ActionWithNS) => ActionWithNS.prototype.ns = key; } }
Revert "Fixed ElasticSearchInfoTest after upgrading to 7.3.1" This reverts commit e0ef226b40f560993e7597cd7cd0b12ce66ea877.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.elasticsearch; import org.apache.camel.builder.RouteBuilder; import org.elasticsearch.action.main.MainResponse; import org.junit.Test; public class ElasticsearchInfoTest extends ElasticsearchBaseTest { @Test public void testInfo() throws Exception { MainResponse infoResult = template.requestBody("direct:info", "test", MainResponse.class); assertNotNull(infoResult.getClusterName()); assertNotNull(infoResult.getNodeName()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:info").to("elasticsearch-rest://elasticsearch?operation=Info&hostAddresses=localhost:" + ES_BASE_HTTP_PORT); } }; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.elasticsearch; import org.apache.camel.builder.RouteBuilder; import org.elasticsearch.client.core.MainResponse; import org.junit.Test; public class ElasticsearchInfoTest extends ElasticsearchBaseTest { @Test public void testInfo() throws Exception { MainResponse infoResult = template.requestBody("direct:info", "test", MainResponse.class); assertNotNull(infoResult.getClusterName()); assertNotNull(infoResult.getNodeName()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:info").to("elasticsearch-rest://elasticsearch?operation=Info&hostAddresses=localhost:" + ES_BASE_HTTP_PORT); } }; } }
Fix lint error in JS fixture
export default { "id": 101, "email": "hugo@demo.studentinsights.org", "admin": false, "full_name": "Teacher, Hugo", "staff_type": null, "schoolwide_access": false, "grade_level_access": [], "restricted_to_sped_students": false, "restricted_to_english_language_learners": false, "can_view_restricted_notes": false, "districtwide_access": false, "school": { "id": 9, "name": "Somerville High" }, "sections": [ { "id": 3, "section_number": "ART-302A", "course_description": "Ceramic Art 3" }, { "id": 4, "section_number": "ART-302B", "course_description": "Ceramic Art 3" } ], "labels": [] };
export default { "id": 101, "email": "hugo@demo.studentinsights.org", "admin": false, "full_name": "Teacher, Hugo", "staff_type": null, "schoolwide_access": false, "grade_level_access": [], "restricted_to_sped_students": false, "restricted_to_english_language_learners": false, "can_view_restricted_notes": false, "districtwide_access": false, "labels": [], "school": { "id": 9, "name": "Somerville High" }, "sections": [ { "id": 3, "section_number": "ART-302A", "course_description": "Ceramic Art 3" }, { "id": 4, "section_number": "ART-302B", "course_description": "Ceramic Art 3" } ], "labels": [] };
Fix settings with false defaults
(function() { angular .module('ionic.utils', []) .factory('localStorage', localStorage); localStorage.$inject = ['$window']; function localStorage($window) { return { set : function (key, value) { $window.localStorage[key] = value; }, get : function (key, defaultValue) { return $window.localStorage[key] || defaultValue; }, setObject : function (key, value) { $window.localStorage[key] = JSON.stringify(value); }, getObject : function (key, defaultValue) { return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (_.isUndefined(defaultValue) ? '{}' : defaultValue)); }, setArray : function (key, value) { this.setObject(key, value); }, getArray : function (key) { return JSON.parse($window.localStorage[key] || '[]'); } }; } })();
(function() { angular .module('ionic.utils', []) .factory('localStorage', localStorage); localStorage.$inject = ['$window']; function localStorage($window) { return { set : function (key, value) { $window.localStorage[key] = value; }, get : function (key, defaultValue) { return $window.localStorage[key] || defaultValue; }, setObject : function (key, value) { $window.localStorage[key] = JSON.stringify(value); }, getObject : function (key, defaultValue) { return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (defaultValue ? defaultValue : '{}')); }, setArray : function (key, value) { this.setObject(key, value); }, getArray : function (key) { return JSON.parse($window.localStorage[key] || '[]'); } }; } })();
Set the internal encoding of mastering. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Config\Bootstrap; use Orchestra\Config\FileLoader; use Orchestra\Config\Repository; use Illuminate\Filesystem\Filesystem; use Illuminate\Contracts\Foundation\Application; class LoadConfiguration { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Application $app) { $loader = new FileLoader(new Filesystem, $app['path.config']); $app->instance('config', $config = new Repository($loader, $app->environment())); // First we will see if we have a cache configuration file. If we do, we'll load // the configuration items from that file so that it is very quick. Otherwise // we will need to spin through every configuration file and load them all. if (file_exists($cached = $app->getCachedConfigPath()) && ! $app->runningInConsole()) { $items = require $cached; $config->set($items); } date_default_timezone_set($config['app.timezone']); mb_internal_encoding('UTF-8'); } }
<?php namespace Orchestra\Config\Bootstrap; use Orchestra\Config\FileLoader; use Orchestra\Config\Repository; use Illuminate\Filesystem\Filesystem; use Illuminate\Contracts\Foundation\Application; class LoadConfiguration { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Application $app) { $loader = new FileLoader(new Filesystem, $app['path.config']); $app->instance('config', $config = new Repository($loader, $app->environment())); // First we will see if we have a cache configuration file. If we do, we'll load // the configuration items from that file so that it is very quick. Otherwise // we will need to spin through every configuration file and load them all. if (file_exists($cached = $app->getCachedConfigPath()) && ! $app->runningInConsole()) { $items = require $cached; $config->set($items); } date_default_timezone_set($config['app.timezone']); } }
Print the message in the encode example.
#!/usr/bin/env python3 import os import sys # Add the Python root directory (fusion-engine-client/python/) to the import search path to enable FusionEngine imports # if this application is being run directly out of the repository and is not installed as a pip package. root_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, root_dir) from fusion_engine_client.messages import * from fusion_engine_client.parsers import FusionEngineEncoder from fusion_engine_client.utils.argument_parser import ArgumentParser from fusion_engine_client.utils.bin_utils import bytes_to_hex if __name__ == "__main__": parser = ArgumentParser(description="""\ Encode a FusionEngine message and print the resulting binary content to the console. """) options = parser.parse_args() # Enable FusionEngine PoseMessage output on UART1 message = SetMessageRate(output_interface=InterfaceID(TransportType.SERIAL, 1), protocol=ProtocolType.FUSION_ENGINE, message_id=MessageType.POSE, rate=MessageRate.ON_CHANGE) print(message) encoder = FusionEngineEncoder() encoded_data = encoder.encode_message(message) print('') print(bytes_to_hex(encoded_data, bytes_per_row=16, bytes_per_col=2))
#!/usr/bin/env python3 import os import sys # Add the Python root directory (fusion-engine-client/python/) to the import search path to enable FusionEngine imports # if this application is being run directly out of the repository and is not installed as a pip package. root_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, root_dir) from fusion_engine_client.messages import * from fusion_engine_client.parsers import FusionEngineEncoder from fusion_engine_client.utils.argument_parser import ArgumentParser from fusion_engine_client.utils.bin_utils import bytes_to_hex if __name__ == "__main__": parser = ArgumentParser(description="""\ Encode a FusionEngine message and print the resulting binary content to the console. """) options = parser.parse_args() # Enable FusionEngine PoseMessage output on UART1 message = SetMessageRate(output_interface=InterfaceID(TransportType.SERIAL, 1), protocol=ProtocolType.FUSION_ENGINE, message_id=MessageType.POSE, rate=MessageRate.ON_CHANGE) encoder = FusionEngineEncoder() encoded_data = encoder.encode_message(message) print(bytes_to_hex(encoded_data, bytes_per_row=16, bytes_per_col=2))
Add som comments to sync version.
(function (window){ // Creates a required validation var sync = $('#zip_sync') .required() .and() // Creates a custom validation wich will make an ajax call syncr. .custom('sync', function (value) { // This flag will be returned by custom validation after ajax call finishes. var ok; $.ajax({ 'url': 'https://api.mercadolibre.com/countries/BR/zip_codes/' + value, 'dataType': 'json', 'type': 'GET', 'async': false }) .done(function () { ok = true; }) .error(function () { ok = false; }); return ok; }, 'Please, enter a valid zip code.'); }(this));
(function (window){ // SYNC var sync = $('#zip_sync').required().and().custom('sync', function (value) { var ok; //ZIP CODE: 90040060 $.ajax({ 'url': 'https://api.mercadolibre.com/countries/BR/zip_codes/' + value, 'dataType': 'json', 'type': 'GET', 'async': false }) .done(function () { ok = true; }) .error(function () { ok = false; }); return ok; }, 'Message Sync.'); }(this));
Set the version name for the default branch to mercurial so we can tell when we run from the repository
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = 'mercurial' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = '0.10' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
Allow specifying a port to actually work
from zope.interface import implements from twisted.plugin import IPlugin from twisted.application.service import IServiceMaker from twisted.application import internet from oauth_proxy import oauth_proxy class OAuthProxyServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = "oauth_proxy" description = "OAuth HTTP proxy" options = oauth_proxy.Options def makeService(self, options): # TODO add error handling for missing params useSSL = options["ssl"] consumerKey = options["consumer-key"] consumerSecret = options["consumer-secret"] if options.has_key("token") and options.has_key("token-secret"): token = options["token"] tokenSecret = options["token-secret"] else: token = tokenSecret = None port = int(options["port"]) credentials = oauth_proxy.OAuthCredentials(consumerKey, consumerSecret, token, tokenSecret) credentialProvider = oauth_proxy.StaticOAuthCredentialProvider(credentials) return internet.TCPServer(port, oauth_proxy.OAuthProxyFactory(credentialProvider, useSSL)) serviceMaker = OAuthProxyServiceMaker()
from zope.interface import implements from twisted.plugin import IPlugin from twisted.application.service import IServiceMaker from twisted.application import internet from oauth_proxy import oauth_proxy class OAuthProxyServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = "oauth_proxy" description = "OAuth HTTP proxy" options = oauth_proxy.Options def makeService(self, options): # TODO add error handling for missing params useSSL = options["ssl"] consumerKey = options["consumer-key"] consumerSecret = options["consumer-secret"] if options.has_key("token") and options.has_key("token-secret"): token = options["token"] tokenSecret = options["token-secret"] else: token = tokenSecret = None port = options["port"] credentials = oauth_proxy.OAuthCredentials(consumerKey, consumerSecret, token, tokenSecret) credentialProvider = oauth_proxy.StaticOAuthCredentialProvider(credentials) return internet.TCPServer(port, oauth_proxy.OAuthProxyFactory(credentialProvider, useSSL)) serviceMaker = OAuthProxyServiceMaker()
Add lists to allowed HTML
<?php /** * A message presenter to show a WordPress notice. */ class Whip_WPMessagePresenter implements Whip_MessagePresenter { private $message; /** * Whip_WPMessagePresenter constructor. * * @param Whip_Message $message The message to use in the presenter. */ public function __construct( Whip_Message $message ) { $this->message = $message; } /** * Registers hooks to WordPress. This is a separate function so you can * control when the hooks are registered. */ public function register_hooks() { add_action( 'admin_notices', array( $this, 'renderMessage' ) ); } /** * Renders the messages present in the global to notices. */ public function renderMessage() { printf( '<div class="error">%s</div>', $this->kses( $this->message->body() ) ); } /** * Removes content from the message that we don't want to show. * * @param string $message The message to clean. * * @return string The cleaned message. */ public function kses( $message ) { return wp_kses( $message, array( 'a' => array( 'href' => true, 'target' => true, ), 'strong' => true, 'p' => true, 'ul' => true, 'li' => true, ) ); } }
<?php /** * A message presenter to show a WordPress notice. */ class Whip_WPMessagePresenter implements Whip_MessagePresenter { private $message; /** * Whip_WPMessagePresenter constructor. * * @param Whip_Message $message The message to use in the presenter. */ public function __construct( Whip_Message $message ) { $this->message = $message; } /** * Registers hooks to WordPress. This is a separate function so you can * control when the hooks are registered. */ public function register_hooks() { add_action( 'admin_notices', array( $this, 'renderMessage' ) ); } /** * Renders the messages present in the global to notices. */ public function renderMessage() { printf( '<div class="error">%s</div>', $this->kses( $this->message->body() ) ); } /** * Removes content from the message that we don't want to show. * * @param string $message The message to clean. * * @return string The cleaned message. */ public function kses( $message ) { return wp_kses( $message, array( 'a' => array( 'href' => true, 'target' => true, ), 'strong' => true, 'p' => true, ) ); } }
Increment column to be printed by 1
import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column + 1) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg)
import os from tailor.types.location import Location class Printer: def __init__(self, filepath): self.__filepath = os.path.abspath(filepath) def warn(self, warn_msg, ctx=None, loc=Location(1, 1)): self.__print('warning', warn_msg, ctx, loc) def error(self, err_msg, ctx=None, loc=Location(1, 1)): self.__print('error', err_msg, ctx, loc) def __print(self, classification, msg, ctx, loc): if ctx is not None: print(self.__filepath + ':' + str(ctx.start.line) + ':' + str(ctx.start.column) + ': ' + classification + ': ' + msg) else: print(self.__filepath + ':' + str(loc.line) + ':' + str(loc.column) + ': ' + classification + ': ' + msg)
Create a test for user creation through `FactoryBoy` Add a test for user creation
from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from rest_framework import status import factory import json from .models import BaseAccount from .serializers import WholeAccountSerializer class UserFactory(factory.django.DjangoModelFactory): class Meta: model = BaseAccount first_name = 'John' last_name = 'Doe' email = '{}.{}@email.com'.format(first_name, last_name) password = 'passjohn1' class FactoryBoyCreateUserTest(APITestCase): def setUp(self): self.user = UserFactory() def test_can_create_user(self): response = self.client.get( reverse('_accounts:account-detail', kwargs={'pk': 1})) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertJSONEqual( raw=json.dumps(response.data), expected_data=WholeAccountSerializer(self.user).data)
from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from rest_framework import status import factory from .models import BaseAccount class UserFactory(factory.Factory): class Meta: model = BaseAccount first_name = 'John' last_name = 'Doe' email = '{}.{}@email.com'.format(first_name, last_name) password = 'passjohn1' class CreateUserTest(APITestCase): def setUp(self): self.user = UserFactory() self.client.login(email=self.user.email, password=self.user.password) def test_can_create_user(self): response = self.client.get( reverse('_accounts:account-list'),) self.assertEqual(response.status_code, status.HTTP_200_OK)
Update comment and obey formatting requirements.
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # The descriptors are equivalent, but we have created # distinct dtype instances. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # A quirk of the metadata test is that equivalent metadata dicts are still # separate objects and so don't evaluate as the same array type description. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
Set default logging level to WARNING Fixes tests with pytest 3.3.0+
# coding: utf-8 """ weasyprint.logging ------------------ Logging setup. The rest of the code gets the logger through this module rather than ``logging.getLogger`` to make sure that it is configured. Logging levels are used for specific purposes: - errors are used for unreachable or unusable external resources, including unreachable stylesheets, unreachables images and unreadable images; - warnings are used for unknown or bad HTML/CSS syntaxes, unreachable local fonts and various non-fatal problems; - infos are used to advertise rendering steps. :copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_literals import logging LOGGER = logging.getLogger('weasyprint') LOGGER.setLevel(logging.WARNING) LOGGER.addHandler(logging.NullHandler())
# coding: utf-8 """ weasyprint.logging ------------------ Logging setup. The rest of the code gets the logger through this module rather than ``logging.getLogger`` to make sure that it is configured. Logging levels are used for specific purposes: - errors are used for unreachable or unusable external resources, including unreachable stylesheets, unreachables images and unreadable images; - warnings are used for unknown or bad HTML/CSS syntaxes, unreachable local fonts and various non-fatal problems; - infos are used to advertise rendering steps. :copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_literals import logging LOGGER = logging.getLogger('weasyprint') LOGGER.addHandler(logging.NullHandler())
Upgrade libchromiumcontent to fix icu symbols
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '55efd338101e08691560192b2be0f9c3b1b0eb72' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e375124044f9044ac88076eba0cd17361ee0997c' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Add sanity typecheck to user details registry lookups
var extend = req('/utilities/extend'), add = req('/utilities/add'); var UserDetails = req('/lib/user-details'); class UserDetailsRegistry { constructor() { this.user_detail_records = [ ]; } getUserDetailsForMessage(message) { return this.getOrStoreUserDetails(message.getUserDetails()); } getOrStoreUserDetails(user_details) { if (!(user_details instanceof UserDetails)) { throw new Error(` Invalid user details argument supplied: ${typeof user_details} `); } return ( this.getMatchingUserDetails(user_details) || this.storeUserDetails(user_details) ); } getOrStoreUserDetailsForNick(nick) { var user_details = UserDetails.fromNick(nick); return this.getOrStoreUserDetails(user_details); } getMatchingUserDetails(user_details) { var index = 0; while (index < this.user_detail_records.length) { let current_user_details = this.user_detail_records[index]; if (current_user_details.matches(user_details)) { return current_user_details; } index++; } return null; } storeUserDetails(user_details) { add(user_details).to(this.user_detail_records); return user_details; } } extend(UserDetailsRegistry.prototype, { user_detail_records: null }); module.exports = UserDetailsRegistry;
var extend = req('/utilities/extend'), add = req('/utilities/add'); var UserDetails = req('/lib/user-details'); class UserDetailsRegistry { constructor() { this.user_detail_records = [ ]; } getUserDetailsForMessage(message) { return this.getOrStoreUserDetails(message.getUserDetails()); } getOrStoreUserDetails(user_details) { return ( this.getMatchingUserDetails(user_details) || this.storeUserDetails(user_details) ); } getOrStoreUserDetailsForNick(nick) { var user_details = UserDetails.fromNick(nick); return this.getOrStoreUserDetails(user_details); } getMatchingUserDetails(user_details) { var index = 0; while (index < this.user_detail_records.length) { let current_user_details = this.user_detail_records[index]; if (current_user_details.matches(user_details)) { return current_user_details; } index++; } return null; } storeUserDetails(user_details) { add(user_details).to(this.user_detail_records); return user_details; } } extend(UserDetailsRegistry.prototype, { user_detail_records: null }); module.exports = UserDetailsRegistry;
:art: Use a non-hacky way to replace nbsp
'use babel' /* @flow */ import type { Message } from '../types' const nbsp = String.fromCodePoint(160) export function visitMessage(message: Message) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(new RegExp(nbsp, 'g'), ' ') }
'use babel' /* @flow */ import type { Message } from '../types' export function visitMessage(message: Message) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } /* eslint-disable no-irregular-whitespace */ // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(/ /g, ' ') /* eslint-enable no-irregular-whitespace */ }
Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@33700 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
[Doctrine] Fix default value to null for entity manager to make fluent integration with Doctrine Registry work
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Doctrine\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * Constraint for the Unique Entity validator * * @author Benjamin Eberlei <kontakt@beberlei.de> */ class UniqueEntity extends Constraint { public $message = 'This value is already used.'; public $em = null; public $fields = array(); public function getRequiredOptions() { return array('fields'); } /** * The validator must be defined as a service with this name. * * @return string */ public function validatedBy() { return 'doctrine.orm.validator.unique'; } /** * {@inheritDoc} */ public function getTargets() { return self::CLASS_CONSTRAINT; } public function getDefaultOption() { return 'fields'; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Doctrine\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * Constraint for the Unique Entity validator * * @author Benjamin Eberlei <kontakt@beberlei.de> */ class UniqueEntity extends Constraint { public $message = 'This value is already used.'; public $em = false; public $fields = array(); public function getRequiredOptions() { return array('fields'); } /** * The validator must be defined as a service with this name. * * @return string */ public function validatedBy() { return 'doctrine.orm.validator.unique'; } /** * {@inheritDoc} */ public function getTargets() { return self::CLASS_CONSTRAINT; } public function getDefaultOption() { return 'fields'; } }
Update cell presence to include rootfs and volume driver info [#124601741] Signed-off-by: Nima Kaviani <0ebde517669f70c2aec92dc89d4950413b825ec0@us.ibm.com>
package vizzini_test import ( "code.cloudfoundry.org/bbs/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) var cell_z1_0 *models.CellPresence for _, cell := range cells { if cell.CellId == "cell_z1-0" { cell_z1_0 = cell break } } Expect(cell_z1_0).NotTo(BeNil()) Expect(cell_z1_0.CellId).To(Equal("cell_z1-0")) Expect(cell_z1_0.Zone).To(Equal("z1")) Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0)) Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0)) }) })
package vizzini_test import ( "code.cloudfoundry.org/bbs/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) var cell_z1_0 *models.CellPresence for _, cell := range cells { if cell.CellId == "cell_z1-0" { cell_z1_0 = cell break } } Expect(cell_z1_0).NotTo(BeNil()) Expect(cell_z1_0.CellId).To(Equal("cell_z1-0")) Expect(cell_z1_0.Zone).To(Equal("z1")) Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0)) }) })
Make player creation code more intention revealing
function tryCreatePlayer(parentNode, asciicast, options) { function createPlayer() { asciinema.CreatePlayer( parentNode, asciicast.width, asciicast.height, asciicast.stdout_frames_url, asciicast.duration, { snapshot: asciicast.snapshot, speed: options.speed, autoPlay: options.autoPlay, loop: options.loop, fontSize: options.fontSize, theme: options.theme } ); } function fetch() { $.get('/api/asciicasts/' + asciicast.id + '.json', function(data) { asciicast = data; checkReadiness(); }); } function checkReadiness() { if (asciicast.stdout_frames_url) { $('.processing-info').remove(); createPlayer(); } else { $('.processing-info').show(); setTimeout(fetch, 2000); } } checkReadiness(); }
function createPlayer(parentNode, asciicast, options) { asciinema.CreatePlayer( parentNode, asciicast.width, asciicast.height, asciicast.stdout_frames_url, asciicast.duration, { snapshot: asciicast.snapshot, speed: options.speed, autoPlay: options.autoPlay, loop: options.loop, fontSize: options.fontSize, theme: options.theme } ); } function tryCreatePlayer(parentNode, asciicast, options) { if (asciicast.stdout_frames_url) { $('.processing-info').remove(); createPlayer(parentNode, asciicast, options); } else { $('.processing-info').show(); setTimeout(function() { $.get('/api/asciicasts/' + asciicast.id + '.json', function(data) { tryCreatePlayer(parentNode, data, options); }); }, 2000); } }
Make small article block comment links clickable
<?php $comments = $article->getNumValidatedComments(); ?> <div class="article-block section <?php echo $article->getCategory()->getCat(); ?>"> <div class="small"<?php if($equalizer): ?> data-equalizer-watch="<?php echo $equalizer; ?>"<?php endif; ?>> <div class="article-title"><a href="<?php echo $article->getUrl(); ?>"><?php echo $article->getTitle(); ?></a></div> <span class="article-time"><span class="glyphicons glyphicons-clock"></span><?php echo Utility::getRelativeTime($article->getPublished()); ?></span> <?php if($comments > 0): ?><span class="article-inline-comments"><a href="<?php echo $article->getUrl(); ?>#commentHeader"><span class="glyphicons glyphicons-comments"></span>&nbsp;<?php echo $comments; ?></a></span><?php endif; ?> </div> </div>
<?php $comments = $article->getNumValidatedComments(); ?> <div class="article-block section <?php echo $article->getCategory()->getCat(); ?>"> <div class="small"<?php if($equalizer): ?> data-equalizer-watch="<?php echo $equalizer; ?>"<?php endif; ?>> <div class="article-title"><a href="<?php echo $article->getUrl(); ?>"><?php echo $article->getTitle(); ?></a></div> <span class="article-time"><span class="glyphicons glyphicons-clock"></span><?php echo Utility::getRelativeTime($article->getPublished()); ?></span> <?php if($comments > 0): ?><span class="article-inline-comments"><span class="glyphicons glyphicons-comments"></span>&nbsp;<?php echo $comments; ?></span><?php endif; ?> </div> </div>
Return errors as object for high abstraction if-statements
// @flow import fetch from 'node-fetch' import {GITHUB_API_BASE_URL, getHeaders} from './utils' import {GithubRequestParams} from './entities' export function createRepo( {name, isPrivate, description, accessToken}: GithubRequestParams ): Promise<any> { console.log(description) const headers = getHeaders(accessToken) const body = JSON.stringify({ name, private: isPrivate, description }) return fetch( `${GITHUB_API_BASE_URL}/user/repos`, {method: 'POST', headers, body} ) .then(res => res.json()) } export function checkIfRepoExists(name: string, accessToken: string): Promise<boolean> { const headers = getHeaders(accessToken) return fetch( `${GITHUB_API_BASE_URL}/user/repos/${name}`, {method: 'GET', headers} ) .then(({ status }) => ({ wrongCredentials: status === 401, repoExists: status === 404, })) }
// @flow import fetch from 'node-fetch' import {GITHUB_API_BASE_URL, getHeaders} from './utils' import {GithubRequestParams} from './entities' export function createRepo( {name, isPrivate, description, accessToken}: GithubRequestParams ): Promise<any> { console.log(description) const headers = getHeaders(accessToken) const body = JSON.stringify({ name, private: isPrivate, description }) return fetch( `${GITHUB_API_BASE_URL}/user/repos`, {method: 'POST', headers, body} ) .then(res => res.json()) } export function checkIfRepoExists(name: string, accessToken: string): Promise<boolean> { const headers = getHeaders(accessToken) return fetch( `${GITHUB_API_BASE_URL}/user/repos/${name}`, {method: 'GET', headers} ) .then(({ status }) => status) }
Replace post-process checks with ones that are not deprecated R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org Bug: 899266 Change-Id: Ia9b1f38590d636fa2858a2bd0bbf75d6b2cfe8fa Reviewed-on: https://chromium-review.googlesource.com/c/1483033 Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org> Reviewed-by: John Budorick <17d38a2d68c6a07a3ab0ce4a2873c5acefbd3dbb@chromium.org> Commit-Queue: Sergiy Belozorov <aadb4a11584aa9878242ea5d9e4b7e3429654579@chromium.org>
# Copyright 2018 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. from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusSuccess) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusAnyFailure) + api.post_process(post_process.DropExpectation) )
# Copyright 2018 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. from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusCodeIn, 0) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusCodeIn, 1) + api.post_process(post_process.DropExpectation) )
Switch all CRUD endpoints to /api namespace This will clearly define what are the API paths and normal paths.
const express = require('express'); const bodyParser = require('body-parser'); const User = require('../database/models/user'); const session = require('express-session'); const Store = require('connect-session-sequelize')(session.Store); const { db } = require('../database/connection'); const app = express(); const path = require('path'); /** * Create the mySql store; passing in the database connection */ const store = new Store({ db: db }); store.sync(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); /** * Creates a new session */ app.use(session({ name: 'MustardTigers', secret: '5 dollar gold club special', resave: true, saveUninitialized: true, store: store })); /** * Static routes */ app.use(express.static(__dirname + '/../client/dist')); app.use('/api', express.Router() .use('/users', require('./users')) .use('/auth', require('./auth')) ); app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '..', 'client', 'dist', 'index.html')); }); module.exports.app = app;
const express = require('express'); const bodyParser = require('body-parser'); const User = require('../database/models/user'); const session = require('express-session'); const Store = require('connect-session-sequelize')(session.Store); const { db } = require('../database/connection'); const app = express(); const path = require('path'); /** * Create the mySql store; passing in the database connection */ const store = new Store({ db: db }); store.sync(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); /** * Creates a new session */ app.use(session({ name: 'MustardTigers', secret: '5 dollar gold club special', resave: true, saveUninitialized: true, store: store })); /** * Static routes */ app.use(express.static(__dirname + '/../client/dist')); app.use('/users', require('./users')); app.use('/auth', require('./auth')); app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '..', 'client', 'dist', 'index.html')); }); module.exports.app = app;
Revert "Update testing to better fit" This reverts commit 04569aeb14186564ff0c080c4ccbdc64b56cf2e8.
/* # # i2mx.js - v0.1-Alpha # Apache v2 License # */ // Create img2musicXML (abbreviated as i2mx) namespace var i2mx = i2mx || { }; // Create JsCheckup class (@TODO: Move to inside namespace) var JsCheckup = function() { this.divId = "i2mx-checkup"; this.activate = function() { // @TODO: Use HTML generator // Initial values var div = document.getElementById(this.divId); var EOL = "<br>" var checkupText = ""; // Start testing checkupText += "Starting tests... " + EOL; if(window.File && window.FileReader && window.FileList && window.Blob) { checkupText += "File and Blob APIs -> OK " + EOL; } // Update DOM div.innerHTML = checkupText; } } var jsCheckup = new JsCheckup(); // @TODO: Use event listener instead of onload window.onload = function() { jsCheckup.activate(); }
/* # # i2mx.js - v0.1-Alpha # Apache v2 License # */ // Create img2musicXML (abbreviated as i2mx) namespace var i2mx = i2mx || { }; // Create JsCheckup class (@TODO: Move to inside namespace) var JsCheckup = function() { this.divId = "i2mx-checkup"; this.activate = function() { // @TODO: Use HTML generator // Initial values var div = document.getElementById(this.divId); var EOL = "<br>" var checkupText = EOL; // Start testing checkupText += "Starting tests... " + EOL; if(window.File && window.FileReader && window.FileList && window.Blob) { checkupText += "File and Blob APIs - OK " + EOL; } // Update DOM div.innerHTML = checkupText; } } var jsCheckup = new JsCheckup(); // @TODO: Use event listener instead of onload window.onload = function() { jsCheckup.activate(); }
Add explicit versions for dependencies
from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2 == 0.7.1", "pyjwt==0.1.2"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
from twilio import __version__ from setuptools import setup, find_packages setup( name = "twilio", version = __version__, description = "Twilio API client and TwiML generator", author = "Twilio", author_email = "help@twilio.com", url = "http://github.com/twilio/twilio-python/", keywords = ["twilio","twiml"], install_requires = ["httplib2", "pyjwt"], packages = find_packages(), classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", ], long_description = """\ Python Twilio Helper Library ---------------------------- DESCRIPTION The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. The Twilio REST API lets to you initiate outgoing calls, list previous calls, and much more. See http://www.github.com/twilio/twilio-python for more information. LICENSE The Twilio Python Helper Library is distributed under the MIT License """ )
Update sample task with pprint
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxwu' import pprint from me.maxwu.cistat import config from me.maxwu.cistat.reqs.circleci_request import CircleCiReq from me.maxwu.cistat.model.xunit_report import Xunitrpt """Main script file to provide configuration loading, cli_app and version. """ VERSION = "1.0" def cli_app(): vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username() urls = CircleCiReq.get_recent_artifacts( token=config.get_circleci_token(), vcs=vcs, project=project, username=username ) report = Xunitrpt() for artifact in urls: print("fetching {}".format(artifact)) report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact)) print("Top 10 failure cases:") pprint.pprint(report.get_cases_in_rate()[:10]) print("Plot Barchart of Pass Rate") report.plot_barchart_rate(project, "Pass Rate per case") if __name__ == '__main__': cli_app()
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxwu' import json from me.maxwu.cistat import config from me.maxwu.cistat.reqs.circleci_request import CircleCiReq from me.maxwu.cistat.model.xunit_report import Xunitrpt """Main script file to provide configuration loading, cli_app and version. """ VERSION = "1.0" def cli_app(): vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username() urls = CircleCiReq.get_recent_artifacts( token=config.get_circleci_token(), vcs=vcs, project=project, username=username ) report = Xunitrpt() for artifact in urls: print("fetching {}".format(artifact)) report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact)) print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10])) print("Plot Barchart of Pass Rate") report.plot_barchart_rate(project, "Pass Rate per case") if __name__ == '__main__': cli_app()
Update demo for _parent field issue
<?php require_once 'vendor/autoload.php'; require_once 'ElasticSearch.php'; //Get the search manager $sm = ElasticSearch::get(); //Execute a direct Elastica term search $query = new Elastica\Filter\Term(array('username' => 'timmyl')); $users = $sm->getRepository('Entities\User')->search($query); foreach($users as $user) { print_r($user); } //Execute a single term lookup, modify and persist $user = $sm->getRepository('Entities\User')->findOneBy(array('username' => 'mrhash')); print_r($user); $user->setName('New name'); $sm->persist($user); $sm->flush(); //Execute a single lookup with no results try { $user = $sm->find('Entities\User', 'unknownid'); } catch(Doctrine\Search\Exception\NoResultException $exception) { print_r($exception->getMessage()); } //Search for comments with parent user. Because of the way ES returns //results, you have to explicitly ask for the _parent or _routing field if required. //On single document query e.g. find() the _parent field is returned by ES anyway. $query = new Elastica\Query(); $query->setFilter(new Elastica\Filter\HasParent( new Elastica\Filter\Term(array('username' => 'mrhash')), 'users' )); $query->setFields(array('_source', '_parent')); $comments = $sm->getRepository('Entities\Comment')->search($query); foreach($comments as $comment) { print_r($comment); }
<?php require_once 'vendor/autoload.php'; require_once 'ElasticSearch.php'; //Get the search manager $sm = ElasticSearch::get(); //Execute a direct Elastica term search $query = new Elastica\Filter\Term(array('username' => 'timmyl')); $users = $sm->getRepository('Entities\User')->search($query); foreach($users as $user) { print_r($user); } //Execute a single term lookup, modify and persist $user = $sm->getRepository('Entities\User')->findOneBy(array('username' => 'mrhash')); print_r($user); $user->setName('New name'); $sm->persist($user); $sm->flush(); //Execute a single lookup with no results try { $user = $sm->find('Entities\User', 'unknownid'); } catch(Doctrine\Search\Exception\NoResultException $exception) { print_r($exception->getMessage()); } //Search for comments with parent user $query = new Elastica\Filter\HasParent( new Elastica\Filter\Term(array('username' => 'mrhash')), 'users' ); $comments = $sm->getRepository('Entities\Comment')->search($query); foreach($comments as $comment) { print_r($comment); }
Add explicit fallback methods to the main object
import { NativeModules } from 'react-native'; import GoogleApi from './googleApi.js'; const { RNGeocoder } = NativeModules; export default { apiKey: null, fallbackToGoogle(key) { this.apiKey = key; }, geocodePositionFallback(position) { if (!this.apiKey) { throw new Error("Google API key required"); } return GoogleApi.geocodePosition(this.apiKey, position); }, geocodeAddressFallback(address) { if (!this.apiKey) { throw new Error("Google API key required"); } return GoogleApi.geocodeAddress(this.apiKey, address); }, geocodePosition(position) { if (!position || !position.lat || !position.lng) { return Promise.reject(new Error("invalid position: {lat, lng} required")); } return RNGeocoder.geocodePosition(position).catch(err => { if (!this.apiKey || err.code !== 'NOT_AVAILABLE') { throw err; } return this.geocodePositionFallback(position); }); }, geocodeAddress(address) { if (!address) { return Promise.reject(new Error("address is null")); } return RNGeocoder.geocodeAddress(address).catch(err => { if (!this.apiKey || err.code !== 'NOT_AVAILABLE') { throw err; } return this.geocodeAddressFallback(address); }); }, }
import { NativeModules } from 'react-native'; import GoogleApi from './googleApi.js'; const { RNGeocoder } = NativeModules; export default { apiKey: null, fallbackToGoogle(key) { this.apiKey = key; }, geocodePosition(position) { if (!position || !position.lat || !position.lng) { return Promise.reject(new Error("invalid position: {lat, lng} required")); } return RNGeocoder.geocodePosition(position).catch(err => { if (!this.apiKey || err.code !== 'NOT_AVAILABLE') { throw err; } return GoogleApi.geocodePosition(this.apiKey, position); }); }, geocodeAddress(address) { if (!address) { return Promise.reject(new Error("address is null")); } return RNGeocoder.geocodeAddress(address).catch(err => { if (!this.apiKey || err.code !== 'NOT_AVAILABLE') { throw err; } return GoogleApi.geocodeAddress(this.apiKey, address); }); }, }
Update project url after github maintainer renaming
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
Switch dumper from error_log to direct writing into php://stderr
<?php /** * Spiral Framework. * * @license MIT * @author Anton Titov (Wolfy-J) */ declare(strict_types=1); use Spiral\Core\Container\Autowire; use Spiral\Debug\Dumper; if (!function_exists('bind')) { /** * Shortcut to container Autowire definition. * * Example: * 'name' => bind(SomeClass::name, [...]) * * @param string $alias Class name or alias. * @param array $parameters * * @return Autowire */ function bind(string $alias, array $parameters = []): Autowire { return new Autowire($alias, $parameters); } } if (!function_exists('dumprr')) { /** * Dumprr is similar to Dump function but always redirect output to STDERR. * * @param mixed $value */ function dumprr($value): void { $result = dump($value, Dumper::RETURN); file_put_contents('php://stderr', $result); } }
<?php /** * Spiral Framework. * * @license MIT * @author Anton Titov (Wolfy-J) */ declare(strict_types=1); use Spiral\Core\Container\Autowire; use Spiral\Debug\Dumper; if (!function_exists('bind')) { /** * Shortcut to container Autowire definition. * * Example: * 'name' => bind(SomeClass::name, [...]) * * @param string $alias Class name or alias. * @param array $parameters * * @return Autowire */ function bind(string $alias, array $parameters = []): Autowire { return new Autowire($alias, $parameters); } } if (!function_exists('dumprr')) { /** * Dumprr is similar to Dump function but always redirect output to STDERR. * * @param mixed $value */ function dumprr($value): void { dump($value, Dumper::ERROR_LOG); } }
Fix ordering problem in tearDown
from ...testcases import DustyIntegrationTestCase from ...fixtures import busybox_single_app_bundle_fixture class TestSyncCLI(DustyIntegrationTestCase): def setUp(self): super(TestSyncCLI, self).setUp() busybox_single_app_bundle_fixture() self.run_command('bundles activate busyboxa') self.run_command('up') def tearDown(self): self.run_command('bundles deactivate busyboxa') try: self.run_command('stop') except Exception: pass super(TestSyncCLI, self).tearDown() def test_sync_repo(self): self.exec_in_container('busyboxa', 'rm -rf /repo') self.assertFileNotInContainer('busyboxa', '/repo/README.md') self.run_command('sync fake-repo') self.assertFileContentsInContainer('busyboxa', '/repo/README.md', '# fake-repo')
from ...testcases import DustyIntegrationTestCase from ...fixtures import busybox_single_app_bundle_fixture class TestSyncCLI(DustyIntegrationTestCase): def setUp(self): super(TestSyncCLI, self).setUp() busybox_single_app_bundle_fixture() self.run_command('bundles activate busyboxa') self.run_command('up') def tearDown(self): super(TestSyncCLI, self).tearDown() self.run_command('bundles deactivate busyboxa') try: self.run_command('stop') except Exception: pass def test_sync_repo(self): self.exec_in_container('busyboxa', 'rm -rf /repo') self.assertFileNotInContainer('busyboxa', '/repo/README.md') self.run_command('sync fake-repo') self.assertFileContentsInContainer('busyboxa', '/repo/README.md', '# fake-repo')
Rewrite robots.txt file in setup
from redsolutioncms.make import BaseMake from redsolutioncms.models import CMSSettings class Make(BaseMake): def make(self): super(Make, self).make() cms_settings = CMSSettings.objects.get_settings() cms_settings.render_to('settings.py', 'chunks/redsolutioncms/settings.pyt') cms_settings.render_to(['..', 'templates', 'base_chunks.html'], 'chunks/redsolutioncms/base_chunks.html', { }, 'w') cms_settings.render_to('urls.py', 'chunks/redsolutioncms/urls.pyt') cms_settings.render_to(['..', 'templates', 'robots.txt'], 'chunks/redsolutioncms/robots.txt', {}, 'w') cms_settings.base_template = 'base_chunks.html' cms_settings.save() make = Make()
from redsolutioncms.make import BaseMake from redsolutioncms.models import CMSSettings class Make(BaseMake): def make(self): super(Make, self).make() cms_settings = CMSSettings.objects.get_settings() cms_settings.render_to('settings.py', 'chunks/redsolutioncms/settings.pyt') cms_settings.render_to(['..', 'templates', 'base_chunks.html'], 'chunks/redsolutioncms/base_chunks.html', { }, 'w') cms_settings.render_to('urls.py', 'chunks/redsolutioncms/urls.pyt') cms_settings.render_to(['..', 'templates', 'robots.txt'], 'chunks/redsolutioncms/robots.txt') cms_settings.base_template = 'base_chunks.html' cms_settings.save() make = Make()
Move the super() up on ContributorMixin.
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): super(ContributorMixin, self).save_model(request, obj, form, change) if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal Information', {'fields': ('name', 'email')}), ('Important Dates', { 'classes': ('grp-collapse grp-closed',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-closed',), 'fields': ('is_active', 'is_staff', 'is_superuser') }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() super(ContributorMixin, self).save_model(request, obj, form, change) class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal Information', {'fields': ('name', 'email')}), ('Important Dates', { 'classes': ('grp-collapse grp-closed',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-closed',), 'fields': ('is_active', 'is_staff', 'is_superuser') }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
Remove paramiko requirement from core
# setup.py for git-keeper-core from setuptools import setup setup( name='git-keeper-core', version='0.1.0', description='Core modules for git-keeper-client and git-keeper-server.', url='https://github.com/git-keeper/git-keeper', license='GPL 3', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Education', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Natural Language :: English', 'Topic :: Education :: Testing', 'Topic :: Education' ], packages=['gkeepcore'], setup_requires=['pytest-runner'], tests_require=['pytest'], )
# setup.py for git-keeper-core from setuptools import setup setup( name='git-keeper-core', version='0.1.0', description='Core modules for git-keeper-client and git-keeper-server.', url='https://github.com/git-keeper/git-keeper', license='GPL 3', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Education', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Natural Language :: English', 'Topic :: Education :: Testing', 'Topic :: Education' ], packages=['gkeepcore'], install_requires=['paramiko'], setup_requires=['pytest-runner'], tests_require=['pytest'], )
Support CDN prefix for production builds Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
/* global require, module, process */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'), cdnPrefix = process.env.CDN_PREFIX || ''; module.exports = function(defaults) { var app = new EmberApp(defaults, { fingerprint: { prepend: cdnPrefix } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/bootstrap/dist/js/bootstrap.js'); app.import('bower_components/bootstrap/dist/css/bootstrap.css'); app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', { destDir: 'fonts' }); app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', { destDir: 'fonts' }); app.import('vendor/forge.min.js'); app.import('vendor/regex-weburl.js'); return app.toTree(); };
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/bootstrap/dist/js/bootstrap.js'); app.import('bower_components/bootstrap/dist/css/bootstrap.css'); app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', { destDir: 'fonts' }); app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', { destDir: 'fonts' }); app.import('vendor/forge.min.js'); app.import('vendor/regex-weburl.js'); return app.toTree(); };
Update python-dateutil to match the package we ship in Cloud:Tools
try: from setuptools import setup except ImportError: from distutils.core import setup from azurectl.version import __VERSION__ config = { 'description': 'Manage Azure PubCloud Service', 'author': 'PubCloud Development team', 'url': 'https://github.com/SUSE/azurectl', 'download_url': 'https://github.com/SUSE/azurectl', 'author_email': 'public-cloud-dev@susecloud.net', 'version': __VERSION__, 'install_requires': [ 'docopt==0.6.2', 'APScheduler==3.0.2', 'pyliblzma==0.5.3', 'azure_storage==0.20.0', 'azure_servicemanagement_legacy==0.20.0', 'python-dateutil==2.4' ], 'packages': ['azurectl'], 'entry_points': { 'console_scripts': ['azurectl=azurectl.azurectl:main'], }, 'name': 'azurectl' } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup from azurectl.version import __VERSION__ config = { 'description': 'Manage Azure PubCloud Service', 'author': 'PubCloud Development team', 'url': 'https://github.com/SUSE/azurectl', 'download_url': 'https://github.com/SUSE/azurectl', 'author_email': 'public-cloud-dev@susecloud.net', 'version': __VERSION__, 'install_requires': [ 'docopt==0.6.2', 'APScheduler==3.0.2', 'pyliblzma==0.5.3', 'azure_storage==0.20.0', 'azure_servicemanagement_legacy==0.20.0', 'python-dateutil==2.1' ], 'packages': ['azurectl'], 'entry_points': { 'console_scripts': ['azurectl=azurectl.azurectl:main'], }, 'name': 'azurectl' } setup(**config)
Append timestamp to dev-trunk url
<?php namespace Outlandish\Wpackagist\Package; class Plugin extends AbstractPackage { public function getVendorName() { return 'wpackagist-plugin'; } public function getComposerType() { return 'wordpress-plugin'; } public static function getSvnBaseUrl() { return 'https://plugins.svn.wordpress.org/'; } public function getHomepageUrl() { return "https://wordpress.org/plugins/".$this->getName().'/'; } public function getDownloadUrl($version) { $isTrunk = $this->versions[$version] === 'trunk'; //Assemble file name and append ?timestamp= variable to the trunk version to avoid Composer cache when plugin/theme author only updates the trunk $filename = ($isTrunk ? $this->getName() : $this->getName().'.'.$version) . '.zip' . ($isTrunk ? '?timestamp=' . urlencode($this->last_committed->format('U')) : ''); return "https://downloads.wordpress.org/plugin/{$filename}"; } }
<?php namespace Outlandish\Wpackagist\Package; class Plugin extends AbstractPackage { public function getVendorName() { return 'wpackagist-plugin'; } public function getComposerType() { return 'wordpress-plugin'; } public static function getSvnBaseUrl() { return 'https://plugins.svn.wordpress.org/'; } public function getHomepageUrl() { return "https://wordpress.org/plugins/".$this->getName().'/'; } public function getDownloadUrl($version) { $filename = $this->versions[$version] == 'trunk' ? $this->getName() : $this->getName().'.'.$version; return "https://downloads.wordpress.org/plugin/$filename.zip"; } }
Fix every case a special character is suppressed I refer to https://github.com/jonschlinkert/remarkable/blob/dev/lib/common/utils.js#L45 for regex writing.
var toc = require('markdown-toc'); module.exports = { book: {}, hooks: { "page:before": function (page) { page.content = toc.insert(page.content, { slugify: function (str) { return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-'); } }); if (this.options.pluginsConfig.atoc.addClass) { var className = this.options.pluginsConfig.atoc.className || 'atoc'; page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>'; } return page; } } };
var toc = require('markdown-toc'); module.exports = { book: {}, hooks: { "page:before": function (page) { page.content = toc.insert(page.content, { slugify: function (str) { return encodeURI(str.toLowerCase()).replace(/%20/g, '-').replace(/[\.,\-\(\)]/g,''); } }); if (this.options.pluginsConfig.atoc.addClass) { var className = this.options.pluginsConfig.atoc.className || 'atoc'; page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>'; } return page; } } };
Update event context instead of replace (NC-529)
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context def set_current_user(user): context = get_event_context() or {} context.update(user._get_log_context('user')) set_event_context(context) def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """ if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR'] class CaptureEventContextMiddleware(object): def process_request(self, request): context = {'ip_address': get_ip_address(request)} user = getattr(request, 'user', None) if user and not user.is_anonymous(): context.update(user._get_log_context('user')) set_event_context(context) def process_response(self, request, response): reset_event_context() return response
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context def set_current_user(user): set_event_context(user._get_log_context('user')) def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """ if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR'] class CaptureEventContextMiddleware(object): def process_request(self, request): context = {'ip_address': get_ip_address(request)} user = getattr(request, 'user', None) if user and not user.is_anonymous(): context.update(user._get_log_context('user')) set_event_context(context) def process_response(self, request, response): reset_event_context() return response
Implement listDecks in anki controller
<?php namespace Austin226\Sdsrs; use Austin226\Sdsrs\Exceptions\ResourceNotFoundException; use GuzzleHttp\Client; class AnkiApiController { private $ankiServerClient; public function __construct(string $ankiServerUri) { $this->ankiServerClient = new Client([ 'base_uri' => $ankiServerUri ]); } /** * Lists all collections we know of. * * @return array */ public function listCollections() : array { $response = $this->ankiServerClient->post('list_collections'); $responseBody = $response->getBody(); $collectionList = json_decode($responseBody, true); return $collectionList; } /** * Lists all decks in a collection. Throws a ResourceNotFoundException * if collection is not found. * * @return array * @throws \Austin226\Sdsrs\Exceptions\ResourceNotFoundException */ public function listDecks(string $collectionName) : array { $url = "/collection/{$collectionName}/list_decks"; $response = $this->ankiServerClient->get($url); $deckList = json_decode($responseBody, true); return $collectionList; } }
<?php namespace Austin226\Sdsrs; use Austin226\Sdsrs\Exceptions\ResourceNotFoundException; use GuzzleHttp\Client; class AnkiApiController { private $ankiServerClient; public function __construct(string $ankiServerUri) { $this->ankiServerClient = new Client([ 'base_uri' => $ankiServerUri ]); } /** * Lists all collections we know of. * * @return array */ public function listCollections() : array { $response = $this->ankiServerClient->post('list_collections'); $responseBody = $response->getBody(); $collectionList = json_decode($responseBody, true); return $collectionList; } public function listDecks(string $collectionName) : array { } }
Set HDF5TableSink as default sink
# coding=utf-8 # Filename: cmd.py """ KM3Pipe command line utility. Usage: km3pipe test km3pipe tohdf5 [-s] -i FILE -o FILE km3pipe (-h | --help) km3pipe --version Options: -h --help Show this screen. -i FILE Input file. -o FILE Output file. -s Write each event in a separate dataset. """ from __future__ import division, absolute_import, print_function from km3pipe import version def tohdf5(input_file, output_file, use_tables=True): """Convert ROOT file to HDF5 file""" from km3pipe import Pipeline # noqa from km3pipe.pumps import AanetPump, HDF5Sink, HDF5TableSink # noqa sink = HDF5TableSink if use_tables else HDF5Sink pipe = Pipeline() pipe.attach(AanetPump, filename=input_file) pipe.attach(sink, filename=output_file, separate_events=separate_events) pipe.drain() def main(): from docopt import docopt arguments = docopt(__doc__, version=version) if arguments['tohdf5']: tohdf5(arguments['-i'], arguments['-o'], arguments['-s'])
# coding=utf-8 # Filename: cmd.py """ KM3Pipe command line utility. Usage: km3pipe test km3pipe tohdf5 [-s] -i FILE -o FILE km3pipe (-h | --help) km3pipe --version Options: -h --help Show this screen. -i FILE Input file. -o FILE Output file. -s Write each event in a separate dataset. """ from __future__ import division, absolute_import, print_function from km3pipe import version def tohdf5(input_file, output_file, separate_events=False): """Convert ROOT file to HDF5 file""" from km3pipe import Pipeline # noqa from km3pipe.pumps import AanetPump, HDF5Sink, HDF5SinkLegacy # noqa sink = HDF5Sink if separate_events else HDF5SinkLegacy pipe = Pipeline() pipe.attach(AanetPump, filename=input_file) pipe.attach(sink, filename=output_file, separate_events=separate_events) pipe.drain() def main(): from docopt import docopt arguments = docopt(__doc__, version=version) if arguments['tohdf5']: tohdf5(arguments['-i'], arguments['-o'], arguments['-s'])
Add -h option to CLI
#!/usr/bin/env node var browserslist = require('./'); var pkg = require('./package.json'); var args = process.argv.slice(2); function isArg(arg) { return args.indexOf(arg) >= 0; } if ( args.length === 0 || isArg('--help') >= 0 || isArg('-h') >= 0 ) { console.log([ '', pkg.name + ' - ' + pkg.description, '', 'Usage:', '', ' ' + pkg.name + ' query ...' ].join('\n')); return; } if ( args.indexOf('--version') >= 0 ) { console.log(pkg.version); return; } browserslist(args).forEach(function (browser) { console.log(browser); });
#!/usr/bin/env node var browserslist = require('./'); var pkg = require('./package.json'); var args = process.argv.slice(2); if ( args.length <= 0 || args.indexOf('--help') >= 0 ) { console.log([ '', pkg.name + ' - ' + pkg.description, '', 'Usage:', '', ' ' + pkg.name + ' query ...' ].join('\n')); return; } if ( args.indexOf('--version') >= 0 ) { console.log(pkg.version); return; } browserslist(args).forEach(function (browser) { console.log(browser); });
Set x-Bit and add she-bang line
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup from azurectl.version import __VERSION__ config = { 'description': 'Manage Azure PubCloud Service', 'author': 'PubCloud Development team', 'url': 'https://github.com/SUSE/azurectl', 'download_url': 'https://github.com/SUSE/azurectl', 'author_email': 'public-cloud-dev@susecloud.net', 'version': __VERSION__, 'install_requires': [ 'docopt~=0.6.2', 'APScheduler~=3.0.2', 'pyliblzma~=0.5.3', 'azure_storage~=0.20.0', 'azure_servicemanagement_legacy~=0.20.1', 'python-dateutil~=2.4', 'dnspython~=1.12.0', 'setuptools~=5.4' ], 'packages': ['azurectl'], 'entry_points': { 'console_scripts': ['azurectl=azurectl.azurectl:main'], }, 'name': 'azurectl' } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup from azurectl.version import __VERSION__ config = { 'description': 'Manage Azure PubCloud Service', 'author': 'PubCloud Development team', 'url': 'https://github.com/SUSE/azurectl', 'download_url': 'https://github.com/SUSE/azurectl', 'author_email': 'public-cloud-dev@susecloud.net', 'version': __VERSION__, 'install_requires': [ 'docopt~=0.6.2', 'APScheduler~=3.0.2', 'pyliblzma~=0.5.3', 'azure_storage~=0.20.0', 'azure_servicemanagement_legacy~=0.20.1', 'python-dateutil~=2.4', 'dnspython~=1.12.0', 'setuptools~=5.4' ], 'packages': ['azurectl'], 'entry_points': { 'console_scripts': ['azurectl=azurectl.azurectl:main'], }, 'name': 'azurectl' } setup(**config)
Improve the attrs key usability change semantics from 2D array to a more intuitive object notation.
function createElement(hash, context){ var element; //create the element if(hash.direct) element = hash.direct; else element = document.createElement(hash.tagName); //add custom properties var properties = Object.getOwnPropertyNames(hash).filter( function(element){ return ['direct','tagName', 'children', 'assignTo', 'attrs'].indexOf(element) == -1; }); properties.forEach( function(prop){ element[prop] = hash[prop]; } ); //set custom attributes if(hash.attrs) for(var key in hash.attrs) element.setAttribute(key, hash.attrs[key]); //give it a name in the higher context if(hash.assignTo && context) context[hash.assignTo] = element; //generate and append children if(hash.children){ hash.children.forEach( function(child_hash){ element.appendChild( createElement(child_hash, context) ); }); } return element; }
function createElement(hash, context){ var element; //create the element if(hash.direct) element = hash.direct; else element = document.createElement(hash.tagName); //add custom properties var properties = Object.getOwnPropertyNames(hash).filter( function(element){ return ['direct','tagName', 'children', 'assignTo', 'attrs'].indexOf(element) == -1; }); properties.forEach( function(prop){ element[prop] = hash[prop]; } ); //set custom attributes if(hash.attrs){ hash.attrs.forEach( function(attr){ element.setAttribute(attr[0], attr[1]); }); } //give it a name in the higher context if(hash.assignTo && context) context[hash.assignTo] = element; //generate and append children if(hash.children){ hash.children.forEach( function(child_hash){ element.appendChild( createElement(child_hash, context) ); }); } return element; }
Fix wrong usage of isset().
<?php /** * This file is part of the Emperor Norton Commands. * * Public domain. All rites reversed. */ namespace EmperorNortonCommands\lib; use DateTime; /** * Class Holydays * @package EmperorNortonCommands\lib */ abstract class Holydays { /** * Array of Holydays. * * Keys are composed of the Gregorian day and month (2 digits). Values are the * Holyday's name in the given language. * * @var mixed */ protected $holydays = array(); /** * Get Holyday. * * Returns the name of the Holyday if there is a Holyday for given the key, * else returns empty string. * * @param string $key * @return string */ public function getHolyday($key) { if (isset($this->holydays[$key])) { return $this->holydays[$key]; } return ''; } }
<?php /** * This file is part of the Emperor Norton Commands. * * Public domain. All rites reversed. */ namespace EmperorNortonCommands\lib; use DateTime; /** * Class Holydays * @package EmperorNortonCommands\lib */ abstract class Holydays { /** * Array of Holydays. * * Keys are composed of the Gregorian day and month (2 digits). Values are the * Holyday's name in the given language. * * @var mixed */ protected $holydays = array(); /** * Get Holyday. * * Returns the English name of the Holyday if there is a Holyday for given * the key, else returns empty string. * * @param string $key * @return string */ public function getHolyday($key) { if (isset($key, $this->holydays)) { return $this->holydays[$key]; } return ''; } }
Fix to pass python linter, this slipped through as the master branch wasnt protected
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
Add changeyear() and commented on selected functions.
function editselection(adminname, adminusername, adminpassword, adminid){ document.getElementById("inputadminname").value = adminname; document.getElementById("inputadminusername").value = adminusername; document.getElementById("inputadminpassword").value = adminpassword; document.getElementById("inputadminadminid").value = adminid; } function deleteadmin(adminname, adminid){ document.getElementById("deleteadminname").innerHTML = "Delete " + adminname + "'s account?"; document.getElementById("deleteadminadminid").value = adminid; } function editUser(username, userusername, userpassword, userid){ document.getElementById("editusername").value = username; document.getElementById("edituserusername").value = userusername; document.getElementById("edituserpassword").value = userpassword; document.getElementById("edituseruserid").value = userid; } function changeday(){ var day = document.getElementById("dayselect").value; //Get the value from the day select document.getElementById("daychange").value = day; //Change the input value to the selected value } function changemonth(){ var month = document.getElementById("monthselect").value; //Get the value from the month select document.getElementById("monthchange").value = month; //Change the input value to the selected value } function changeyear(){ var year = document.getElementById("yearselect").value; //Get the value from the year select document.getElementById("yearchange").value = year; //Change the input value to the selected value }
function editselection(adminname, adminusername, adminpassword, adminid){ document.getElementById("inputadminname").value = adminname; document.getElementById("inputadminusername").value = adminusername; document.getElementById("inputadminpassword").value = adminpassword; document.getElementById("inputadminadminid").value = adminid; } function deleteadmin(adminname, adminid){ document.getElementById("deleteadminname").innerHTML = "Delete " + adminname + "'s account?"; document.getElementById("deleteadminadminid").value = adminid; } function editUser(username, userusername, userpassword, userid){ document.getElementById("editusername").value = username; document.getElementById("edituserusername").value = userusername; document.getElementById("edituserpassword").value = userpassword; document.getElementById("edituseruserid").value = userid; } function changeday(){ var day = document.getElementById("dayselect").value; document.getElementById("daychange").value = day; } function changemonth(){ var month = document.getElementById("monthselect").value; document.getElementById("monthchange").value = month; }
Change signup page to create an account and fix sign in link
<div class="single"> <div class="panel warp"> <?php echo formOpen('user/signup'); ?> <h1>Create Account</h1> <div> <?php echo inputText('username', 'Username, 5-16 characters.'); ?> </div> <div> <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?> </div> <div> <?php echo inputPassword('rpassword', 'Retype your password.'); ?> </div> <div> <?php echo inputSubmit('Create my account'); ?> </div> <div> Already have account? <a href="<?php echo baseUrl(); ?>user/signin">Sign In</a> </div> <?php echo formClose(); ?> </div> </div>
<div class="single"> <div class="panel warp"> <?php echo formOpen('user/signup'); ?> <h1>Sign Up</h1> <div> <?php echo inputText('username', 'Username, 5-16 characters.'); ?> </div> <div> <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?> </div> <div> <?php echo inputPassword('rpassword', 'Retype your password.'); ?> </div> <div> <?php echo inputSubmit('Sign In'); ?> </div> <div> Already have account? <a href="<?php echo baseUrl(); ?>user/signup">Sign In</a> </div> <?php echo formClose(); ?> </div> </div>
Update contentFor to use the head type - The vendor-prefix type has been deprecated
/* eslint-env node */ 'use strict'; var Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-ckeditor', included: function(app) { this._super.included(app); app.import(app.bowerDirectory + '/ckeditor/ckeditor.js'); }, contentFor: function(type, config) { if (type === 'head') { return `<script>window.CKEDITOR_BASEPATH = '${config.rootURL}assets/ckeditor/';</script>`; } }, treeForPublic: function(tree) { return new Funnel(this.project.bowerDirectory + '/ckeditor', { srcDir: '/', // include: ['**/*.woff', '**/stylesheet.css'], destDir: '/assets/ckeditor' }); } };
/* eslint-env node */ 'use strict'; var Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-ckeditor', included: function(app) { this._super.included(app); app.import(app.bowerDirectory + '/ckeditor/ckeditor.js'); }, contentFor: function(type, config) { if (type === 'vendor-prefix') { return `window.CKEDITOR_BASEPATH = '${config.rootURL}assets/ckeditor/';`; } }, treeForPublic: function(tree) { return new Funnel(this.project.bowerDirectory + '/ckeditor', { srcDir: '/', // include: ['**/*.woff', '**/stylesheet.css'], destDir: '/assets/ckeditor' }); } };
refactor(users): Create relationship for users table modifield: app/User.php see #124
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'date_of_birth', 'city_id', 'country_id', 'district_id', 'address', 'avatar' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function orders() { return $this->hasMany('App\Order'); } public function assignments() { return $this->hasMany('App\Assignment'); } public function addresses() { return $this->hasMany('App\Address'); } }
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'date_of_birth', 'city_id', 'country_id', 'district_id', 'address', 'avatar' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function orders() { return $this->hasMany('App\Order'); } }
Use /{room}/{event} for the path
<?php namespace Mwop\Github\PuSH; use Psr\Container\ContainerInterface; use Zend\Expressive\Application; class RoutesDelegator { private $events = [ 'issues', 'issue_comment', 'pull_request', 'pull_request_review', 'pull_request_review_comment', 'release', 'status', ]; public function __invoke(ContainerInterface $container, string $name, callable $callback) : Application { $app = $callback(); foreach ($this->events as $event) { $app->post( sprintf('/github/{room}/%s', $event), LoggerAction::class, sprintf('github.%s', $event) ); } return $app; } }
<?php namespace Mwop\Github\PuSH; use Psr\Container\ContainerInterface; use Zend\Expressive\Application; class RoutesDelegator { private $events = [ 'issues', 'issue_comment', 'pull_request', 'pull_request_review', 'pull_request_review_comment', 'release', 'status', ]; public function __invoke(ContainerInterface $container, string $name, callable $callback) : Application { $app = $callback(); foreach ($this->events as $event) { $app->post( sprintf('/github/%s', $event), LoggerAction::class, sprintf('github.%s', $event) ); } return $app; } }
Move location of generated stations.json to data directory
import json from ns_api import Station, NSAPI from local_settings import USERNAME, APIKEY def update_station_data(): nsapi = NSAPI(USERNAME, APIKEY) stations = nsapi.get_stations() data = {'stations': []} for station in stations: # if station.country == "NL" and "Utrecht" in station.names['long']: if station.country == "NL": names = station.names data['stations'].append({'names': names, 'lon': station.lon, 'lat': station.lat, 'type': station.stationtype}) json_data = json.dumps(data, indent=4, sort_keys=True) with open('./data/stations.json', 'w') as fileout: fileout.write(json_data) if __name__ == "__main__": update_station_data()
import json from ns_api import Station, NSAPI from local_settings import USERNAME, APIKEY def update_station_data(): nsapi = NSAPI(USERNAME, APIKEY) stations = nsapi.get_stations() data = {'stations': []} for station in stations: # if station.country == "NL" and "Utrecht" in station.names['long']: if station.country == "NL": names = station.names data['stations'].append({'names': names, 'lon': station.lon, 'lat': station.lat, 'type': station.stationtype}) json_data = json.dumps(data, indent=4, sort_keys=True) with open('stations.json', 'w') as fileout: fileout.write(json_data) if __name__ == "__main__": update_station_data()
Convert HTTP redirect to 301 Moved Permanently When issuing a redirect, make it a Permanent one so we can give the browser another indicator that this change is permanent and it should not try to use HTTP again for this resource.
<?php /* Redirect to HTTPS and refuse to serve HTTP */ if($_SERVER['HTTPS'] != "on"){ $_SERVER['FULL_URL'] = 'https://'; if($_SERVER['SERVER_PORT']!='80') $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME']; else $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; if($_SERVER['QUERY_STRING']>' '){ $_SERVER['FULL_URL'] .= '?'.$_SERVER['QUERY_STRING']; } header("Location: " . $_SERVER['FULL_URL'], true, 301); exit(); } else { /* Only use HTTPS for the next year */ header("Strict-Transport-Security: max-age=31536000"); } ?>
<?php /* Redirect to HTTPS and refuse to serve HTTP */ if($_SERVER['HTTPS'] != "on"){ $_SERVER['FULL_URL'] = 'https://'; if($_SERVER['SERVER_PORT']!='80') $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME']; else $_SERVER['FULL_URL'] .= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; if($_SERVER['QUERY_STRING']>' '){ $_SERVER['FULL_URL'] .= '?'.$_SERVER['QUERY_STRING']; } header("Location: " . $_SERVER['FULL_URL']); exit(); } else { /* Only use HTTPS for the next year */ header("Strict-Transport-Security: max-age=31536000"); } ?>
Remove omitempty from CustomLink definition since should never b
package server import ( "errors" "net/url" ) type getExternalLinksResponse struct { StatusFeed *string `json:"statusFeed,omitempty"` // Location of the a JSON Feed for client's Status page News Feed CustomLinks []CustomLink `json:"custom,omitempty"` // Any custom external links for client's User menu } // CustomLink is a handler that returns a custom link to be used in server's routes response, within ExternalLinks type CustomLink struct { Name string `json:"name"` URL string `json:"url"` } // NewCustomLinks transforms `--custom-link` CLI flag data or `CUSTOM_LINKS` ENV // var data into a data structure that the Chronograf client will expect func NewCustomLinks(links map[string]string) ([]CustomLink, error) { var customLinks []CustomLink for name, link := range links { if name == "" { return nil, errors.New("CustomLink missing key for Name") } if link == "" { return nil, errors.New("CustomLink missing value for URL") } _, err := url.Parse(link) if err != nil { return nil, err } customLinks = append(customLinks, CustomLink{ Name: name, URL: link, }) } return customLinks, nil }
package server import ( "errors" "net/url" ) type getExternalLinksResponse struct { StatusFeed *string `json:"statusFeed,omitempty"` // Location of the a JSON Feed for client's Status page News Feed CustomLinks []CustomLink `json:"custom,omitempty"` // Any custom external links for client's User menu } // CustomLink is a handler that returns a custom link to be used in server's routes response, within ExternalLinks type CustomLink struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` } // NewCustomLinks transforms `--custom-link` CLI flag data or `CUSTOM_LINKS` ENV // var data into a data structure that the Chronograf client will expect func NewCustomLinks(links map[string]string) ([]CustomLink, error) { var customLinks []CustomLink for name, link := range links { if name == "" { return nil, errors.New("CustomLink missing key for Name") } if link == "" { return nil, errors.New("CustomLink missing value for URL") } _, err := url.Parse(link) if err != nil { return nil, err } customLinks = append(customLinks, CustomLink{ Name: name, URL: link, }) } return customLinks, nil }
Remove promises from fs, watch loaded files
const { promisify } = require('util') const fs = require('fs') const showdown = require('showdown') class MarkdownRenderer { constructor (callback) { this.callback = callback this.converter = new showdown.Converter() } loadFile (fileName) { fs.watch(fileName, () => { const markdown = fs.readFileSync(fileName, 'utf8') Promise.resolve(this.load(markdown)) }) const markdown = fs.readFileSync(fileName, 'utf8') return this.load(markdown) } load (markdown) { return this.convert(markdown).then((html) => { return this.callback(html) }).catch((error) => { throw error }) } convert (markdown) { return promisify((markdown, callback) => { var html = this.converter.makeHtml(markdown) html = '<div class="markdown-body">' + html + '</div>' callback(null, html) })(markdown) } } exports.MarkdownRenderer = MarkdownRenderer
const Promise = require('bluebird') const readFile = Promise.promisify(require('fs').readFile) const showdown = require('showdown') class MarkdownRenderer { constructor (callback) { this.callback = callback this.converter = new showdown.Converter() } loadFile (fileName) { return readFile(fileName, 'utf8').then((markdown) => { return this.load(markdown) }) } load (markdown) { return this.convert(markdown).then((html) => { return this.callback(html) }).catch((error) => { throw error }) } convert (markdown) { return Promise.promisify((markdown, callback) => { var html = this.converter.makeHtml(markdown) html = '<div class="markdown-body">' + html + '</div>' callback(null, html) })(markdown) } } exports.MarkdownRenderer = MarkdownRenderer
Allow rows to have fixed height
/* @flow */ 'use strict'; import React, {Component} from 'react'; import {View, } from 'react-native'; import computeProps from '../Utils/computeProps'; import _ from 'lodash'; export default class RowNB extends Component { prepareRootProps() { var type = { flexDirection: 'row', flex: (this.props.size) ? this.props.size : (this.props.style && this.props.style.height) ? 0 : 1, } var defaultProps = { style: type } return computeProps(this.props, defaultProps); } render() { return( <View {...this.prepareRootProps()} >{this.props.children}</View> ); } }
/* @flow */ 'use strict'; import React, {Component} from 'react'; import {View, } from 'react-native'; import computeProps from '../Utils/computeProps'; import _ from 'lodash'; export default class RowNB extends Component { prepareRootProps() { var type = { flexDirection: 'row', flex: (this.props.size) ? this.props.size : 1, } var defaultProps = { style: type } return computeProps(this.props, defaultProps); } render() { return( <View {...this.prepareRootProps()} >{this.props.children}</View> ); } }
Update glob() for autoload config files Per a discussion on IRC with @weierophinney: - requiring ".config" in the filenames is redundant as they live under the config/ tree - "local" and "global" should be optional This leaves us with simply config/autoload/*.php.
<?php chdir(dirname(__DIR__)); require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php'; Zend\Loader\AutoloaderFactory::factory(); $appConfig = include 'config/application.config.php'; $listenerOptions = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']); $defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions); $defaultListeners->getConfigListener()->addConfigGlobPath("config/autoload/*.php"); $moduleManager = new Zend\Module\Manager($appConfig['modules']); $moduleManager->events()->attachAggregate($defaultListeners); $moduleManager->loadModules(); // Create application, bootstrap, and run $bootstrap = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig()); $application = new Zend\Mvc\Application; $bootstrap->bootstrap($application); $application->run()->send();
<?php chdir(dirname(__DIR__)); require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php'; Zend\Loader\AutoloaderFactory::factory(); $appConfig = include 'config/application.config.php'; $listenerOptions = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']); $defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions); $defaultListeners->getConfigListener()->addConfigGlobPath("config/autoload/{,*.}{global,local}.config.php"); $moduleManager = new Zend\Module\Manager($appConfig['modules']); $moduleManager->events()->attachAggregate($defaultListeners); $moduleManager->loadModules(); // Create application, bootstrap, and run $bootstrap = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig()); $application = new Zend\Mvc\Application; $bootstrap->bootstrap($application); $application->run()->send();
Change comment reference to Team channel
var Office365ConnectorHook = require("./index.js"), winston = require('winston'); var Logger = winston.Logger; var Console = winston.transports.Console; var logger = new Logger({ transports: [ new Console({}), new Office365ConnectorHook({ hookUrl: 'https://outlook.office.com/webhook/28b98568-d712-43b0-acab-dc662d48af10@6afcd346-7cb2-46db-897d-c639dbdf0449/IncomingWebhook/292e9954dc38453ab8dca787d4dae2c3/26b2f7b0-a26a-43d3-b4e8-ccd198b6b3ef' }) ] }); logger.info('I am being logged here'); // will be sent to both console and channel
var Office365ConnectorHook = require("./index.js"), winston = require('winston'); var Logger = winston.Logger; var Console = winston.transports.Console; var logger = new Logger({ transports: [ new Console({}), new Office365ConnectorHook({ hookUrl: 'https://outlook.office.com/webhook/28b98568-d712-43b0-acab-dc662d48af10@6afcd346-7cb2-46db-897d-c639dbdf0449/IncomingWebhook/292e9954dc38453ab8dca787d4dae2c3/26b2f7b0-a26a-43d3-b4e8-ccd198b6b3ef' }) ] }); logger.info('I am being logged here'); // will be sent to both console and Slack
Fix a problem with config publishing
<?php namespace LaurentEsc\Localization; use Illuminate\Support\ServiceProvider; class LocalizationServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/../config/config.php' => config_path('localization.php'), ], 'config'); } /** * Register the service provider. * * @return void */ public function register() { $packageConfigFile = __DIR__ . '/../config/config.php'; $this->mergeConfigFrom( $packageConfigFile, 'localization' ); $this->app['localization.localize'] = $this->app->share( function () { return new Localize(); } ); $this->app['localization.router'] = $this->app->share( function () { return new Router(); } ); } }
<?php namespace LaurentEsc\Localization; use Illuminate\Support\ServiceProvider; class LocalizationServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/../../config/config.php' => config_path('localization.php'), ], 'config'); } /** * Register the service provider. * * @return void */ public function register() { $packageConfigFile = __DIR__ . '/../config/config.php'; $this->mergeConfigFrom( $packageConfigFile, 'localization' ); $this->app['localization.localize'] = $this->app->share( function () { return new Localize(); } ); $this->app['localization.router'] = $this->app->share( function () { return new Router(); } ); } }
Call getName on currencyType so extensions are invoked
<?php namespace Tbbc\MoneyBundle\Form\Type; use Symfony\Component\Form\Extension\Core\Type\TextType; use Tbbc\MoneyBundle\Form\DataTransformer\MoneyToArrayTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Tbbc\MoneyBundle\Form\Type\CurrencyType; /** * Form type for the Money object. */ class MoneyType extends AbstractType { /** @var CurrencyType */ protected $currencyType; /** @var int */ protected $decimals; public function __construct( CurrencyType $currencyType, $decimals ) { $this->currencyType = $currencyType; $this->decimals = (int)$decimals; } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('tbbc_amount', new TextType()) ->add('tbbc_currency', $this->currencyType->getName()) ->addModelTransformer( new MoneyToArrayTransformer($this->decimals) ); } /** * @inheritdoc */ public function getName() { return 'tbbc_money'; } }
<?php namespace Tbbc\MoneyBundle\Form\Type; use Symfony\Component\Form\Extension\Core\Type\TextType; use Tbbc\MoneyBundle\Form\DataTransformer\MoneyToArrayTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Tbbc\MoneyBundle\Form\Type\CurrencyType; /** * Form type for the Money object. */ class MoneyType extends AbstractType { /** @var CurrencyType */ protected $currencyType; /** @var int */ protected $decimals; public function __construct( CurrencyType $currencyType, $decimals ) { $this->currencyType = $currencyType; $this->decimals = (int)$decimals; } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('tbbc_amount', new TextType()) ->add('tbbc_currency', $this->currencyType) ->addModelTransformer( new MoneyToArrayTransformer($this->decimals) ); } /** * @inheritdoc */ public function getName() { return 'tbbc_money'; } }
Convert json.Numbers into int64 or float64.
package jsonschema import ( "encoding/json" "fmt" "reflect" "strings" ) // normalizeNumber accepts any input and, if it is a supported number type, // converts it to either int64 or float64. normalizeNumber raises an error // if the input is an explicitly unsupported number type. func normalizeNumber(v interface{}) (n interface{}, err error) { switch t := v.(type) { case json.Number: if strings.Contains(t.String(), ".") { n, err = t.Float64() } else { n, err = t.Int64() } case float32: n = float64(t) case float64: n = t case int: n = int64(t) case int8: n = int64(t) case int16: n = int64(t) case int32: n = int64(t) case int64: n = t case uint8: n = int64(t) case uint16: n = int64(t) case uint32: n = int64(t) case uint64: n = t err = fmt.Errorf("%s is not a supported type.", reflect.TypeOf(v)) default: n = t } return }
package jsonschema import ( "fmt" "reflect" ) // normalizeNumber accepts any input and, if it is a supported number type, // converts it to either int64 or float64. normalizeNumber raises an error // if the input is an explicitly unsupported number type. func normalizeNumber(v interface{}) (n interface{}, err error) { switch t := v.(type) { case float32: n = float64(t) case float64: n = t case int: n = int64(t) case int8: n = int64(t) case int16: n = int64(t) case int32: n = int64(t) case int64: n = t case uint8: n = int64(t) case uint16: n = int64(t) case uint32: n = int64(t) case uint64: n = t err = fmt.Errorf("%s is not a supported type.", reflect.TypeOf(v)) default: n = t } return }
Change number of news on frontpage
from django.shortcuts import render from news.models import Article, Event from door.models import DoorStatus from datetime import datetime from itertools import chain def index(request): number_of_news = 3 # Sorts the news to show the events nearest in future and then fill in with the newest articles event_list = Event.objects.filter(time_end__gte=datetime.now())[0:number_of_news:-1] article_list = Article.objects.order_by('-pub_date')[0:number_of_news - len(event_list)] news_list = list(chain(event_list, article_list)) try: door_status = DoorStatus.objects.get(name='hackerspace').status except DoorStatus.DoesNotExist: door_status = True context = { 'news_list': news_list, 'door_status': door_status, } return render(request, 'index.html', context) def test404(request): return render(request, '404.html')
from django.shortcuts import render from news.models import Article, Event from door.models import DoorStatus from datetime import datetime from itertools import chain def index(request): number_of_news = 4 # Sorts the news to show the events nearest in future and then fill in with the newest articles event_list = Event.objects.filter(time_end__gte=datetime.now())[0:number_of_news:-1] article_list = Article.objects.order_by('-pub_date')[0:number_of_news - len(event_list)] news_list = list(chain(event_list, article_list)) try: door_status = DoorStatus.objects.get(name='hackerspace').status except DoorStatus.DoesNotExist: door_status = True context = { 'news_list': news_list, 'door_status': door_status, } return render(request, 'index.html', context) def test404(request): return render(request, '404.html')
mac: Upgrade libchromiumcontent to fix linking error
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '6300862b4b16bd171f00ae566b697098c29743f7' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '17a0e24666d0198810752284690bc2d0d87094d7' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Fix display of artist names in search tool.
var async = require("async"); var mongoose = require("mongoose"); require("ukiyoe-models")(mongoose); var Artist = mongoose.model("Artist"); mongoose.connect('mongodb://localhost/extract'); mongoose.connection.on('error', function(err) { console.error('Connection Error:', err) }); mongoose.connection.once('open', function() { process.stdin.on("data", function(data) { var name = data.toString().trim(); Artist.searchByName(name, function(err, results) { if (err) { console.error(err); return; } console.log(results.match && results.match.name.name, results.matches.map(function(match) { return match.text + " " + match.score; }) ); }); }); });
var async = require("async"); var mongoose = require("mongoose"); require("ukiyoe-models")(mongoose); var Artist = mongoose.model("Artist"); mongoose.connect('mongodb://localhost/extract'); mongoose.connection.on('error', function(err) { console.error('Connection Error:', err) }); mongoose.connection.once('open', function() { process.stdin.on("data", function(data) { var name = data.toString().trim(); Artist.searchByName(name, function(err, results) { if (err) { console.error(err); return; } console.log(results.match && results.match.name.name, results.matches.map(function(match) { return match.artist.name.name + " " + match.score; }) ); }); }); });
Fix tokens using too-random of a value
import datetime import os from flask import session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce def login_user(user): session["id"] = user.id session["name"] = user.name session["email"] = user.email session["nonce"] = generate_nonce() def logout_user(): session.clear() def generate_user_token(user, expiration=None): temp_token = True while temp_token is not None: value = hexencode(os.urandom(32)) temp_token = UserTokens.query.filter_by(value=value).first() token = UserTokens( user_id=user.id, expiration=expiration, value=value ) db.session.add(token) db.session.commit() return token def lookup_user_token(token): token = UserTokens.query.filter_by(value=token).first() if token: if datetime.datetime.utcnow() >= token.expiration: raise UserTokenExpiredException return token.user else: raise UserNotFoundException return None
import datetime import os from flask import session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce def login_user(user): session["id"] = user.id session["name"] = user.name session["email"] = user.email session["nonce"] = generate_nonce() def logout_user(): session.clear() def generate_user_token(user, expiration=None): temp_token = True while temp_token is not None: value = hexencode(os.urandom(32)) temp_token = UserTokens.query.filter_by(value=value).first() token = UserTokens( user_id=user.id, expiration=expiration, value=hexencode(os.urandom(32)) ) db.session.add(token) db.session.commit() return token def lookup_user_token(token): token = UserTokens.query.filter_by(value=token).first() if token: if datetime.datetime.utcnow() >= token.expiration: raise UserTokenExpiredException return token.user else: raise UserNotFoundException return None
Test coverage for useSecureRandom method
<?php namespace Scheb\TwoFactorBundle\Tests\Security\TwoFactor; use Scheb\TwoFactorBundle\Security\TwoFactor\TrustedTokenGenerator; class TrustedTokenGeneratorTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function generateToken_useSecureRandom_validToken() { $generator = new TrustedTokenGenerator(); //Use SecureRandom $token = $generator->generateToken(20); $this->assertEquals(20, strlen($token)); } /** * @test */ public function generateToken_useFallback_validToken() { $generator = new TestableTrustedTokenGenerator(); $generator->useSecureRandom = false; //Use fallback $token = $generator->generateToken(20); $this->assertEquals(20, strlen($token)); $this->assertRegExp("/^A+$/", $token); } } /** * Makes the TrustedTokenGenerator more testable */ class TestableTrustedTokenGenerator extends TrustedTokenGenerator { public $useSecureRandom = true; //Override generator selection protected $charspace = "A"; //Override charspace protected function useSecureRandom() { return $this->useSecureRandom; } }
<?php namespace Scheb\TwoFactorBundle\Tests\Security\TwoFactor; use Scheb\TwoFactorBundle\Security\TwoFactor\TrustedTokenGenerator; class TrustedTokenGeneratorTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function generateToken_useSecureRandom_validToken() { $generator = new TestableTrustedTokenGenerator(); $generator->useSecureRandom = true; //Use SecureRandom $token = $generator->generateToken(20); $this->assertEquals(20, strlen($token)); } /** * @test */ public function generateToken_useFallback_validToken() { $generator = new TestableTrustedTokenGenerator(); $generator->useSecureRandom = false; //Use fallback $token = $generator->generateToken(20); $this->assertEquals(20, strlen($token)); $this->assertRegExp("/^A+$/", $token); } } /** * Makes the TrustedTokenGenerator more testable */ class TestableTrustedTokenGenerator extends TrustedTokenGenerator { public $useSecureRandom = true; //Override generator selection protected $charspace = "A"; //Override charspace protected function useSecureRandom() { return $this->useSecureRandom; } }
Move property notification to common location I prefer this to be next to where the change is made that causes the all property to change.
import Ember from 'ember'; import { wrap } from 'bus-detective/utils/deserializer'; export default Ember.Service.extend({ storeKey: "favoriteStops", store: window.localStorage, add: function(stop) { var newStops = this.get('all').concat(stop); this.replaceStops(newStops); }, remove: function(stop) { var newStops = this.get('all').rejectBy('id', stop.id); this.replaceStops(newStops); }, hasStop: function(stop) { return !!this.get('all').findBy('id', stop.id); }, all: Ember.computed(function() { var stops = this.store[this.storeKey]; return stops ? JSON.parse(stops).map(wrap) : []; }), replaceStops: function(stops) { this.store[this.storeKey] = JSON.stringify(stops); this.notifyPropertyChange('all'); } });
import Ember from 'ember'; import { wrap } from 'bus-detective/utils/deserializer'; export default Ember.Service.extend({ storeKey: "favoriteStops", store: window.localStorage, add: function(stop) { var newStops = this.get('all').concat(stop); this.replaceStops(newStops); this.notifyPropertyChange('all'); }, remove: function(stop) { var newStops = this.get('all').rejectBy('id', stop.id); this.replaceStops(newStops); this.notifyPropertyChange('all'); }, hasStop: function(stop) { return !!this.get('all').findBy('id', stop.id); }, all: Ember.computed(function() { var stops = this.store[this.storeKey]; return stops ? JSON.parse(stops).map(wrap) : []; }), replaceStops: function(stops) { this.store[this.storeKey] = JSON.stringify(stops); } });
Add eslint rules of typescript.
module.exports = { "parserOptions": { "ecmaVersion": 2018, "sourceType": "module" }, "env": { "node": true, "es6": true }, "extends": [ "airbnb-base", "plugin:promise/recommended" ], "plugins": [ "promise", "typescript" ], "rules": { "func-names": "off", "import/prefer-default-export": "off", "no-await-in-loop": "off", "no-console": "off", "no-plusplus": "off", "no-underscore-dangle": ["error", { "allowAfterThis": true, "allowAfterSuper": true }], }, "overrides": [{ "files": ["**/*.ts"], "parser": "typescript-eslint-parser", "rules": { "import/no-unresolved": "off", "no-undef": "off", "typescript/member-ordering": ["error"], "typescript/no-array-constructor": ["error"], "typescript/no-triple-slash-reference": ["error"], "typescript/no-unused-vars": ["error"] } }, { "files": ["scripts/**/*"], "rules": { "import/no-extraneous-dependencies": "off" } }] };
module.exports = { "parserOptions": { "ecmaVersion": 2018, "sourceType": "module" }, "env": { "node": true, "es6": true }, "extends": [ "airbnb-base", "plugin:promise/recommended" ], "plugins": [ "promise", "typescript" ], "rules": { "func-names": "off", "import/prefer-default-export": "off", "no-await-in-loop": "off", "no-console": "off", "no-plusplus": "off", "no-underscore-dangle": ["error", { "allowAfterThis": true, "allowAfterSuper": true }], }, "overrides": [{ "files": ["**/*.ts"], "parser": "typescript-eslint-parser", "rules": { "import/no-unresolved": "off", "no-undef": "off", "typescript/no-unused-vars": ["error"] } }, { "files": ["scripts/**/*"], "rules": { "import/no-extraneous-dependencies": "off" } }] };
Validate the Command UUID to be UUIDv4
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Command; use Symfony\Component\Validator\Constraints as Assert; abstract class AbstractCommand implements Command { /** * @Assert\NotBlank() * @Assert\Type(type="string") * @Assert\Regex(pattern="~^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$~") * * @var string */ public $UUID; public function __toString() { return get_class($this) . '[' . $this->UUID . ']'; } }
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Command; use Symfony\Component\Validator\Constraints as Assert; abstract class AbstractCommand implements Command { /** * @Assert\NotBlank() * @Assert\Type(type="string") * * @var string */ public $UUID; public function __toString() { return get_class($this) . '[' . $this->UUID . ']'; } }
Use correct noun for sample remove modal Use 'sample' instead of 'OTU'
import React from "react"; import { connect } from "react-redux"; import { push } from "connected-react-router"; import { routerLocationHasState } from "../../utils/utils"; import { removeSample } from "../actions"; import { RemoveModal } from "../../base"; export const RemoveSample = ({ id, name, show, onHide, onConfirm }) => ( <RemoveModal noun="Sample" name={name} show={show} onConfirm={() => onConfirm(id)} onHide={onHide} /> ); const mapStateToProps = state => { const { id, name } = state.samples.detail; return { show: routerLocationHasState(state, "removeSample"), id, name }; }; const mapDispatchToProps = dispatch => ({ onConfirm: sampleId => { dispatch(removeSample(sampleId)); }, onHide: () => { dispatch(push({ state: { removeSample: false } })); } }); export default connect( mapStateToProps, mapDispatchToProps )(RemoveSample);
import React from "react"; import { connect } from "react-redux"; import { push } from "connected-react-router"; import { routerLocationHasState } from "../../utils/utils"; import { removeSample } from "../actions"; import { RemoveModal } from "../../base"; export const RemoveSample = ({ id, name, show, onHide, onConfirm }) => ( <RemoveModal noun="OTU" name={name} show={show} onConfirm={() => onConfirm(id)} onHide={onHide} /> ); const mapStateToProps = state => { const { id, name } = state.samples.detail; return { show: routerLocationHasState(state, "removeSample"), id, name }; }; const mapDispatchToProps = dispatch => ({ onConfirm: sampleId => { dispatch(removeSample(sampleId)); }, onHide: () => { dispatch(push({ state: { removeSample: false } })); } }); export default connect( mapStateToProps, mapDispatchToProps )(RemoveSample);
Revert "Switch the default registry to ZK based" This reverts commit 558ee079fd04dfab8e61eca10ee98ab5bac89dfa because it wasn't tagged with a jira ID. Will be re-applied.
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.yetus.audience.InterfaceAudience; /** * Factory class to get the instance of configured connection registry. */ @InterfaceAudience.Private final class ConnectionRegistryFactory { private ConnectionRegistryFactory() { } /** * @return The connection registry implementation to use. */ static ConnectionRegistry getRegistry(Configuration conf) { Class<? extends ConnectionRegistry> clazz = conf.getClass( CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, MasterRegistry.class, ConnectionRegistry.class); return ReflectionUtils.newInstance(clazz, conf); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.yetus.audience.InterfaceAudience; /** * Factory class to get the instance of configured connection registry. */ @InterfaceAudience.Private final class ConnectionRegistryFactory { private ConnectionRegistryFactory() { } /** * @return The connection registry implementation to use. */ static ConnectionRegistry getRegistry(Configuration conf) { Class<? extends ConnectionRegistry> clazz = conf.getClass( CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, ZKConnectionRegistry.class, ConnectionRegistry.class); return ReflectionUtils.newInstance(clazz, conf); } }
Add cffi to the package requirements.
from setuptools import find_packages from setuptools import setup setup( name='kms-encryption-toolbox', version='0.0.6', url='https://github.com/ApplauseOSS/kms-encryption-toolbox', license='Applause', description='Encryption toolbox to be used with the Amazon Key Management Service for securing your deployment secrets. It encapsulates the aws-encryption-sdk package to expose cmdline actions.', author='Applause', author_email='architecture@applause.com', zip_safe=False, packages=find_packages(), install_requires=[ 'cffi>=1.10.0', 'aws-encryption-sdk>=1.2.0', 'click>=6.6', 'attrs>=16.3.0,<17.0.0' ], entry_points={ "console_scripts": [ "kms-encryption = kmsencryption.__main__:main", ] }, scripts=["kmsencryption/scripts/decrypt-and-start.sh"] )
from setuptools import find_packages from setuptools import setup setup( name='kms-encryption-toolbox', version='0.0.5', url='https://github.com/ApplauseOSS/kms-encryption-toolbox', license='Applause', description='Encryption toolbox to be used with the Amazon Key Management Service for securing your deployment secrets. It encapsulates the aws-encryption-sdk package to expose cmdline actions.', author='Applause', author_email='architecture@applause.com', zip_safe=False, packages=find_packages(), install_requires=[ 'aws-encryption-sdk>=1.2.0', 'click>=6.6', 'attrs>=16.3.0,<17.0.0' ], entry_points={ "console_scripts": [ "kms-encryption = kmsencryption.__main__:main", ] }, scripts=["kmsencryption/scripts/decrypt-and-start.sh"] )
Fix typo in module docstring.
""" Tests for go_cli.main. """ from unittest import TestCase from click.testing import CliRunner from go_cli.main import cli class TestCli(TestCase): def test_help(self): runner = CliRunner() result = runner.invoke(cli, ['--help']) self.assertEqual(result.exit_code, 0) self.assertTrue("Vumi Go command line utility." in result.output) self.assertTrue("send Send messages via an HTTP API (nostream)..." in result.output) def test_version(self): runner = CliRunner() result = runner.invoke(cli, ['--version']) self.assertEqual(result.exit_code, 0) self.assertTrue("go_cli, version " in result.output)
""" Tests fir go_cli.main. """ from unittest import TestCase from click.testing import CliRunner from go_cli.main import cli class TestCli(TestCase): def test_help(self): runner = CliRunner() result = runner.invoke(cli, ['--help']) self.assertEqual(result.exit_code, 0) self.assertTrue("Vumi Go command line utility." in result.output) self.assertTrue("send Send messages via an HTTP API (nostream)..." in result.output) def test_version(self): runner = CliRunner() result = runner.invoke(cli, ['--version']) self.assertEqual(result.exit_code, 0) self.assertTrue("go_cli, version " in result.output)
Revert "Revert "style(webpack_config/server): rewrite prod conf in functional style"" This reverts commit e9de3d6da5e3cfc03b6d5e39fe92ede9c110d712.
import webpack from 'webpack' import baseWebpackConfig from './webpack.base' import UglifyJSPlugin from 'uglifyjs-webpack-plugin' import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer' import {Plugin as ShakePlugin} from 'webpack-common-shake' import OptimizeJsPlugin from 'optimize-js-plugin' const analyzePlugins = process.env.ANALYZE_BUNDLE ? [new BundleAnalyzerPlugin({analyzerMode: 'static'})] : [] const plugins = [ new webpack.ProgressPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), new ShakePlugin(), // NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin // new BabiliPlugin(), new UglifyJSPlugin({ sourceMap: true, compress: { warnings: false, unused: true, dead_code: true // This option removes console.log in production // drop_console: true }, output: { comments: false } }), new OptimizeJsPlugin({ sourceMap: true }), ...analyzePlugins ] export default Object.assign({}, baseWebpackConfig, { plugins: baseWebpackConfig.plugins.concat(plugins) })
import webpack from 'webpack' import baseWebpackConfig from './webpack.base' import UglifyJSPlugin from 'uglifyjs-webpack-plugin' import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer' import {Plugin as ShakePlugin} from 'webpack-common-shake' import OptimizeJsPlugin from 'optimize-js-plugin' const plugins = [ new webpack.ProgressPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), new ShakePlugin(), // NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin // new BabiliPlugin(), new UglifyJSPlugin({ sourceMap: true, compress: { warnings: false, unused: true, dead_code: true // This option removes console.log in production // drop_console: true }, output: { comments: false } }), new OptimizeJsPlugin({ sourceMap: true }) ] // Do you want to use bundle analyzer? if (process.env.ANALYZE_BUNDLE) { plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'})) } export default Object.assign({}, baseWebpackConfig, { plugins: baseWebpackConfig.plugins.concat(plugins) })
Fix bug with restaurant div
$(document).ready(function(){ $(".restaurant-info").hide(); $(".restaurant-tab-container").on("click", function(event) { var restaurant = $(this).find(".restaurant-tab").prop('id'); var restaurantId = getRestaurantId(restaurant) $("#restaurant-info-" + restaurantId).slideToggle("slow"); }) function checkAllWaittime() { $(".restaurants-wrapper").children().each(function() { var htmlId = $(this).find('.restaurant-tab').prop('id') console.log(htmlId); getWaittime(getRestaurantId(htmlId)); }) } function getWaittime(restaurantId) { var restaurantUrl = "/restaurants/" + restaurantId +"/waittime" $.ajax({ method: "get", url: restaurantUrl, data: { id: restaurantId } }).done(function(response){ console.log(response) $("#restaurant-" + restaurantId).find(".waittime-display").replaceWith("<p class='waittime-display'>" + response + " minutes</p>") }) } function getRestaurantId(htmlId) { var match = htmlId.match(/\d+/g); return match[0]; } setInterval(checkAllWaittime, 60000) })
$(document).ready(function(){ $(".restaurant-info").hide(); $(".restaurant-tab-container").on("click", function(event) { var restaurant = $(this).find(".restaurant-tab").prop('id'); var restaurantId = getRestaurantId(restaurant) $("#restaurant-info-" + restaurantId).slideToggle("slow"); }) function checkAllWaittime() { $(".restaurants-wrapper").children().each(function() { var htmlId = $(this).prop('id') console.log(htmlId); getWaittime(getRestaurantId(htmlId)); }) } function getWaittime(restaurantId) { var restaurantUrl = "/restaurants/" + restaurantId +"/waittime" $.ajax({ method: "get", url: restaurantUrl, data: { id: restaurantId } }).done(function(response){ console.log(response) $("#restaurant-" + restaurantId).find(".waittime-display").replaceWith("<p class='waittime-display'>" + response + " minutes</p>") }) } function getRestaurantId(htmlId) { var match = htmlId.match(/\d+/g); return match[0]; } setInterval(checkAllWaittime, 60000) })
Clean up wording, not worth a re-release.
<?php /* $Id:$ */ // Wrapper code for opening a new window. // //This program is free software; you can redistribute it and/or //modify it under the terms of version 2 of the GNU General Public //License as published by the Free Software Foundation. // //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 General Public License for more details. ?> <h2> Java SSH </h2> If necessary re-enter the maint user and password. Once the applet has opened enter the IP address of your PBX. You will then connect to the FreePBX server. You can then login as 'root' or 'asterisk', or whatever user you have created. <APPLET CODE="com.mindbright.application.MindTerm.class" ARCHIVE="/admin/modules/javassh/mindterm.jar" WIDTH=0 HEIGHT=0> <PARAM NAME="cabinets" VALUE="/admin/modules/javassh/mindterm.cab"> <PARAM NAME="sepframe" value="true"> <PARAM NAME="debug" value="false"> </APPLET> </div>
<?php /* $Id:$ */ // Wrapper code for opening a new window. // //This program is free software; you can redistribute it and/or //modify it under the terms of version 2 of the GNU General Public //License as published by the Free Software Foundation. // //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 General Public License for more details. ?> <h2> Java SSH </h2> If necessary re-enter the maint user and password. Once the applet has opened enter the IP address of your PBX. Log in with the CentOS user name and password <APPLET CODE="com.mindbright.application.MindTerm.class" ARCHIVE="/admin/modules/javassh/mindterm.jar" WIDTH=0 HEIGHT=0> <PARAM NAME="cabinets" VALUE="/admin/modules/javassh/mindterm.cab"> <PARAM NAME="sepframe" value="true"> <PARAM NAME="debug" value="false"> </APPLET> </div>
Move stream check outside the loop
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; stream_is_local($file) && ($file = realpath($file)); foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); if (0 !== strpos($file, $prefix)) { continue; } $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force); } return $paths; } }
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); stream_is_local($file) && ($file = realpath($file)); if (0 !== strpos($file, $prefix)) { continue; } $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force); } return $paths; } }
Rename blueprint static_pages to staticpages and rename staticpages.show to staticpages.page
# -*- coding: utf-8 -*- """ flask-rst.modules.staticfiles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from flask import Blueprint, current_app, render_template, safe_join from flaskrst.parsers import rstDocument staticpages = Blueprint('staticpages', __name__, template_folder='templates') @staticpages.route('/', defaults={'file_path': 'index'}) @staticpages.route('/<path:file_path>') def page(file_path): if file_path.endswith('/'): file_path += "index" rst_file = safe_join(current_app.config['SOURCE'], file_path + '.rst') rst = rstDocument(rst_file) return render_template("static_page.html", page=rst) def setup(app, cfg): app.register_blueprint(staticpages)
# -*- coding: utf-8 -*- """ flask-rst.modules.staticfiles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ import os from flask import Blueprint, current_app, render_template from flaskrst.parsers import rstDocument static_pages = Blueprint('static_pages', __name__, \ template_folder='templates') @static_pages.route('/', defaults={'file_path': 'index'}) @static_pages.route('/<path:file_path>') def show(file_path): if file_path.endswith('/'): file_path += "index" rst_file = os.path.join(current_app.config['SOURCE'], file_path + '.rst') rst = rstDocument(rst_file) return render_template("static_page.html", page=rst) def setup(app, cfg): app.register_blueprint(static_pages)
Use shorter flavor names for cxx rules Summary:Instead of using file path in the cxx rule flavor, only use its last element. This will shorten the directory names used for rules' outputs, which are currently gettting very close to the filesystem limit. This should be safe because we still append a hash of the full path to the flavor and it should not be too confusing because we still use the file name in the flavor. Test Plan: CI. Reviewed By: Coneko fb-gh-sync-id: bf46338 shipit-source-id: bf46338
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.model.Flavor; import com.google.common.hash.Hashing; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; public class CxxFlavorSanitizer { private CxxFlavorSanitizer() { } public static String sanitize(String name) { String fileName = Paths.get(name).getFileName().toString(); // The hash prevents collisions between "an/example.c", "an_example.c" etc. return Flavor.replaceInvalidCharacters(fileName) + Hashing.murmur3_32().hashString(name, StandardCharsets.UTF_8); } }
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.model.Flavor; import com.google.common.hash.Hashing; import java.nio.charset.StandardCharsets; public class CxxFlavorSanitizer { private CxxFlavorSanitizer() { } public static String sanitize(String name) { // The hash prevents collisions between "an/example.c", "an_example.c" etc. return Flavor.replaceInvalidCharacters(name) + Hashing.murmur3_32().hashString(name, StandardCharsets.UTF_8); } }
Add option to invert `OptionalIf` validator
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from wtforms.validators import Optional class OptionalIf(Optional): # makes a field optional if some other data is supplied or is not supplied def __init__(self, deciding_field, invert=False, *args, **kwargs): self.deciding_field = deciding_field self.invert = invert super(OptionalIf, self).__init__(*args, **kwargs) def __call__(self, form, field): deciding_field = form._fields.get(self.deciding_field) if deciding_field is None: raise Exception('no field named "{}" in form'.format( self.deciding_field)) if (bool(deciding_field.data) and deciding_field.data != 'None')\ ^ self.invert: super(OptionalIf, self).__call__(form, field)
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from wtforms.validators import Optional class OptionalIf(Optional): # makes a field optional if some other data is supplied def __init__(self, deciding_field, *args, **kwargs): self.deciding_field = deciding_field super(OptionalIf, self).__init__(*args, **kwargs) def __call__(self, form, field): deciding_field = form._fields.get(self.deciding_field) if deciding_field is None: raise Exception('no field named "{}" in form'.format( self.deciding_field)) if bool(deciding_field.data): super(OptionalIf, self).__call__(form, field)
Undo async decorator to attempt fix to About page
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import loadComponent from '../../../helpers/loadComponent'; import LayoutContainer from '../../../components/Layout/LayoutContainer'; const title = 'About / Privacy'; export default { path: '/about', action(context) { return loadComponent( () => require.ensure([], require => require('./About').default, 'about') ).then(About => ({ title, chunk: 'about', component: ( <LayoutContainer path={context.url}> <About /> </LayoutContainer> ), })); }, };
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import loadComponent from '../../../helpers/loadComponent'; import LayoutContainer from '../../../components/Layout/LayoutContainer'; const title = 'About / Privacy'; // try to fix a strange ReferenceError in production server build // by defining and assigning About first let About = () => null; export default { path: '/about', async action(context) { About = await loadComponent( () => require.ensure([], require => require('./About').default, 'about') ); return { title, chunk: 'about', component: ( <LayoutContainer path={context.url}> <About /> </LayoutContainer> ), }; }, };
Sort menus only in parent containment
var initMenu=function(){var e="li:not(.toggle-blade-helper)",n=function(e,t){var a=[];return e.children(t).map(function(e,o){var l={key:$(o).data("key")};$(o).children("ul").length>0&&(l.children=n($(o).children("ul"),t)),a.push(l)}),a},t=$("#main-menu");t.sortable({containment:"parent",items:e,stop:function(a){var o=n(t,e);console.log(o),$.ajax({url:t.data("ajax"),headers:{"X-CSRF-TOKEN":$('meta[name="_token"]').attr("content")},type:"POST",data:{menus:JSON.stringify(o)}})}})};$(function(){$(".delete-confirm").on("click",function(){var e=new Confirm("mconsole-table-delete",trans("delete-modal-title"),trans("delete-modal-body"),trans("delete-modal-ok"),trans("delete-modal-cancel"),"btn-danger");return e.show(function(){$(this).closest("form").submit()}.bind(this)),!1}),$(".color-picker").length>0&&$(".color-picker").map(function(e,n){$(n).minicolors({defaultValue:"#0088cc",theme:"bootstrap"})}),initMenu()});
var initMenu=function(){var e="li:not(.toggle-blade-helper)",n=function(e,t){var a=[];return e.children(t).map(function(e,o){var l={key:$(o).data("key")};$(o).children("ul").length>0&&(l.children=n($(o).children("ul"),t)),a.push(l)}),a},t=$("#main-menu");t.sortable({items:e,stop:function(a){var o=n(t,e);console.log(o),$.ajax({url:t.data("ajax"),headers:{"X-CSRF-TOKEN":$('meta[name="_token"]').attr("content")},type:"POST",data:{menus:JSON.stringify(o)}})}})};$(function(){$(".delete-confirm").on("click",function(){var e=new Confirm("mconsole-table-delete",trans("delete-modal-title"),trans("delete-modal-body"),trans("delete-modal-ok"),trans("delete-modal-cancel"),"btn-danger");return e.show(function(){$(this).closest("form").submit()}.bind(this)),!1}),$(".color-picker").length>0&&$(".color-picker").map(function(e,n){$(n).minicolors({defaultValue:"#0088cc",theme:"bootstrap"})}),initMenu()});
Remove redundant VERSION from test sandbox. This is no longer needed due to 22b744b7e60122bee5abb82642ecb4feefa873d0.
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"); require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = null; files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"), version = require("../package.json").version; require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = {VERSION: version}; files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { VERSION: version, console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
Comment out optional base url configuration
import sys from upload_s3 import set_metadata from flask import Flask, render_template from flask_frozen import Freezer app = Flask(__name__) freezer = Freezer(app) app.config['FREEZER_DEFAULT_MIMETYPE'] = 'text/html' app.config['FREEZER_IGNORE_MIMETYPE_WARNINGS'] = True # If project doesn't have it's own domain/subdomain, use BASE_URL # app.config['FREEZER_BASE_URL'] = 'http://www.example.com/not_base' # If Flask is needed to generate URLs, use freezer.register_generator # see: http://pythonhosted.org/Frozen-Flask/#url-generators @app.route('/') def index(): return render_template('content.html') if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'build': freezer.freeze() set_metadata() else: app.run(debug=True)
import sys from upload_s3 import set_metadata from flask import Flask, render_template from flask_frozen import Freezer app = Flask(__name__) freezer = Freezer(app) app.config['FREEZER_DEFAULT_MIMETYPE'] = 'text/html' app.config['FREEZER_IGNORE_MIMETYPE_WARNINGS'] = True app.config['FREEZER_BASE_URL'] = 'http://www.vpr.net/apps/test' # If project doesn't have it's own domain/subdomain, use BASE_URL # app.config['FREEZER_BASE_URL'] = 'http://www.example.com/not_base' # If Flask is needed to generate URLs, use freezer.register_generator # see: http://pythonhosted.org/Frozen-Flask/#url-generators @app.route('/') def index(): return render_template('content.html') @app.route('/test/work') def work(): return render_template('content.html') if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'build': freezer.freeze() set_metadata() else: app.run(debug=True)
Add firefox to the list of karma test browsers
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= module.exports = function(config) { config.set({ frameworks: ['jasmine', 'karma-typescript'], files: [ {pattern: 'src/**/*.ts'} ], preprocessors: { '**/*.ts': ['karma-typescript'], // *.tsx for React Jsx }, karmaTypescriptConfig: { tsconfig: "tsconfig.json" }, reporters: ['progress', 'karma-typescript'], browsers: ['Chrome', 'Firefox'] }); };
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= module.exports = function(config) { config.set({ frameworks: ['jasmine', 'karma-typescript'], files: [ {pattern: 'src/**/*.ts'} ], preprocessors: { '**/*.ts': ['karma-typescript'], // *.tsx for React Jsx }, karmaTypescriptConfig: { tsconfig: "tsconfig.json" }, reporters: ['progress', 'karma-typescript'], browsers: ['Chrome'] }); };
Add default value for package name. If all else fails assume the name of the current folder is the packoge name.
<?php namespace Respect\Foundation\InfoProviders; use DirectoryIterator; class PackageName extends AbstractProvider { public function providerPackageIni() { $iniPath = realpath($this->projectFolder.'/package.ini'); if (!file_exists($iniPath)) return ''; $ini = parse_ini_file($iniPath, true); return $ini['package']['name']; } public function providerFolderStructure() { $vendorFolder = new LibraryFolder($this->projectFolder); if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder))) foreach (new DirectoryIterator((string) $vendorFolder) as $vendor) if (!$vendor->isDot() && $vendor->isDir()) return $vendor->getFileName(); } public function providerDefault() { return ucfirst(preg_replace('#^.*'.DIRECTORY_SEPARATOR.'(?=\w$)#U', '', $this->projectFolder)); } }
<?php namespace Respect\Foundation\InfoProviders; use DirectoryIterator; class PackageName extends AbstractProvider { public function providerPackageIni() { $iniPath = realpath($this->projectFolder.'/package.ini'); if (!file_exists($iniPath)) return ''; $ini = parse_ini_file($iniPath, true); return $ini['package']['name']; } public function providerFolderStructure() { $vendorFolder = new LibraryFolder($this->projectFolder); if (file_exists($vendorFolder .= DIRECTORY_SEPARATOR . new VendorName($this->projectFolder))) foreach (new DirectoryIterator((string) $vendorFolder) as $vendor) if (!$vendor->isDot() && $vendor->isDir()) return $vendor->getFileName(); } }
Attach main function directly to exports, linting
/* * gulp-hub * https://github.com/frankwallis/gulp-hub * * Copyright (c) 2014 Frank Wallis * Licensed under the MIT license. */ var gulp = require('gulp'); var path = require('path'); var util = require('gulp-util'); var runSequence = require('run-sequence'); var resolveGlob = require('./resolve-glob'); var getSubfiles = require('./get-subfiles'); var loadSubfile = require('./load-subfile'); var addTask = require('./add-task'); var tasks = {}; module.exports = function(pattern) { // assert `pattern` is a valid glob (non-empty string) or array of globs var isString = typeof pattern === 'string'; var isArray = Array.isArray(pattern); if ((!isString && !isArray) || (pattern.length === 0)) { throw new TypeError('A glob pattern or an array of glob patterns is required.'); } // find all the gulpfiles - needs to happen synchronously so we create the tasks before gulp runs var filelist = resolveGlob(pattern); var subfiles = getSubfiles(filelist); // load all the gulpfiles subfiles.forEach(function (subfile) { util.log( 'Loading', util.colors.yellow(subfile.relativePath)); loadSubfile(subfile); }); // create the task tree for (var name in tasks) { if (tasks.hasOwnProperty(name)) { addTask(tasks[name]); } } };
/* * gulp-hub * https://github.com/frankwallis/gulp-hub * * Copyright (c) 2014 Frank Wallis * Licensed under the MIT license. */ var gulp = require('gulp'); var path = require('path'); var util = require('gulp-util'); var runSequence = require('run-sequence'); var resolveGlob = require('./resolve-glob'); var getSubfiles = require('./get-subfiles'); var loadSubfile = require('./load-subfile'); var addTask = require('./add-task'); var tasks = {}; function hub(pattern) { // assert `pattern` is a valid glob (non-empty string) or array of globs var isString = typeof pattern === 'string'; var isArray = Array.isArray(pattern); if ((!isString && !isArray) || (pattern.length === 0)) { throw new TypeError('A glob pattern or an array of glob patterns is required.'); } // find all the gulpfiles - needs to happen synchronously so we create the tasks before gulp runs var filelist = resolveGlob(pattern); var subfiles = getSubfiles(filelist); // load all the gulpfiles subfiles.forEach(function (subfile) { util.log( 'Loading', util.colors.yellow(subfile.relativePath)); loadSubfile(subfile); }); // create the task tree for (var name in tasks) { if (tasks.hasOwnProperty(name)) { addTask(tasks[name]); } } } module.exports = hub;
Use toString instead of asString
define(['./node', './joinId', './imports'], function ( node, joinId, imports) { return function (requestedFiles, nodes) { var is = imports(requestedFiles, nodes); var trees = []; requestedFiles.forEach(function (file) { var index = {}; nodes.forEach(function (n) { index[joinId(n.getId())] = n; }); var id = joinId(file.getId()); var children = index[id].getNestedNodes().map(function (c) { return node(c, index); }); trees.push({ name : file.getFilename().toString(), meta : "file", imports : is[id], id : id, nodes : children }); }); return trees; }; });
define(['./node', './joinId', './imports'], function ( node, joinId, imports) { return function (requestedFiles, nodes) { var is = imports(requestedFiles, nodes); var trees = []; requestedFiles.forEach(function (file) { var index = {}; nodes.forEach(function (n) { index[joinId(n.getId())] = n; }); var id = joinId(file.getId()); var children = index[id].getNestedNodes().map(function (c) { return node(c, index); }); trees.push({ name : file.getFilename().asString(), meta : "file", imports : is[id], id : id, nodes : children }); }); return trees; }; });
Update User API - ADD type hints - Remove unused imports
# stdlib from typing import Any from typing import Callable # syft relative from ...messages.user_messages import CreateUserMessage from ...messages.user_messages import DeleteUserMessage from ...messages.user_messages import GetUserMessage from ...messages.user_messages import GetUsersMessage from ...messages.user_messages import UpdateUserMessage from .request_api import GridRequestAPI class UserRequestAPI(GridRequestAPI): response_key = "user" def __init__(self, send: Callable): super().__init__( create_msg=CreateUserMessage, get_msg=GetUserMessage, get_all_msg=GetUsersMessage, update_msg=UpdateUserMessage, delete_msg=DeleteUserMessage, send=send, response_key=UserRequestAPI.response_key, ) def __getitem__(self, key: int) -> Any: return self.get(user_id=key) def __delitem__(self, key: int) -> None: self.delete(user_id=key)
# stdlib from typing import Any from typing import Dict # third party from pandas import DataFrame # syft relative from ...messages.user_messages import CreateUserMessage from ...messages.user_messages import DeleteUserMessage from ...messages.user_messages import GetUserMessage from ...messages.user_messages import GetUsersMessage from ...messages.user_messages import UpdateUserMessage from .request_api import GridRequestAPI class UserRequestAPI(GridRequestAPI): response_key = "user" def __init__(self, send): super().__init__( create_msg=CreateUserMessage, get_msg=GetUserMessage, get_all_msg=GetUsersMessage, update_msg=UpdateUserMessage, delete_msg=DeleteUserMessage, send=send, response_key=UserRequestAPI.response_key, ) def __getitem__(self, key): return self.get(user_id=key) def __delitem__(self, key): self.delete(user_id=key)
Add a test for a "real" nodetool command, not only "help" Patch by Alex Petrov; reviewed by Yifan Cai for CASSANDRA-15429
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.distributed.test; import org.junit.Test; import org.apache.cassandra.distributed.Cluster; import static org.junit.Assert.assertEquals; public class NodeToolTest extends DistributedTestBase { @Test public void test() throws Throwable { try (Cluster cluster = init(Cluster.create(1))) { assertEquals(0, cluster.get(1).nodetool("help")); assertEquals(0, cluster.get(1).nodetool("flush")); assertEquals(1, cluster.get(1).nodetool("not_a_legal_command")); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.distributed.test; import org.junit.Test; import org.apache.cassandra.distributed.Cluster; import static org.junit.Assert.assertEquals; public class NodeToolTest extends DistributedTestBase { @Test public void test() throws Throwable { try (Cluster cluster = init(Cluster.create(1))) { assertEquals(0, cluster.get(1).nodetool("help")); assertEquals(1, cluster.get(1).nodetool("not_a_legal_command")); } } }
Allow connection from any host
package ${package}.server; import java.io.IOException; import java.net.URI; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; /** Starts REST server based on Jersey. */ final class Main implements ContainerResponseFilter { public static void main(String... args) throws Exception { ResourceConfig rc = new ResourceConfig( ContactsResource.class, Main.class ); URI u = new URI("http://0.0.0.0:8080/"); HttpServer server = GrizzlyHttpServerFactory.createHttpServer(u, rc); System.err.println("Press Enter to shutdown the server"); System.in.read(); server.stop(); } @Override public void filter( ContainerRequestContext requestContext, ContainerResponseContext r ) throws IOException { r.getHeaders().add("Access-Control-Allow-Origin", "*"); r.getHeaders().add("Access-Control-Allow-Credentials", "true"); r.getHeaders().add("Access-Control-Allow-Headers", "Content-Type"); r.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); } }
package ${package}.server; import java.io.IOException; import java.net.URI; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; /** Starts REST server based on Jersey. */ final class Main implements ContainerResponseFilter { public static void main(String... args) throws Exception { ResourceConfig rc = new ResourceConfig( ContactsResource.class, Main.class ); URI u = new URI("http://localhost:8080/"); HttpServer server = GrizzlyHttpServerFactory.createHttpServer(u, rc); System.err.println("Press Enter to shutdown the server"); System.in.read(); server.stop(); } @Override public void filter( ContainerRequestContext requestContext, ContainerResponseContext r ) throws IOException { r.getHeaders().add("Access-Control-Allow-Origin", "*"); r.getHeaders().add("Access-Control-Allow-Credentials", "true"); r.getHeaders().add("Access-Control-Allow-Headers", "Content-Type"); r.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); } }
Update the PyPI version to 0.2.13
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.14', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.13', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )