text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove obsolete import and fix formatting in test.
package hello; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @RunWith(SpringRunner.class) @SpringBootTest(classes = Hello.class) @AutoConfigureMockMvc @ActiveProfiles("test") public class HomePageTest { @Autowired private MockMvc mvc; @Test public void getRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()); } @Test public void getJsonRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
package hello; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import hello.Hello; @RunWith(SpringRunner.class) @SpringBootTest(classes = Hello.class) @AutoConfigureMockMvc @ActiveProfiles("test") public class HomePageTest { @Autowired private MockMvc mvc; @Test public void getRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()); } @Test public void getJsonRoot() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
Make precompiled script plugin sample backwards compatible with JDK8
package com.example; import org.gradle.api.DefaultTask; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.ListProperty; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.TaskAction; import org.gradle.util.GFileUtils; import java.io.IOException; import java.nio.file.Files; import java.util.regex.Pattern; /** * Verifies that the given readme file contains the desired patterns. */ public abstract class ReadmeVerificationTask extends DefaultTask { @PathSensitive(PathSensitivity.RELATIVE) @InputFile public abstract RegularFileProperty getReadme(); @Internal public abstract ListProperty<String> getReadmePatterns(); @TaskAction void verifyServiceReadme() throws IOException { String readmeContents = new String (Files.readAllBytes(getReadme().getAsFile().get().toPath())); for (String requiredSection : getReadmePatterns().get()) { Pattern pattern = Pattern.compile(requiredSection, Pattern.MULTILINE); if (!pattern.matcher(readmeContents).find()) { throw new RuntimeException("README should contain section: " + pattern.pattern()); } } } }
package com.example; import org.gradle.api.DefaultTask; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.ListProperty; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.TaskAction; import org.gradle.util.GFileUtils; import java.io.IOException; import java.nio.file.Files; import java.util.regex.Pattern; /** * Verifies that the given readme file contains the desired patterns. */ public abstract class ReadmeVerificationTask extends DefaultTask { @PathSensitive(PathSensitivity.RELATIVE) @InputFile public abstract RegularFileProperty getReadme(); @Internal public abstract ListProperty<String> getReadmePatterns(); @TaskAction void verifyServiceReadme() throws IOException { String readmeContents = Files.readString(getReadme().getAsFile().get().toPath()); for (String requiredSection : getReadmePatterns().get()) { Pattern pattern = Pattern.compile(requiredSection, Pattern.MULTILINE); if (!pattern.matcher(readmeContents).find()) { throw new RuntimeException("README should contain section: " + pattern.pattern()); } } } }
Add a mechanism for creating and deleting a bucket after a dataflow test.
package com.neverwinterdp.scribengin.dataflow.test; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParametersDelegate; import com.neverwinterdp.scribengin.client.shell.ScribenginShell; import com.neverwinterdp.scribengin.storage.s3.S3Client; public class S3DataflowTest extends DataflowTest { @ParametersDelegate private DataflowSourceGenerator sourceGenerator = new S3DataflowSourceGenerator(); @ParametersDelegate private DataflowSinkValidator sinkValidator = new S3DataflowSinkValidator(); private S3Client s3Client; final static public String TEST_NAME = "s3-to-s3"; @Parameter(names = "--source-auto-create-bucket", description = "Enable auto creating a bucket") protected boolean sourceAutoCreateBucket = false; @Parameter(names = "--sink-auto-delete-bucket", description = "Enable auto deleting a bucket") protected boolean sinkAutoDeleteBucket = false; protected void doRun(ScribenginShell shell) throws Exception { s3Client = new S3Client(); s3Client.onInit(); if (sourceAutoCreateBucket) { s3Client.createBucket(sourceGenerator.sourceLocation); } sourceToSinkDataflowTest(shell, sourceGenerator, sinkValidator); if (sinkAutoDeleteBucket) { s3Client.deleteBucket(sinkValidator.sinkLocation, true); } s3Client.onDestroy(); } }
package com.neverwinterdp.scribengin.dataflow.test; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParametersDelegate; import com.neverwinterdp.scribengin.client.shell.ScribenginShell; import com.neverwinterdp.scribengin.storage.s3.S3Client; public class S3DataflowTest extends DataflowTest { @ParametersDelegate private DataflowSourceGenerator sourceGenerator = new S3DataflowSourceGenerator(); @ParametersDelegate private DataflowSinkValidator sinkValidator = new S3DataflowSinkValidator(); private S3Client s3Client; final static public String TEST_NAME = "s3-to-s3"; @Parameter(names = "----source-auto-create-bucket", description = "Enable auto creating a bucket") protected boolean sourceAutoCreateBucket = false; @Parameter(names = "----sink-auto-delete-bucket", description = "Enable auto deleting a bucket") protected boolean sinkAutoDeleteBucket = false; protected void doRun(ScribenginShell shell) throws Exception { s3Client = new S3Client(); s3Client.onInit(); if (sourceAutoCreateBucket) { s3Client.createBucket(sourceGenerator.sourceLocation); } sourceToSinkDataflowTest(shell, sourceGenerator, sinkValidator); if (sinkAutoDeleteBucket) { s3Client.deleteBucket(sinkValidator.sinkLocation, true); } s3Client.onDestroy(); } }
Rename result file of a replay from `result.replay` to `replay.result`
package de.retest.recheck; import java.util.Set; import de.retest.ui.DefaultValueFinder; import de.retest.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the replay.result to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); }
package de.retest.recheck; import java.util.Set; import de.retest.ui.DefaultValueFinder; import de.retest.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the result.replay to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); }
Support for YouTube 2020 CSS changes
function main() { // Define video & thumbnail HTML element classes var videoClasses = '.html5-video-container'; var thumbnailClasses = '.yt-uix-simple-thumb-wrap, .yt-thumb img, .yt-img-shadow, .ytp-thumbnail-overlay, .pl-header-thumb'; // Add transition for the blur effect $(thumbnailClasses).css('-webkit-transition', '-webkit-filter ease-in-out 0.35s'); // Get enabled flag chrome.storage.local.get('enabled', function (result) { // Extension enabled? if (result.enabled == false) { // Hide HTML5 video player element $(videoClasses).show(); // Un-do blur $(thumbnailClasses).css('-webkit-filter', 'none'); // Stop execution return; } // Hide HTML5 video player element $(videoClasses).hide(); // Blur out thumbnails $(thumbnailClasses).css('-webkit-filter', 'blur(5px)'); }); } // Ugly hack // TODO: Find a cleaner way to do this setInterval(main, 100);
function main() { // Define video & thumbnail HTML element classes var videoClasses = '.html5-video-container'; var thumbnailClasses = '.yt-uix-simple-thumb-wrap, .yt-thumb img, .ytp-thumbnail-overlay, .pl-header-thumb'; // Add transition for the blur effect $(thumbnailClasses).css('-webkit-transition', '-webkit-filter ease-in-out 0.35s'); // Get enabled flag chrome.storage.local.get('enabled', function (result) { // Extension enabled? if (result.enabled == false) { // Hide HTML5 video player element $(videoClasses).show(); // Un-do blur $(thumbnailClasses).css('-webkit-filter', 'none'); // Stop execution return; } // Hide HTML5 video player element $(videoClasses).hide(); // Blur out thumbnails $(thumbnailClasses).css('-webkit-filter', 'blur(5px)'); }); } // Ugly hack // TODO: Find a cleaner way to do this setInterval(main, 100);
Fix the wrong method because of a rename in the annotation
package info.u_team.u_team_core.integration; import org.apache.logging.log4j.*; import org.objectweb.asm.Type; import info.u_team.u_team_core.api.integration.*; import info.u_team.u_team_core.util.AnnotationUtil; import net.minecraftforge.fml.ModList; import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData; public class IntegrationManager { private static final Logger LOGGER = LogManager.getLogger("IntegrationManager"); public static void constructIntegrations(String modid) { for (AnnotationData data : AnnotationUtil.getAnnotations(modid, Type.getType(Integration.class))) { final String annotationModid = (String) data.getAnnotationData().get("modid"); final String integrationModid = (String) data.getAnnotationData().get("integration"); if (modid.equals(annotationModid)) { if (ModList.get().isLoaded(integrationModid)) { LOGGER.info("Try to load " + integrationModid + " integration for mod " + modid); try { Class.forName(data.getMemberName()).asSubclass(IModIntegration.class).newInstance().construct(); } catch (LinkageError | ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException ex) { LOGGER.error("Failed to load and construct integration : {}", data.getMemberName(), ex); throw new RuntimeException(ex); } } } } } }
package info.u_team.u_team_core.integration; import org.apache.logging.log4j.*; import org.objectweb.asm.Type; import info.u_team.u_team_core.api.integration.*; import info.u_team.u_team_core.util.AnnotationUtil; import net.minecraftforge.fml.ModList; import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData; public class IntegrationManager { private static final Logger LOGGER = LogManager.getLogger("IntegrationManager"); public static void constructIntegrations(String modid) { for (AnnotationData data : AnnotationUtil.getAnnotations(modid, Type.getType(Integration.class))) { final String annotationModid = (String) data.getAnnotationData().get("modid"); final String integrationModid = (String) data.getAnnotationData().get("value"); if (modid.equals(annotationModid)) { if (ModList.get().isLoaded(integrationModid)) { LOGGER.info("Try to load " + integrationModid + " integration for mod " + modid); try { Class.forName(data.getMemberName()).asSubclass(IModIntegration.class).newInstance().construct(); } catch (LinkageError | ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException ex) { LOGGER.error("Failed to load and construct integration : {}", data.getMemberName(), ex); throw new RuntimeException(ex); } } } } } }
Add test for get products when no store is specified
<?php /** * @loadSharedFixture */ class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case { public function testCanGetRandomProducts() { Mage::app()->setCurrentStore(1); $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']); Mage::app()->setCurrentStore(0); } public function testIfAStoreHasNoProductsNothingIsReturned() { $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1); $this->assertEmpty($products); } public function testCanGetRandomProductsIfNoStoreIsDefined() { $products = ShopymindClient_Callback::getProducts(null, false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']); } }
<?php /** * @loadSharedFixture */ class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case { public function testCanGetRandomProducts() { Mage::app()->setCurrentStore(1); $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1); $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']); Mage::app()->setCurrentStore(0); } public function testIfAStoreHasNoProductsNothingIsReturned() { $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1); $this->assertEmpty($products); } }
Fix STATIC_URL (for Django 1.5 admin tests)
#!/usr/bin/env python import sys from os.path import abspath, dirname from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( ROOT_URLCONF='simple_history.tests.urls', STATIC_URL='/static/', INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'simple_history', 'simple_history.tests' ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ) def main(): from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == "__main__": main()
#!/usr/bin/env python import sys from os.path import abspath, dirname from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( ROOT_URLCONF='simple_history.tests.urls', INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'simple_history', 'simple_history.tests' ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ) def main(): from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == "__main__": main()
Add 'sent items' to default folder mapping
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154 INBOX = 'inbox' DRAFTS = 'drafts' SPAM = 'spam' ARCHIVE = 'archive' SENT = 'sent' TRASH = 'trash' ALL = 'all' IMPORTANT = 'important' # Default mapping to unify various provider behaviors DEFAULT_FOLDER_MAPPING = { 'inbox': INBOX, 'drafts': DRAFTS, 'draft': DRAFTS, 'junk': SPAM, 'spam': SPAM, 'archive': ARCHIVE, 'sent': SENT, 'sent items': SENT, 'trash': TRASH, 'all': ALL, 'important': IMPORTANT, } DEFAULT_FOLDER_FLAGS = { '\\Trash': 'trash', '\\Sent': 'sent', '\\Drafts': 'drafts', '\\Junk': 'spam', '\\Inbox': 'inbox', '\\Spam': 'spam' }
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154 INBOX = 'inbox' DRAFTS = 'drafts' SPAM = 'spam' ARCHIVE = 'archive' SENT = 'sent' TRASH = 'trash' ALL = 'all' IMPORTANT = 'important' # Default mapping to unify various provider behaviors DEFAULT_FOLDER_MAPPING = { 'inbox': INBOX, 'drafts': DRAFTS, 'draft': DRAFTS, 'junk': SPAM, 'spam': SPAM, 'archive': ARCHIVE, 'sent': SENT, 'trash': TRASH, 'all': ALL, 'important': IMPORTANT, } DEFAULT_FOLDER_FLAGS = { '\\Trash': 'trash', '\\Sent': 'sent', '\\Drafts': 'drafts', '\\Junk': 'spam', '\\Inbox': 'inbox', '\\Spam': 'spam' }
Use importlib.import_module instead of __import__.
import builtins import operator import functools import importlib from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '==': operator.eq , '!=': operator.ne , '>': operator.gt , '>=': operator.ge , 'is': operator.is_ , 'in': lambda a, b: a in b , 'not': operator.not_ , '~': operator.invert , '+': varary(operator.pos, operator.add) , '-': varary(operator.neg, operator.sub) , '*': operator.mul , '**': operator.pow , '/': operator.truediv , '//': operator.floordiv , '%': operator.mod , '!!': operator.getitem , '&': operator.and_ , '^': operator.xor , '|': operator.or_ , '<<': operator.lshift , '>>': operator.rshift # Useful stuff. , 'import': importlib.import_module , 'foldl': functools.reduce , '~:': functools.partial })
import builtins import operator import functools from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '==': operator.eq , '!=': operator.ne , '>': operator.gt , '>=': operator.ge , 'is': operator.is_ , 'in': lambda a, b: a in b , 'not': operator.not_ , '~': operator.invert , '+': varary(operator.pos, operator.add) , '-': varary(operator.neg, operator.sub) , '*': operator.mul , '**': operator.pow , '/': operator.truediv , '//': operator.floordiv , '%': operator.mod , '!!': operator.getitem , '&': operator.and_ , '^': operator.xor , '|': operator.or_ , '<<': operator.lshift , '>>': operator.rshift # Useful stuff. , 'import': __import__ , 'foldl': functools.reduce , '~:': functools.partial })
Use testtools as test base class. On the path to testr migration, we need to replace the unittest base classes with testtools. Replace tearDown with addCleanup, addCleanup is more resilient than tearDown. The fixtures library has excellent support for managing and cleaning tempfiles. Use it. Replace skip_ with testtools.skipTest Part of blueprint grizzly-testtools. Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import unittest from openstack.common import context class ContextTest(unittest.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
Add enabled flag as courtesy
/* * Copyright 2013-2015 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.springframework.cloud.sleuth.zipkin; import org.springframework.boot.context.properties.ConfigurationProperties; import com.github.kristofa.brave.zipkin.ZipkinSpanCollectorParams; import lombok.Data; /** * @author Spencer Gibb */ @ConfigurationProperties("spring.zipkin") @Data public class ZipkinProperties { // Sample rate = 1 means every request will get traced. private int fixedSampleRate = 1; private String host = "localhost"; private int port = 9410; private boolean enabled = true; private ZipkinSpanCollectorParams collector = new ZipkinSpanCollectorParams(); }
/* * Copyright 2013-2015 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.springframework.cloud.sleuth.zipkin; import org.springframework.boot.context.properties.ConfigurationProperties; import com.github.kristofa.brave.zipkin.ZipkinSpanCollectorParams; import lombok.Data; /** * @author Spencer Gibb */ @ConfigurationProperties("spring.zipkin") @Data public class ZipkinProperties { // Sample rate = 1 means every request will get traced. private int fixedSampleRate = 1; private String host = "localhost"; private int port = 9410; private ZipkinSpanCollectorParams collector = new ZipkinSpanCollectorParams(); }
Put nbresuse js files in appropriate path How did this work before?
from glob import glob import setuptools setuptools.setup( name="nbresuse", version='0.2.0', url="https://github.com/yuvipanda/nbresuse", author="Yuvi Panda", description="Simple Jupyter extension to show how much resources (RAM) your notebook is using", packages=setuptools.find_packages(), install_requires=[ 'psutil', 'notebook', ], data_files=[ ('share/jupyter/nbextensions/nbresuse', glob('nbresuse/static/*')), ('etc/jupyter/jupyter_notebook_config.d', ['nbresuse/etc/serverextension.json']), ('etc/jupyter/nbconfig/notebook.d', ['nbresuse/etc/nbextension.json']) ], zip_safe=False, include_package_data=True )
import setuptools setuptools.setup( name="nbresuse", version='0.2.0', url="https://github.com/yuvipanda/nbresuse", author="Yuvi Panda", description="Simple Jupyter extension to show how much resources (RAM) your notebook is using", packages=setuptools.find_packages(), install_requires=[ 'psutil', 'notebook', ], package_data={'nbresuse': ['static/*']}, data_files=[ ('etc/jupyter/jupyter_notebook_config.d', ['nbresuse/etc/serverextension.json']), ('etc/jupyter/nbconfig/notebook.d', ['nbresuse/etc/nbextension.json']) ], zip_safe=False, include_package_data=True )
Add cheat to the game
var LEDModule = require('./lib/modules/LEDModule'); var ModuleLoader = require('./lib/ModuleLoader'); var WebSocketServer = require('./lib/WebSocketServer'); var led = new LEDModule(); var server = new WebSocketServer(3000); var moduleLoader = new ModuleLoader({ Accelerometer: 'A', Ambient: 'C' }); /** * Triggers when accelerometer data is received * @param data * @private */ function _onAccelerometerData(data) { server.send({ type: 'accelerometer', data: data }); } /** * Triggers when clap sound is triggered * @param data * @private */ function _onRestartGame(data) { server.send({ type: 'restart', data: data }); } /** * Triggers when cheat is activated * @private */ function _onCheatActivated() { server.send({ type: 'cheat', data: {} }); } /** * Triggers when all modules is ready to work * @param {Object} modules * @private */ function _onModulesReady(modules) { modules.Accelerometer.getNativeModule().on('data', _onAccelerometerData); modules.Ambient.onClapTrigger(_onRestartGame, 2); modules.Ambient.onClapTrigger(_onCheatActivated, 1); led.on('LED2'); } moduleLoader.on('ready', _onModulesReady);
var LEDModule = require('./lib/modules/LEDModule'); var ModuleLoader = require('./lib/ModuleLoader'); var WebSocketServer = require('./lib/WebSocketServer'); var led = new LEDModule(); var server = new WebSocketServer(3000); var moduleLoader = new ModuleLoader({ Accelerometer: 'A', Ambient: 'C' }); /** * Triggers when accelerometer data is received * @param data * @private */ function _onAccelerometerData(data) { server.send({ type: 'accelerometer', data: data }); } /** * Triggers when clap sound is triggered * @param data * @private */ function _onClapTrigger(data) { server.send({ type: 'restart', data: data }); } /** * Triggers when all modules is ready to work * @param {Object} modules * @private */ function _onModulesReady(modules) { modules.Accelerometer.getNativeModule().on('data', _onAccelerometerData); modules.Ambient.onClapTrigger(_onClapTrigger); led.on('LED2'); } moduleLoader.on('ready', _onModulesReady);
Order parents in Admin select field
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Fix typo in FXML file name
package com.gitrekt.resort.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; /** * FXML Controller class for reports home screen. */ public class ReportsHomeScreenController implements Initializable { @FXML private Button backButton; @FXML private Button bookingPercentagesReportButton; @FXML private Button feedbackReportButton; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void onBackButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/StaffHomeScreen.fxml" ); } public void onBookingPercentagesReportButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/BookingsReportScreen.fxml" ); } public void onFeedbackReportButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/FeedbackReportScreen.fxml" ); } }
package com.gitrekt.resort.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; /** * FXML Controller class for reports home screen. */ public class ReportsHomeScreenController implements Initializable { @FXML private Button backButton; @FXML private Button bookingPercentagesReportButton; @FXML private Button feedbackReportButton; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void onBackButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/StaffHomeScreen.fxml" ); } public void onBookingPercentagesReportButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/BookingReportScreen.fxml" ); } public void onFeedbackReportButtonClicked() { ScreenManager.getInstance().switchToScreen( "/fxml/FeedbackReportScreen.fxml" ); } }
SO-3379: Add text/csv media type constant
/* * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.api.rest; /** * @since 1.0 */ public abstract class AbstractRestService { /** * The currently supported versioned media type of the snowowl RESTful API. */ public static final String SO_MEDIA_TYPE = "application/vnd.com.b2international.snowowl+json"; public static final String CSV_MEDIA_TYPE = "text/csv"; }
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.api.rest; /** * @since 1.0 */ public abstract class AbstractRestService { /** * The currently supported versioned media type of the snowowl RESTful API. */ public static final String SO_MEDIA_TYPE = "application/vnd.com.b2international.snowowl+json"; }
Test all functions in basic composition test, deliberately misorder them.
package sqlc import ( "reflect" "runtime" "strings" "testing" ) func TestBasicComposition(t *testing.T) { s := Statement{} // These statements are deliberately out of order s = s.Group("role").Order("id").Limit("30") s = s.Where("name = 'Marge'") s = s.Select("*").From("Employees") sql, args := s.ToSQL() expect(t, args, make([]interface{}, 0)) expect(t, sql, strings.TrimSpace(` SELECT * FROM Employees WHERE (name = 'Marge') GROUP BY role ORDER BY id LIMIT 30 `)) } func TestArgumentComposition(t *testing.T) { s := Statement{} s = s.Where("name = ?", "Marge").Where("role = ?", "Comptroller") sql, args := s.ToSQL() expect(t, args, []interface{}{"Marge", "Comptroller"}) expect(t, sql, strings.TrimSpace("WHERE (name = ?) AND (role = ?)")) } /* Test Helpers */ func expect(t *testing.T, a interface{}, b interface{}) { if !reflect.DeepEqual(a, b) { _, _, line, _ := runtime.Caller(1) t.Errorf("line %d: Got %#v, expected %#v", line, a, b) } }
package sqlc import ( "reflect" "runtime" "strings" "testing" ) func TestBasicComposition(t *testing.T) { s := Statement{} s = s.Select("*").From("Employees").Where("name = 'Marge'").Order("id") sql, args := s.ToSQL() expect(t, args, make([]interface{}, 0)) expect(t, sql, strings.TrimSpace(` SELECT * FROM Employees WHERE (name = 'Marge') ORDER BY id `)) } func TestArgumentComposition(t *testing.T) { s := Statement{} s = s.Where("name = ?", "Marge").Where("role = ?", "Comptroller") sql, args := s.ToSQL() expect(t, args, []interface{}{"Marge", "Comptroller"}) expect(t, sql, strings.TrimSpace("WHERE (name = ?) AND (role = ?)")) } /* Test Helpers */ func expect(t *testing.T, a interface{}, b interface{}) { if !reflect.DeepEqual(a, b) { _, _, line, _ := runtime.Caller(1) t.Errorf("line %d: Got %#v, expected %#v", line, a, b) } }
Support mach3 style comments with parentheses.
/** * Parses a string of gcode instructions, and invokes handlers for * each type of command. * * Special handler: * 'default': Called if no other handler matches. */ function GCodeParser(handlers) { this.handlers = handlers || {}; } GCodeParser.prototype.parseLine = function(text, info) { text = text.replace(/[;(].*$/, '').trim(); // Remove comments if (text) { var tokens = text.split(' '); if (tokens) { var cmd = tokens[0]; var args = { 'cmd': cmd }; tokens.splice(1).forEach(function(token) { var key = token[0].toLowerCase(); var value = parseFloat(token.substring(1)); args[key] = value; }); var handler = this.handlers[tokens[0]] || this.handlers['default']; if (handler) { return handler(args, info); } } } }; GCodeParser.prototype.parse = function(gcode) { var lines = gcode.split('\n'); for (var i = 0; i < lines.length; i++) { if (this.parseLine(lines[i], i) === false) { break; } } };
/** * Parses a string of gcode instructions, and invokes handlers for * each type of command. * * Special handler: * 'default': Called if no other handler matches. */ function GCodeParser(handlers) { this.handlers = handlers || {}; } GCodeParser.prototype.parseLine = function(text, info) { text = text.replace(/;.*$/, '').trim(); // Remove comments if (text) { var tokens = text.split(' '); if (tokens) { var cmd = tokens[0]; var args = { 'cmd': cmd }; tokens.splice(1).forEach(function(token) { var key = token[0].toLowerCase(); var value = parseFloat(token.substring(1)); args[key] = value; }); var handler = this.handlers[tokens[0]] || this.handlers['default']; if (handler) { return handler(args, info); } } } }; GCodeParser.prototype.parse = function(gcode) { var lines = gcode.split('\n'); for (var i = 0; i < lines.length; i++) { if (this.parseLine(lines[i], i) === false) { break; } } };
Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
Hide dialog when leaving route
import Ember from "ember"; export default Ember.Component.extend({ didInsertElement: function() { // show the dialog this.$('.modal').modal('show'); // send the according action after it has been hidden again var _this = this; this.$('.modal').one('hidden.bs.modal', function() { Ember.run(function() { // send the according action after it has been hidden _this.sendAction("dismiss"); }); }); }, willDestroyElement: function() { this.$('.modal').modal('hide'); }, showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'), actions: { accept: function() { this.sendAction("accept"); }, doNotAccept: function() { this.sendAction("doNotAccept"); }, cancel: function() { this.sendAction("cancel"); } } });
import Ember from "ember"; export default Ember.Component.extend({ didInsertElement: function() { // show the dialog this.$('.modal').modal('show'); // send the according action after it has been hidden again var _this = this; this.$('.modal').one('hidden.bs.modal', function() { Ember.run(function() { // send the according action after it has been hidden _this.sendAction("dismiss"); }); }); }, showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'), actions: { accept: function() { this.sendAction("accept"); }, doNotAccept: function() { this.sendAction("doNotAccept"); }, cancel: function() { this.sendAction("cancel"); } } });
Add a test method to test wildcard matcher parsing
package org.monospark.spongematchers.type; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches; import org.junit.Test; import org.monospark.spongematchers.matcher.SpongeMatcher; import org.monospark.spongematchers.parser.SpongeMatcherParseException; import org.monospark.spongematchers.parser.element.StringElementParser; import org.monospark.spongematchers.type.MatcherType; public class MatcherTypeTest { @Test public void parseMatcher_MatcherWithConjunctions_ReturnsCorrectMatcher() throws SpongeMatcherParseException { String input = "(('test1'|'test2')&!('test2'))"; SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input)); assertThat(matcher, matches("test1")); assertThat(matcher, not(matches("test2"))); } @Test public void parseMatcher_WildcardMatcher_ReturnsCorrectMatcher() throws SpongeMatcherParseException { String input = "*"; SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input)); assertThat(matcher, matches("test1")); assertThat(matcher, matches("test2")); } }
package org.monospark.spongematchers.type; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches; import org.junit.Test; import org.monospark.spongematchers.matcher.SpongeMatcher; import org.monospark.spongematchers.parser.SpongeMatcherParseException; import org.monospark.spongematchers.parser.element.StringElementParser; import org.monospark.spongematchers.type.MatcherType; public class MatcherTypeTest { @Test public void parseMatcher_MatcherWithConjunctions_ReturnsCorrectMatcher() throws SpongeMatcherParseException { String input = "(('test1'|'test2')&!('test2'))"; SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input)); assertThat(matcher, matches("test1")); assertThat(matcher, not(matches("test2"))); } }
Use proper spinegar wrapper again.
<?php namespace BisonLab\SugarCrmBundle\Service; /* * Just a service object for the sugar7crm-wrapper class. */ class SugarWrapper { private $sugar; private $options; public function __construct($base_url, $username, $password) { $this->options = array('base_url' => $base_url, 'username' => $username, 'password' => $password); } public function getSugar() { if (!$this->sugar) $this->connectSugar(); return $this->sugar; } public function connectSugar() { /* A base URL can include the path.. aka check if someone has..*/ if (!preg_match("/v10/", $this->options['base_url'])) { $this->options['base_url'] = $this->options['base_url'] . '/rest/v10/'; } $this->sugar = new \Spinegar\SugarRestClient\Rest(); $this->sugar ->setClientOption('verify', false) ->setUrl($this->options['base_url']) ->setUsername($this->options['username']) ->setPassword($this->options['password']) ; } }
<?php namespace BisonLab\SugarCrmBundle\Service; /* * Just a service object for the sugar7crm-wrapper class. */ class SugarWrapper { private $sugar; private $options; public function __construct($base_url, $username, $password) { $this->options = array('base_url' => $base_url, 'username' => $username, 'password' => $password); } public function getSugar() { if (!$this->sugar) $this->connectSugar(); return $this->sugar; } public function connectSugar() { /* A base URL can include the path.. aka check if someone has..*/ if (!preg_match("/v10/", $this->options['base_url'])) { $this->options['base_url'] = $this->options['base_url'] . '/rest/v10/'; } $this->sugar = new \Spinegar\Sugar7Wrapper\Rest("Guzzle6"); $this->sugar->setClientOption('verify', false) ->setUrl($this->options['base_url']) ->setUsername($this->options['username']) ->setPassword($this->options['password']) ->connect(); } }
Fix jogging with Y or Z axes inverted
# Copyright (c) 2020 Aldo Hoeben / fieldOfView # OctoPrintPlugin is released under the terms of the AGPLv3 or higher. from cura.PrinterOutput.GenericOutputController import GenericOutputController class OctoPrintOutputController(GenericOutputController): def __init__(self, output_device: "PrinterOutputDevice") -> None: super().__init__(output_device) def moveHead(self, printer: "PrinterOutputModel", x, y, z, speed) -> None: axis_information = self._output_device.getAxisInformation() if axis_information["x"].inverted: x = -x if axis_information["y"].inverted: y = -y if axis_information["z"].inverted: z = -z self._output_device.sendCommand("G91") self._output_device.sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed)) self._output_device.sendCommand("G90")
# Copyright (c) 2020 Aldo Hoeben / fieldOfView # OctoPrintPlugin is released under the terms of the AGPLv3 or higher. from cura.PrinterOutput.GenericOutputController import GenericOutputController class OctoPrintOutputController(GenericOutputController): def __init__(self, output_device: "PrinterOutputDevice") -> None: super().__init__(output_device) def moveHead(self, printer: "PrinterOutputModel", x, y, z, speed) -> None: axis_information = self._output_device.getAxisInformation() if axis_information["x"].inverted: x = -x if axis_information["y"].inverted: x = -y if axis_information["z"].inverted: x = -z self._output_device.sendCommand("G91") self._output_device.sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed)) self._output_device.sendCommand("G90")
Fix tests for image fallbacks
define([ 'client/preprocessors/visualisation_fallback', 'modernizr' ], function (visualisationFallback, Modernizr) { describe('Module actions', function () { var el; beforeEach(function () { el = $('<div class="visualisation-inner" data-src="spec/client/preprocessors/transparent.gif">original content</div>'); $('body').append(el); }); afterEach(function () { $('.visualisation-inner').remove(); }); it('does nothing when the browser supports SVG', function () { Modernizr.inlinesvg = true; visualisationFallback(); expect(el.html()).toEqual('original content'); }); it('replaces the fallback container content with a fallback image', function () { Modernizr.inlinesvg = false; visualisationFallback(); waitsFor(function () { return (el.html() !== 'original content'); }); runs(function () { expect(el.html()).toEqual('<img src="spec/client/preprocessors/transparent.gif">'); }); }); }); });
define([ 'client/preprocessors/visualisation_fallback' ], function (visualisationFallback) { describe('Module actions', function () { var originalModernizr = visualisationFallback.Modernizr; var el; beforeEach(function () { visualisationFallback.Modernizr = {}; el = $('<div class="visualisation-inner" data-src="spec/client/preprocessors/transparent.gif">original content</div>'); $('body').append(el); }); afterEach(function () { visualisationFallback.Modernizr = originalModernizr; $('.visualisation-inner').remove(); }); it('does nothing when the browser supports SVG', function () { visualisationFallback.Modernizr.inlinesvg = true; visualisationFallback(); expect(el.html()).toEqual('original content'); }); it('replaces the fallback container content with a fallback image', function () { visualisationFallback.Modernizr.inlinesvg = false; visualisationFallback(); waitsFor(function () { return (el.html() !== 'original content'); }); runs(function () { expect(el.html()).toEqual('<img src="spec/client/preprocessors/transparent.gif">'); }); }); }); });
Fix fatal error from Imagick when creating email picture
<?php function createEmailPic($jid, $email) { $cachefile = DOCUMENT_ROOT.'/cache/'.$jid.'_email.png'; if(file_exists(DOCUMENT_ROOT.'/cache/'.$jid.'_email.png')) unlink(DOCUMENT_ROOT.'/cache/'.$jid.'_email.png'); $draw = new ImagickDraw(); try { $draw->setFontSize(13); $draw->setGravity(Imagick::GRAVITY_CENTER); $canvas = new Imagick(); $metrics = $canvas->queryFontMetrics($draw, $email); $canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png"); $canvas->annotateImage($draw, 0, 0, 0, $email); $canvas->setImageFormat('PNG'); $canvas->writeImage($cachefile); } catch (ImagickException $e) { error_log($e->getMessage()); } }
<?php function createEmailPic($jid, $email) { $cachefile = DOCUMENT_ROOT.'/cache/'.$jid.'_email.png'; if(file_exists(DOCUMENT_ROOT.'/cache/'.$jid.'_email.png')) unlink(DOCUMENT_ROOT.'/cache/'.$jid.'_email.png'); $draw = new ImagickDraw(); $draw->setFontSize(13); $draw->setGravity(Imagick::GRAVITY_CENTER); $canvas = new Imagick(); $metrics = $canvas->queryFontMetrics($draw, $email); $canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png"); $canvas->annotateImage($draw, 0, 0, 0, $email); $canvas->setImageFormat('PNG'); $canvas->writeImage($cachefile); }
runCommand: Expand use for returning both exit code + content
# -*- coding: utf-8 -*- import sys from .processrunner import ProcessRunner from .writeout import writeOut def runCommand(command, outputPrefix="ProcessRunner> ", returnAllContent=False): """Easy invocation of a command with default IO streams returnAllContent as False (default): Args: command (list): List of strings to pass to subprocess.Popen Kwargs: outputPrefix(str): String to prepend to all output lines. Defaults to 'ProcessRunner> ' returnAllContent(bool): False (default) sends command stdout/stderr to regular interfaces, True collects and returns them Returns: int The return code from the command (returnAllContent as False (default)) tuple (return code, list of output) The return code and any output content (returnAllContent as True) """ proc = ProcessRunner(command) if returnAllContent: content = proc.collectLines() else: proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") returnCode = proc.wait().poll() proc.terminate() proc.shutdown() if returnAllContent: return (returnCode, content) else: return returnCode
# -*- coding: utf-8 -*- import sys from .processrunner import ProcessRunner from .writeout import writeOut def runCommand(command, outputPrefix="ProcessRunner> "): """Easy invocation of a command with default IO streams Args: command (list): List of strings to pass to subprocess.Popen Kwargs: outputPrefix(str): String to prepend to all output lines. Defaults to 'ProcessRunner> ' Returns: int The return code from the command """ proc = ProcessRunner(command) proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") proc.wait() returnCode = proc.poll() proc.terminate() proc.shutdown() return returnCode
Add router and start server
package main import ( "github.com/gorilla/mux" "github.com/larzconwell/moln/config" "github.com/larzconwell/moln/loggers" "log" "net/http" "os" "path/filepath" ) func main() { env := "development" if len(os.Args) > 1 { env = os.Args[1] } conf, err := config.ReadFiles("config/environment.json", "config/"+env+".json") if err != nil { log.Fatalln(err) } errorLogger, errorLogFile, err := loggers.Error(filepath.Join(conf.LogDir, "errors")) if err != nil { log.Fatalln(err) } defer errorLogFile.Close() logFile, err := loggers.Access(conf.LogDir) if err != nil { errorLogger.Fatalln(err) } defer logFile.Close() router := mux.NewRouter() server := &http.Server{ Addr: conf.ServerAddr, Handler: router, ReadTimeout: conf.MaxTimeout, WriteTimeout: conf.MaxTimeout, } if conf.TLS != nil { err = server.ListenAndServeTLS(conf.TLS.Cert, conf.TLS.Key) } else { err = server.ListenAndServe() } if err != nil { errorLogger.Fatal(err) } }
package main import ( "github.com/larzconwell/moln/config" "github.com/larzconwell/moln/loggers" "log" "os" "path/filepath" ) func main() { env := "development" if len(os.Args) > 1 { env = os.Args[1] } conf, err := config.ReadFiles("config/environment.json", "config/"+env+".json") if err != nil { log.Fatalln(err) } errorLogger, errorLogFile, err := loggers.Error(filepath.Join(conf.LogDir, "errors")) if err != nil { log.Fatalln(err) } defer errorLogFile.Close() logFile, err := loggers.Access(conf.LogDir) if err != nil { errorLogger.Fatalln(err) } defer logFile.Close() }
Refactor Armory API to use UnsignedTransaction class
import urlparse import os, sys, re, random,pybitcointools, bitcoinrpc, math from decimal import Decimal from flask import Flask, request, jsonify, abort, json, make_response from msc_apps import * tools_dir = os.environ.get('TOOLSDIR') lib_path = os.path.abspath(tools_dir) sys.path.append(lib_path) data_dir_root = os.environ.get('DATADIR') sys.path.append("/usr/lib/armory/") from armoryengine.ALL import * app = Flask(__name__) app.debug = True @app.route('/getunsigned', methods=['POST']) def generate_unsigned(): unsigned_hex = request.form['unsigned_hex'] pubkey = request.form['pubkey'] #Translate raw txn pytx = PyTx() print("Encoding raw txn: %s" % unsigned_hex) try: unsigned_tx_bin = hex_to_binary(unsigned_tx_hex) pytx = PyTx().unserialize(unsigned_tx_bin) utx = UnsignedTransaction(pytx=pytx, pubKeyMap=hex_to_binary(public_key_hex)) unsigned_tx_ascii = utx.serializeAscii() except Exception, e: abort("Error serializing transaction: %s" % e) print("\n\nOutput is:\n%s" % unsigned_tx_ascii) return jsonify({'armoryUnsigned':unsigned_tx_ascii})
import urlparse import os, sys, re, random,pybitcointools, bitcoinrpc, math from decimal import Decimal from flask import Flask, request, jsonify, abort, json, make_response from msc_apps import * tools_dir = os.environ.get('TOOLSDIR') lib_path = os.path.abspath(tools_dir) sys.path.append(lib_path) data_dir_root = os.environ.get('DATADIR') sys.path.append("/usr/lib/armory/") from armoryengine.ALL import * app = Flask(__name__) app.debug = True @app.route('/getunsigned', methods=['POST']) def generate_unsigned(): unsigned_hex = request.form['unsigned_hex'] pubkey = request.form['pubkey'] #Translate raw txn pytx = PyTx() print("Encoding raw txn: %s" % unsigned_hex) binTxn = hex_to_binary(unsigned_hex) pytx.unserialize(binTxn) tx = PyTxDistProposal(pytx) print("\n\nOutput is:\n%s" % tx.serializeAscii()) return jsonify({'armoryUnsigned':tx.serializeAscii()})
Fix not on FX thread exception
package org.jabref; import org.jabref.gui.util.DefaultTaskExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Catch and log any unhandled exceptions. */ public class FallbackExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(FallbackExceptionHandler.class); public static void installExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new FallbackExceptionHandler()); } @Override public void uncaughtException(Thread thread, Throwable exception) { LOGGER.error("Uncaught exception occurred in " + thread, exception); DefaultTaskExecutor.runInJavaFXThread(() -> JabRefGUI.getMainFrame() .getDialogService() .showErrorDialogAndWait("Uncaught exception occurred in " + thread, exception) ); } }
package org.jabref; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Catch and log any unhandled exceptions. */ public class FallbackExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(FallbackExceptionHandler.class); public static void installExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new FallbackExceptionHandler()); } @Override public void uncaughtException(Thread thread, Throwable exception) { LOGGER.error("Uncaught exception occurred in " + thread, exception); JabRefGUI.getMainFrame() .getDialogService() .showErrorDialogAndWait( exception.getLocalizedMessage(), exception); } }
Create all the subroutes and pass logOut to the DashNav
import React from 'react'; import { connect } from 'react-redux'; // actions import { logOut } from '../actions/login'; // Components import { Route, Redirect, Switch } from 'react-router'; import DashNav from '../components/dashboard/DashNav'; // Styles import '../styles/dashboard/index.css'; // SubContainers import TrucksContainer from './TrucksContainer'; const TmpComponent = () => <h1>Coming Soon</h1> const DashboardContainer = ({logged_in, match}) => { if(logged_in){ return ( <div className="page-dashboard"> <DashNav logOut={logOut}/> <div className="dashboard container"> <Switch> <Route path={match.url + "/trucks"} component={TrucksContainer}/> <Route path={match.url + "/routes"} component={TmpComponent}/> <Route path={match.url + "/drivers"} component={TmpComponent}/> </Switch> </div> </div> ) } else { return <Redirect to="/login"/> } } function mapStateToProps(state, ownProps) { return { logged_in: state.login.logged_in, } } export default connect(mapStateToProps, { logOut })(DashboardContainer)
import React from 'react'; import { connect } from 'react-redux'; // Components import { Route, Redirect } from 'react-router'; import DashNav from '../components/dashboard/DashNav'; // Styles import '../styles/dashboard/index.css'; const DashboardContainer = (props) => { if(props.loggedIn){ return ( <div className="page-dashboard"> <DashNav /> <div className="dashboard"> </div> </div> ) } else { return <Redirect to="/login"/> } } function mapStateToProps(state, ownProps) { return { loggedIn: state.login.logged_in, } } export default connect(mapStateToProps)(DashboardContainer)
Add new field for about link
import DS from 'ember-data'; import OsfModel from 'ember-osf/models/osf-model'; export default OsfModel.extend({ name: DS.attr('fixstring'), logoPath: DS.attr('string'), bannerPath: DS.attr('string'), description: DS.attr('fixstring'), example: DS.attr('fixstring'), advisoryBoard: DS.attr('string'), emailContact: DS.attr('fixstring'), emailSupport: DS.attr('fixstring'), socialTwitter: DS.attr('fixstring'), socialFacebook: DS.attr('fixstring'), socialInstagram: DS.attr('fixstring'), aboutLink: DS.attr('fixstring'), headerText: DS.attr('fixstring'), subjectsAcceptable: DS.attr(), // Relationships taxonomies: DS.hasMany('taxonomy'), preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }), licensesAcceptable: DS.hasMany('license', { inverse: null }), });
import DS from 'ember-data'; import OsfModel from 'ember-osf/models/osf-model'; export default OsfModel.extend({ name: DS.attr('fixstring'), logoPath: DS.attr('string'), bannerPath: DS.attr('string'), description: DS.attr('fixstring'), example: DS.attr('fixstring'), advisoryBoard: DS.attr('string'), emailContact: DS.attr('fixstring'), emailSupport: DS.attr('fixstring'), socialTwitter: DS.attr('fixstring'), socialFacebook: DS.attr('fixstring'), socialInstagram: DS.attr('fixstring'), headerText: DS.attr('fixstring'), subjectsAcceptable: DS.attr(), // Relationships taxonomies: DS.hasMany('taxonomy'), preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }), licensesAcceptable: DS.hasMany('license', { inverse: null }), });
consentSimpleAdmin: Use new selftest-function on database backend.
<?php /** * * @param array &$hookinfo hookinfo */ function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) { assert('is_array($hookinfo)'); assert('array_key_exists("errors", $hookinfo)'); assert('array_key_exists("info", $hookinfo)'); try { $consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php'); // Parse consent config $consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store')); if (!is_callable(array($consent_storage, 'selftest'))) { /* Doesn't support a selftest. */ return; } $testres = $consent_storage->selftest(); if ($testres) { $hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage selftest OK.'; } else { $hookinfo['errors'][] = '[consentSimpleAdmin] Consent Storage selftest failed.'; } } catch (Exception $e) { $hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage(); } } ?>
<?php /** * * @param array &$hookinfo hookinfo */ function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) { assert('is_array($hookinfo)'); assert('array_key_exists("errors", $hookinfo)'); assert('array_key_exists("info", $hookinfo)'); try { $consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php'); // Parse consent config $consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store')); // Get all consents for user $stats = $consent_storage->getStatistics(); $hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.'; } catch (Exception $e) { $hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage(); } } ?>
Update case of autoload class
<?php namespace Joindin; require_once '../src/Joindin/Service/Autoload.php'; spl_autoload_register('Joindin\Service\Autoload::autoload'); session_cache_limiter(false); session_start(); ini_set('display_errors', 'on'); // include dependencies require '../vendor/Slim/Slim.php'; require '../vendor/TwigView.php'; // include view controller require '../src/Joindin/View/Filters.php'; $config = array(); $configFile = realpath(__DIR__ . '/../config/config.php'); if (is_readable($configFile)) { include $configFile; } // initialize Slim $app = new \Slim( array( 'mode' => 'development', 'view' => new \TwigView(), 'custom' => $config, ) ); // set Twig base folder, view folder and initialize Joindin filters \TwigView::$twigDirectory = realpath(__DIR__ . '/../vendor/Twig/lib/Twig'); $app->view()->setTemplatesDirectory('../views'); \Joindin\View\Filter\initialize($app->view()->getEnvironment()); // register routes new Controller\Application($app); new Controller\Event($app); // execute application $app->run();
<?php namespace Joindin; require_once '../src/Joindin/Service/Autoload.php'; spl_autoload_register('Joindin\Service\autoload::autoload'); session_cache_limiter(false); session_start(); ini_set('display_errors', 'on'); // include dependencies require '../vendor/Slim/Slim.php'; require '../vendor/TwigView.php'; // include view controller require '../src/Joindin/View/Filters.php'; $config = array(); $configFile = realpath(__DIR__ . '/../config/config.php'); if (is_readable($configFile)) { include $configFile; } // initialize Slim $app = new \Slim( array( 'mode' => 'development', 'view' => new \TwigView(), 'custom' => $config, ) ); // set Twig base folder, view folder and initialize Joindin filters \TwigView::$twigDirectory = realpath(__DIR__ . '/../vendor/Twig/lib/Twig'); $app->view()->setTemplatesDirectory('../views'); \Joindin\View\Filter\initialize($app->view()->getEnvironment()); // register routes new Controller\Application($app); new Controller\Event($app); // execute application $app->run();
Update range comments inches and centimeters
package org.firebears.sensors; // made by Jacob Wiggins import edu.wpi.first.wpilibj.AnalogInput; /* * Range Sensor */ public class sharpIRRange extends AnalogInput { public sharpIRRange(int channel) { super(channel); } //distance will be close to the distance that the robot is //assuming that it is between 10cm and 80cm. //volt represents the voltage that the sensor outputs //when taking the range between the robot and something //we got the constants by plotting points, making a function that fits the data //and using trial and error to make it more accurate //return value in inches 8" approx 20 cm. public double getRangefinderDistance() { double volt = this.getAverageVoltage(); // value from sensor * (5/1024) //System.out.println(volt); double distance = (26.86 * Math.pow(volt, -1.15))/2.54; return distance; } // @Override // public void updateTable() { // ITable m_table = super.getTable(); // if (m_table != null) { // m_table.putNumber("Distance", getRangefinderDistance()); // } // } }
package org.firebears.sensors; // made by Jacob Wiggins import edu.wpi.first.wpilibj.AnalogInput; /* * Range Sensor */ public class sharpIRRange extends AnalogInput { public sharpIRRange(int channel) { super(channel); } //distance will be close to the distance that the robot is //assuming that it is between 10cm and 80cm. //volt represents the voltage that the sensor outputs //when taking the range between the robot and something //we got the constants by plotting points, making a function that fits the data //and using trial and error to make it more accurate //return value in inches public double getRangefinderDistance() { double volt = this.getAverageVoltage(); // value from sensor * (5/1024) //System.out.println(volt); double distance = (26.86 * Math.pow(volt, -1.15))/2.54; return distance; } // @Override // public void updateTable() { // ITable m_table = super.getTable(); // if (m_table != null) { // m_table.putNumber("Distance", getRangefinderDistance()); // } // } }
Read README as UTF-8, always
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme: README = readme.read() setup( name='django-postgres-extra', version='1.20', packages=find_packages(), include_package_data=True, license='MIT License', description='Bringing all of PostgreSQL\'s awesomeness to Django.', long_description=README, url='https://github.com/SectorLabs/django-postgres-extra', author='Sector Labs', author_email='open-source@sectorlabs.ro', keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ] )
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() setup( name='django-postgres-extra', version='1.19', packages=find_packages(), include_package_data=True, license='MIT License', description='Bringing all of PostgreSQL\'s awesomeness to Django.', long_description=README, url='https://github.com/SectorLabs/django-postgres-extra', author='Sector Labs', author_email='open-source@sectorlabs.ro', keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ] )
Set up better merge method with default values
<?php namespace ThemeKeeper\DI; use Nette\DI\CompilerExtension; use ThemeKeeper\Theme\Theme; use UrlMatcher\Utils\Arrays; /** * Class ThemeKeeperExtension * * @author Lukáš Drahník (http://drahnik-lukas.com/) * @package ldrahnik\ThemeKeeper\DI */ class ThemeKeeperExtension extends CompilerExtension { private $defaults = [ 'themeDir' => null, 'assetsDir' => null, 'views' => [] ]; public function loadConfiguration() { $builder = $this->getContainerBuilder(); $config = $this->getConfig(); foreach ($config as $name => $configuration) { $config[$name] = new Theme($name, Arrays::merge_only_exist_keys($configuration, $this->defaults)); } $builder->addDefinition($this->prefix('ThemeKeeper')) ->setClass('ThemeKeeper\ThemeKeeper', array($config) ); } }
<?php namespace ThemeKeeper\DI; use Nette\DI\CompilerExtension; use ThemeKeeper\Theme\Theme; use UrlMatcher\Utils\Arrays; /** * Class ThemeKeeperExtension * * @author Lukáš Drahník (http://drahnik-lukas.com/) * @package ldrahnik\ThemeKeeper\DI */ class ThemeKeeperExtension extends CompilerExtension { private $defaults = [ 'themeDir' => null, 'assetsDir' => null, 'views' => [] ]; public function loadConfiguration() { $builder = $this->getContainerBuilder(); $config = $this->getConfig(); foreach ($config as $name => $configuration) { $config[$name] = new Theme($name, Arrays::merge($configuration, $this->defaults)); } $builder->addDefinition($this->prefix('ThemeKeeper')) ->setClass('ThemeKeeper\ThemeKeeper', array($config) ); } }
Handle Android RN 0.47 breaking change
package com.BV.LinearGradient; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; public class LinearGradientPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } // Deprecated RN 0.47 public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList( new LinearGradientManager()); } }
package com.BV.LinearGradient; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; public class LinearGradientPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Arrays.<ViewManager>asList( new LinearGradientManager()); } }
chore(example): Move the location of the enhancer
import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import { reducer as repoReducer } from './RepoRedux' import { reducer as logoReducer } from './LogoRedux' import { reducer as errorReducer } from './ErrorRedux' import { not, contains } from 'ramda' import { createLogger } from 'redux-logger' import createSagaMiddleware from 'redux-saga' import rootSaga from '../Sagas' // Reactotron Stuff import Reactotron from 'reactotron-react-native' // make our root reducer const rootReducer = combineReducers({ repo: repoReducer, logo: logoReducer, error: errorReducer }) // the logger master switch const USE_LOGGING = false // silence these saga-based messages const SAGA_LOGGING_BLACKLIST = ['EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED'] // create the logger const logger = createLogger({ predicate: (getState, { type }) => USE_LOGGING && not(contains(type, SAGA_LOGGING_BLACKLIST)) }) // a function which can create our store and auto-persist the data export default () => { const sagaMiddleware = createSagaMiddleware({ sagaMonitor: Reactotron.createSagaMonitor() }) const middleware = applyMiddleware(logger, sagaMiddleware) const store = createStore(rootReducer, compose(middleware, Reactotron.createEnhancer())) sagaMiddleware.run(rootSaga) return store }
import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import { reducer as repoReducer } from './RepoRedux' import { reducer as logoReducer } from './LogoRedux' import { reducer as errorReducer } from './ErrorRedux' import { not, contains } from 'ramda' import { createLogger } from 'redux-logger' import createSagaMiddleware from 'redux-saga' import rootSaga from '../Sagas' // Reactotron Stuff import Reactotron from 'reactotron-react-native' // make our root reducer const rootReducer = combineReducers({ repo: repoReducer, logo: logoReducer, error: errorReducer }) // the logger master switch const USE_LOGGING = false // silence these saga-based messages const SAGA_LOGGING_BLACKLIST = ['EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED'] // create the logger const logger = createLogger({ predicate: (getState, { type }) => USE_LOGGING && not(contains(type, SAGA_LOGGING_BLACKLIST)) }) // a function which can create our store and auto-persist the data export default () => { const sagaMiddleware = createSagaMiddleware({ sagaMonitor: Reactotron.createSagaMonitor() }) const middleware = applyMiddleware(logger, sagaMiddleware) const store = createStore(rootReducer, compose(Reactotron.createEnhancer(), middleware)) sagaMiddleware.run(rootSaga) return store }
Remove the prepended 0x returned from RPC.
var web3 = require('web3') var rm = require('web3/lib/web3/requestmanager') var web3api = function(provider) { this.requestmanager = rm.getInstance(); try { web3.setProvider(new web3.providers.HttpProvider(provider)); } catch(e) { console.error("Could not connect: %s", e); } } web3api.prototype.getBalance = function(address) { var bignum = web3.eth.getBalance('0x' + address); return bignum.toNumber(); } web3api.prototype.injectTransaction = function(signedTx) { // this function will only work if you run the go client return this.requestmanager.send({ method: 'eth_sendRawTransaction', params: ['0x' + signedTx] }).slice(2); } web3api.prototype.getNonce = function(address) { return web3.eth.getTransactionCount('0x' + address); } web3api.prototype.estimateGas = function(txObject) { return web3.eth.estimateGas(txObject); } web3api.prototype.getWeb3 = function() { return web3; } module.exports = web3api;
var web3 = require('web3') var rm = require('web3/lib/web3/requestmanager') var web3api = function(provider) { this.requestmanager = rm.getInstance(); try { web3.setProvider(new web3.providers.HttpProvider(provider)); } catch(e) { console.error("Could not connect: %s", e); } } web3api.prototype.getBalance = function(address) { var bignum = web3.eth.getBalance('0x' + address); return bignum.toNumber(); } web3api.prototype.injectTransaction = function(signedTx) { // this function will only work if you run the go client return this.requestmanager.send({ method: 'eth_sendRawTransaction', params: ['0x' + signedTx] }); } web3api.prototype.getNonce = function(address) { return web3.eth.getTransactionCount('0x' + address); } web3api.prototype.estimateGas = function(txObject) { return web3.eth.estimateGas(txObject); } web3api.prototype.getWeb3 = function() { return web3; } module.exports = web3api;
Make jacobian use more explicit.
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 15:23:58 2015 @author: jensv """ import skin_core_scanner_simple as scss reload(scss) import equil_solver as es reload(es) import newcomb_simple as new reload(new) (lambda_a_mesh, k_a_mesh, stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25], epsilon=0.11, core_radius_norm=0.9, transition_width_norm=0.033, skin_width_norm=0.034, method='lsoda', max_step=1E-2, nsteps=1000, use_jac=True)
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 15:23:58 2015 @author: jensv """ import skin_core_scanner_simple as scss reload(scss) import equil_solver as es reload(es) import newcomb_simple as new reload(new) (lambda_a_mesh, k_a_mesh, stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25], epsilon=0.11, core_radius_norm=0.9, transition_width_norm=0.033, skin_width_norm=0.034, method='lsoda', max_step=1E-2, nsteps=1000)
Fix build failure with pip
#!/usr/bin/env python3 """ Dispatch your torrents into multiple watchdirs See: https://github.com/Anthony25/torrents_dispatcher """ from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) setup( name="torrents_dispatcher", version="0.0.1", description="Dispatch your torrents between multiple torrents clients", url="https://github.com/Anthony25/torrents_dispatcher", author="Anthony25 <Anthony Ruhier>", author_email="anthony.ruhier@gmail.com", license="Simplified BSD", classifiers=[ "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "License :: OSI Approved :: BSD License", ], keywords="torrent", packages=["torrents_dispatcher", ], install_requires=["appdirs", "argparse", "bencodepy"], entry_points={ 'console_scripts': [ 'torrdispatcher = torrents_dispatcher.__main__:parse_args', ], } )
#!/usr/bin/env python3 """ Dispatch your torrents into multiple watchdirs See: https://github.com/Anthony25/torrents_dispatcher """ from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, "README.mkd"), encoding="utf-8") as f: long_description = f.read() setup( name="torrents_dispatcher", version="0.0.1", description="Dispatch your torrents between multiple torrents clients", long_description=long_description, url="https://github.com/Anthony25/torrents_dispatcher", author="Anthony25 <Anthony Ruhier>", author_email="anthony.ruhier@gmail.com", license="Simplified BSD", classifiers=[ "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "License :: OSI Approved :: BSD License", ], keywords="torrent", packages=["torrents_dispatcher", ], install_requires=["appdirs", "argparse", "bencodepy"], entry_points={ 'console_scripts': [ 'torrdispatcher = torrents_dispatcher.__main__:parse_args', ], } )
Update to use Buffer.alloc in place of deprecated new Buffer()
function isBrowser() { return typeof window !== 'undefined'; } function isNode() { return typeof window === 'undefined'; } function nodeBufferToArrayBuffer(buffer) { const ab = new ArrayBuffer(buffer.length); const view = new Uint8Array(ab); for (let i = 0; i < buffer.length; ++i) { view[i] = buffer[i]; } return ab; } function arrayBufferToNodeBuffer(ab) { const buffer = Buffer.alloc(ab.byteLength); const view = new Uint8Array(ab); for (let i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; } function checkArgument(expression, message) { if (!expression) { throw message; } } export { isBrowser, isNode, nodeBufferToArrayBuffer, arrayBufferToNodeBuffer, checkArgument };
function isBrowser() { return typeof window !== 'undefined'; } function isNode() { return typeof window === 'undefined'; } function nodeBufferToArrayBuffer(buffer) { const ab = new ArrayBuffer(buffer.length); const view = new Uint8Array(ab); for (let i = 0; i < buffer.length; ++i) { view[i] = buffer[i]; } return ab; } function arrayBufferToNodeBuffer(ab) { const buffer = new Buffer(ab.byteLength); const view = new Uint8Array(ab); for (let i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; } function checkArgument(expression, message) { if (!expression) { throw message; } } export { isBrowser, isNode, nodeBufferToArrayBuffer, arrayBufferToNodeBuffer, checkArgument };
Comment mxtoolbox because of limited requests
from functools import reduce import pprint import time import shodan import requests import api_key from google_api import query_google_api from shodan_api import query_shodan_api from mxtoolbox_api import query_mxtoolbox_api from utils import assoc_default_score, combine_scores pp = pprint.PrettyPrinter(indent=2) def main(): start_time = time.time() # No more than 10 requests ips = ['103.245.153.70'] scored_ips = assoc_default_score(ips) shodan_scores = query_shodan_api(ips) google_scores = query_google_api(ips) # Limited number of requests... Be careful # mx_toolbox_scores = query_mxtoolbox_api(ips) results = reduce(combine_scores, [scored_ips, shodan_scores, google_scores]) pp.pprint(results) print("--------- %s seconds -------" % (time.time() - start_time)) return results def get_some_ips(): req = requests.get("https://zeustracker.abuse.ch/blocklist.php?download=badips") return [line for line in req.text.split('\n') if line and line[0].isdigit()] def get_bad_ips(): with open("bad_ips.txt", "r") as file: ips = list(filter(lambda line: line != '', file.read().split("\n"))) return ips if __name__ == "__main__": main()
from functools import reduce import pprint import time import shodan import requests import api_key from google_api import query_google_api from shodan_api import query_shodan_api from mxtoolbox_api import query_mxtoolbox_api from utils import assoc_default_score, combine_scores pp = pprint.PrettyPrinter(indent=2) def main(): start_time = time.time() # No more than 10 requests ips = ['103.245.153.70'] scored_ips = assoc_default_score(ips) shodan_scores = query_shodan_api(ips) google_scores = query_google_api(ips) # Limited number of requests... Be careful mx_toolbox_scores = query_mxtoolbox_api(ips) results = reduce(combine_scores, [scored_ips, shodan_scores, google_scores, mx_toolbox_scores]) pp.pprint(results) print("--------- %s seconds -------" % (time.time() - start_time)) return results def get_some_ips(): req = requests.get("https://zeustracker.abuse.ch/blocklist.php?download=badips") return [line for line in req.text.split('\n') if line and line[0].isdigit()] def get_bad_ips(): with open("bad_ips.txt", "r") as file: ips = list(filter(lambda line: line != '', file.read().split("\n"))) return ips if __name__ == "__main__": main()
Add helper to check instance and subclass
""" Helpers ======= """ import inspect from collections import Mapping, Iterable def is_generator(obj): """Return True if ``obj`` is a generator """ return inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) def is_iterable_but_not_string(obj): """Return True if ``obj`` is an iterable object that isn't a string.""" return ( (isinstance(obj, Iterable) and not hasattr(obj, "strip")) or is_generator(obj) ) def is_indexable_but_not_string(obj): """Return True if ``obj`` is indexable but isn't a string.""" return not hasattr(obj, "strip") and hasattr(obj, "__getitem__") def is_collection(obj): """ Return True if ``obj`` is a collection type, e.g list, tuple, queryset. """ return is_iterable_but_not_string(obj) and not isinstance(obj, Mapping) def is_instance_or_subclass(val, class_): """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
""" Helpers ======= """ import inspect from collections import Mapping, Iterable def is_generator(obj): """Return True if ``obj`` is a generator """ return inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) def is_iterable_but_not_string(obj): """Return True if ``obj`` is an iterable object that isn't a string.""" return ( (isinstance(obj, Iterable) and not hasattr(obj, "strip")) or is_generator(obj) ) def is_indexable_but_not_string(obj): """Return True if ``obj`` is indexable but isn't a string.""" return not hasattr(obj, "strip") and hasattr(obj, "__getitem__") def is_collection(obj): """ Return True if ``obj`` is a collection type, e.g list, tuple, queryset. """ return is_iterable_but_not_string(obj) and not isinstance(obj, Mapping)
Add seperate key log handler
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # Print, log, and return. print(request.url) with open("cap.log", "a") as f: f.write(replace_entities(str(request.url)) + "\n") with open("key.log", "a") as f: if "c" in request.get: keys = replace_entities(request.get['c']) f.write(keys + '\n') return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages." # @app.route('/<path:path>') # def staticserve(path): # """Serve a file from your static directory.""" # return app.send_static_file(path) if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # Print, log, and return. print(request.url) with open("cap.log", "a") as f: f.write(replace_entities(str(request.url)) + "\n") return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages." # @app.route('/<path:path>') # def staticserve(path): # """Serve a file from your static directory.""" # return app.send_static_file(path) if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
Add more documentation. Fix the expand_directory function
import os def expand_directory(directory_path): """Recursively create a list of all the files in a directory and its subdirectories """ ret = [] for file_path in os.listdir(directory_path): if os.path.isfile(os.path.join(directory_path, file_path)): # Append instead of extend or += because those separate the string into its individual characters # This has to do with the way strings act like lists in python ret.append(os.path.join(directory_path, file_path)) else: ret.extend(expand_directory(os.path.join(directory_path, file_path))) return ret def find_file_id_in_commit(file_name, revision_number): """Find the file id of a specified file in the change map of a specified commit """ with open(".pvcs/revisions/" + str(revision_number) + "/change_map") as change_map: # Loop through every line, find the one containing the file, return the id for line in change_map.readlines(): if line.find(file_name) != -1: return int(line.split(",")[0])
import os def expand_directory(directory_path): ret = [] for file_path in os.listdir(directory_path): if os.path.isfile(os.path.join(directory_path, file_path)): # Append instead of extend or += because those separate the string into its individual characters # This has to do with the way strings act like lists in python ret.append(os.path.join(directory_path, file_path)) return ret def find_file_id_in_commit(file_name, revision_number): with open(".pvcs/revisions/" + str(revision_number) + "/change_map") as change_map: for line in change_map.readlines(): if line.find(file_name) != -1: return int(line.split(",")[0])
Set default value of order in Quotation
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateQuotationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('quotations', function (Blueprint $table) { $table->increments('id'); $table->string('context'); $table->integer('order')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('quotations'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateQuotationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('quotations', function (Blueprint $table) { $table->increments('id'); $table->string('context'); $table->integer('order'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('quotations'); } }
Clean string returned by website => remove newline-characters and strip
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text def clean(s): return s.replace('\n', '').strip() return clean(search(r'Client\ 64\-bit')), \ clean(search(r'Server\ 64\-bit'))
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
Move Settings to addCheck config syntax
<?hh class SettingsController extends BaseController { public static function getPath(): string { return '/settings'; } public static function getConfig(): ControllerConfig { return (new ControllerConfig())->addCheck( Auth::requireRoles(Vector {UserRole::Superuser}), ); } public static function get(): :xhp { $settings = Map { 'applications_open' => Settings::get('applications_open'), }; return <x:js-scope> <nucleus:settings settings={$settings} /> </x:js-scope>; } public static function post(): void { if (isset($_POST['applications_disabled'])) { Settings::set('applications_open', false); } else { Settings::set('applications_open', true); } Route::redirect(self::getPath()); } }
<?hh class SettingsController extends BaseController { public static function getPath(): string { return '/settings'; } public static function getConfig(): ControllerConfig { return (new ControllerConfig())->setUserRoles(Vector {UserRole::Superuser}); } public static function get(): :xhp { $settings = Map { 'applications_open' => Settings::get('applications_open'), }; return <x:js-scope> <nucleus:settings settings={$settings} /> </x:js-scope>; } public static function post(): void { if (isset($_POST['applications_disabled'])) { Settings::set('applications_open', false); } else { Settings::set('applications_open', true); } Route::redirect('/settings'); } }
Fix FoUC visibility style order - Body visibility visible order is not correct in react & vue, it is now fixed by appending visibility hidden to the top of the nodes.
import { applyPolyfills, defineCustomElements as dce } from '../loader'; export { defineCustomElements, addTheme }; function defineCustomElements() { fixFouc(); return applyPolyfills().then(() => dce(window)); } function addTheme(_theme) { const { store, actions, storeReady } = window.CorporateUi || {}; if (storeReady) { return init(_theme, { detail: { store, actions } }); } // TODO: Maybe this event listener should be accesable from the theme itself? document.addEventListener('storeReady', event => init(_theme, event)); function init(theme, event) { const name = Object.keys(theme)[0]; theme[name].components = document.head.attachShadow ? theme[name].components.default : theme[name].components.ie; [ { type: 'ADD_THEME', theme }, ].map(item => { item.type = event.detail.actions[item.type]; event.detail.store.dispatch(item); }); } } function fixFouc() { const elm = document.createElement('style'); const style = document.createTextNode('body { visibility: hidden; }'); document.head.insertBefore(elm, document.head.firstChild); elm.appendChild(style); document.addEventListener('DOMContentLoaded', () => { // This timeout is to make sure that IE has time to load setTimeout(() => { if(document.querySelector('c-theme')) return; // Used in case a theme element is not rendered style.nodeValue = 'body { visibility: visible; }'; }); }) }
import { applyPolyfills, defineCustomElements as dce } from '../loader'; export { defineCustomElements, addTheme }; function defineCustomElements() { fixFouc(); return applyPolyfills().then(() => dce(window)); } function addTheme(_theme) { const { store, actions, storeReady } = window.CorporateUi || {}; if (storeReady) { return init(_theme, { detail: { store, actions } }); } // TODO: Maybe this event listener should be accesable from the theme itself? document.addEventListener('storeReady', event => init(_theme, event)); function init(theme, event) { const name = Object.keys(theme)[0]; theme[name].components = document.head.attachShadow ? theme[name].components.default : theme[name].components.ie; [ { type: 'ADD_THEME', theme }, ].map(item => { item.type = event.detail.actions[item.type]; event.detail.store.dispatch(item); }); } } function fixFouc() { const elm = document.createElement('style'); const style = document.createTextNode('body { visibility: hidden; }'); document.head.appendChild(elm); elm.appendChild(style); document.addEventListener('DOMContentLoaded', () => { // This timeout is to make sure that IE has time to load setTimeout(() => { if(document.querySelector('c-theme')) return; // Used in case a theme element is not rendered style.nodeValue = 'body { visibility: visible; }'; }); }) }
Order taxons with hierarchy in mind.
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\TaxonomiesBundle\Doctrine\ORM; use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository; use Sylius\Bundle\TaxonomiesBundle\Model\TaxonomyInterface; use Sylius\Bundle\TaxonomiesBundle\Repository\TaxonRepositoryInterface; /** * Base taxon repository. * * @author Saša Stamenković <umpirsky@gmail.com> */ class TaxonRepository extends EntityRepository implements TaxonRepositoryInterface { public function getTaxonsAsList(TaxonomyInterface $taxonomy) { return $this->getQueryBuilder() ->where('o.taxonomy = :taxonomy') ->andWhere('o.parent IS NOT NULL') ->setParameter('taxonomy', $taxonomy) ->orderBy('o.left') ->getQuery() ->getResult() ; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\TaxonomiesBundle\Doctrine\ORM; use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository; use Sylius\Bundle\TaxonomiesBundle\Model\TaxonomyInterface; use Sylius\Bundle\TaxonomiesBundle\Repository\TaxonRepositoryInterface; /** * Base taxon repository. * * @author Saša Stamenković <umpirsky@gmail.com> */ class TaxonRepository extends EntityRepository implements TaxonRepositoryInterface { public function getTaxonsAsList(TaxonomyInterface $taxonomy) { return $this->getQueryBuilder() ->where('o.taxonomy = :taxonomy') ->andWhere('o.parent IS NOT NULL') ->setParameter('taxonomy', $taxonomy) ->getQuery() ->getResult() ; } }
Use the custom.js as served from the CDN for try
#!/usr/bin/env python # -*- coding: utf-8 -*- # Configuration file for ipython-notebook. c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 # Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded- # For headerssent by the upstream reverse proxy. Necessary if the proxy handles # SSL c.NotebookApp.trust_xheaders = True # Include our extra templates c.NotebookApp.extra_template_paths = ['/srv/templates/'] # Supply overrides for the tornado.web.Application that the IPython notebook # uses. c.NotebookApp.tornado_settings = { 'headers': { 'Content-Security-Policy': "frame-ancestors 'self' https://*.jupyter.org https://jupyter.github.io https://*.tmpnb.org" }, 'static_url_prefix': 'https://cdn.jupyter.org/notebook/try/' }
#!/usr/bin/env python # -*- coding: utf-8 -*- # Configuration file for ipython-notebook. c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 # Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded- # For headerssent by the upstream reverse proxy. Necessary if the proxy handles # SSL c.NotebookApp.trust_xheaders = True # Include our extra templates c.NotebookApp.extra_template_paths = ['/srv/templates/'] # Supply overrides for the tornado.web.Application that the IPython notebook # uses. c.NotebookApp.tornado_settings = { 'headers': { 'Content-Security-Policy': "frame-ancestors 'self' https://*.jupyter.org https://jupyter.github.io https://*.tmpnb.org" }, 'static_url_prefix': 'https://cdn.jupyter.org/notebook/3.1.0/' }
Fix safe handling of old buttons
'use strict' var botQueryHandler = require('./storage/replyQuery'); var tg = require('./telegram/telegramAPI'); var replyQuery = require('./storage/replyQuery'); var lfm = require('./lfmController') botQueryHandler.answer = function (query, queryData) { botQueryHandler[queryData.method](query, queryData); }; botQueryHandler.youtube = function (query, queryData) { var replyData = replyQuery.get(queryData.artist, queryData.object, 'tracks'); if (!replyData) { tg.answerCallbackQuery(query.id); return tg.sendTextMessage('Sorry, this button is outdated', query.message.chat.id); }; lfm.getYouTubeLink(replyData.artist, replyData.object, function (response) { tg.sendTextMessage(response, query.message.chat.id); tg.answerCallbackQuery(query.id); }); }; module.exports = botQueryHandler;
'use strict' var botQueryHandler = require('./storage/replyQuery'); var tg = require('./telegram/telegramAPI'); var replyQuery = require('./storage/replyQuery'); var lfm = require('./lfmController') botQueryHandler.answer = function (query, queryData) { botQueryHandler[queryData.method](query, queryData); }; botQueryHandler.youtube = function (query, queryData) { var replyData = replyQuery.get(queryData.artist, queryData.object, 'tracks'); lfm.getYouTubeLink(replyData.artist, replyData.object, function (response) { if (!response) { response = 'Sorry, this button is outdated'; }; tg.sendTextMessage(response, query.message.chat.id); tg.answerCallbackQuery(query.id); }); }; module.exports = botQueryHandler;
Remove creating variables and just show function call results.
package mccli import ( "fmt" "github.com/codegangsta/cli" "github.com/materials-commons/config" "github.com/materials-commons/mcstore/server/mcstore" ) var ShowCommand = cli.Command{ Name: "show", Aliases: []string{"sh"}, Usage: "Show commands", Subcommands: []cli.Command{ showConfigCommand, }, } var showConfigCommand = cli.Command{ Name: "config", Aliases: []string{"conf", "c"}, Usage: "Show configuration", Action: showConfigCLI, } func showConfigCLI(c *cli.Context) { fmt.Println("apikey:", config.GetString("apikey")) fmt.Println("mcurl:", mcstore.MCUrl()) fmt.Println("mclogging:", config.GetString("mclogging")) }
package mccli import ( "fmt" "github.com/codegangsta/cli" "github.com/materials-commons/config" "github.com/materials-commons/mcstore/server/mcstore" ) var ShowCommand = cli.Command{ Name: "show", Aliases: []string{"sh"}, Usage: "Show commands", Subcommands: []cli.Command{ showConfigCommand, }, } var showConfigCommand = cli.Command{ Name: "config", Aliases: []string{"conf", "c"}, Usage: "Show configuration", Action: showConfigCLI, } func showConfigCLI(c *cli.Context) { apikey := config.GetString("apikey") mcurl := mcstore.MCUrl() mclogging := config.GetString("mclogging") fmt.Println("apikey:", apikey) fmt.Println("mcurl:", mcurl) fmt.Println("mclogging:", mclogging) }
Print error message before exiting in main() Amends 42af9a9985ec5409f7773d9daf9f8a68df291228
import sys from .config import RawConfig from .exc import RunCommandsError from .run import run, partition_argv, read_run_args_from_file from .util import printer def main(argv=None): try: all_argv, run_argv, command_argv = partition_argv(argv) cli_args = run.parse_args(RawConfig(debug=False), run_argv) run_args = read_run_args_from_file(run) run_args.update(cli_args) run.implementation( None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv, cli_args=cli_args, **run_args) except RunCommandsError as exc: printer.error(exc, file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())
import sys from .config import RawConfig from .exc import RunCommandsError from .run import run, partition_argv, read_run_args_from_file def main(argv=None): try: all_argv, run_argv, command_argv = partition_argv(argv) cli_args = run.parse_args(RawConfig(debug=False), run_argv) run_args = read_run_args_from_file(run) run_args.update(cli_args) run.implementation( None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv, cli_args=cli_args, **run_args) except RunCommandsError: return 1 return 0 if __name__ == '__main__': sys.exit(main())
Use io.open for Python 2 compatibility.
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='portend', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="TCP port monitoring utilities", long_description=long_description, url="https://bitbucket.org/jaraco/portend", packages=setuptools.find_packages(), py_modules=['portend'], install_requires=[ 'jaraco.timing', ], setup_requires=[ 'hgtools', 'pytest-runner', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import setuptools with open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='portend', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="TCP port monitoring utilities", long_description=long_description, url="https://bitbucket.org/jaraco/portend", packages=setuptools.find_packages(), py_modules=['portend'], install_requires=[ 'jaraco.timing', ], setup_requires=[ 'hgtools', 'pytest-runner', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
Remove deprecated Logger usage in Analytics Change-Id: I66165a76f3a8a47af8473555c6280450835a75c2
/* * Copyright 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. */ package com.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
/* * Copyright 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. */ package com.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
Add missing libapol rolequery import.
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any later version. # # SETools 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with SETools. If not, see # <http://www.gnu.org/licenses/>. # __version__ = "4.0.0-alpha" # Python classes for policy representation import policyrep from policyrep import SELinuxPolicy # Component Queries import typequery import rolequery import userquery import boolquery import polcapquery # Rule Queries import terulequery import rbacrulequery import mlsrulequery # Information Flow Analysis import infoflow import permmap # Domain Transition Analysis import dta
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any later version. # # SETools 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with SETools. If not, see # <http://www.gnu.org/licenses/>. # __version__ = "4.0.0-alpha" # Python classes for policy representation import policyrep from policyrep import SELinuxPolicy # Component Queries import typequery import userquery import boolquery import polcapquery # Rule Queries import terulequery import rbacrulequery import mlsrulequery # Information Flow Analysis import infoflow import permmap # Domain Transition Analysis import dta
Send events to be prevented by default
import React, { PropTypes, Component } from 'react'; export default function (WrappedComponent) { class KeyStrokeSupport extends Component { static propTypes = { cancel: PropTypes.func.isRequired, submit: PropTypes.func.isRequired }; constructor (props) { super(props); this.handleKeyDown = this.handleKeyDown.bind(this); } componentWillMount () { document.addEventListener('keydown', this.handleKeyDown); } componentWillUnmount () { document.removeEventListener('keydown', this.handleKeyDown); } handleKeyDown (e) { switch (e.keyCode) { case 13: this.props.submit(e); break; case 27: this.props.cancel(e); break; } } render () { return (<WrappedComponent {...this.props}/>); } } return KeyStrokeSupport; };
import React, { PropTypes, Component } from 'react'; export default function (WrappedComponent) { class KeyStrokeSupport extends Component { static propTypes = { cancel: PropTypes.func.isRequired, submit: PropTypes.func.isRequired }; constructor (props) { super(props); this.handleKeyDown = this.handleKeyDown.bind(this); } componentWillMount () { document.addEventListener('keydown', this.handleKeyDown); } componentWillUnmount () { document.removeEventListener('keydown', this.handleKeyDown); } handleKeyDown (e) { switch (e.keyCode) { case 13: this.props.submit(); break; case 27: this.props.cancel(); break; } } render () { return (<WrappedComponent {...this.props}/>); } } return KeyStrokeSupport; };
Fix the CLI minor bug
#!/usr/bin/env node const jsdotmd = require('../lib') const program = require('commander') const path = require('path') program .usage('[options] <source> <destination>') .option( '-l, --langCodes <items>', 'List of language codes that are compiled into the destination, separated by commas. Default: js,javascript,node', (string) => string.split(',') ) .parse(process.argv) if (program.args.length !== 2) { program.help(() => process.exit(1)) } const {langCodes, args: [source, destination]} = program const currentPath = process.cwd() const sourcePath = path.join(currentPath, source) const destinationPath = path.join(currentPath, destination) jsdotmd.compile(sourcePath, destinationPath, {langCodes}) .catch((err) => console.log('Something went wrong!', err))
#!/usr/bin/env node const jsdotmd = require('../lib') const program = require('commander') const path = require('path') program .usage('[options] <source> <destination') .option( '-l, --langCodes <items>', 'List of language codes that are compiled into the destination, separated by commas. Default: js,javascript,node', (string) => string.split(',') ) .parse(process.argv) if (program.args.length !== 2) { program.help(() => process.exit(1)) } const {langCodes, args: [source, destination]} = program const currentPath = process.cwd() const sourcePath = path.join(currentPath, source) const destinationPath = path.join(currentPath, destination) jsdotmd.compile(sourcePath, destinationPath, {langCodes}) .catch((err) => console.log('Something went wrong!', err))
Add function for adding domains
'use strict'; module.exports = function(app) { app.controller('dataController', [ '$scope', 'HttpService', '$http', '$cookies', function($scope, HttpService, $http, $cookies) { $http.defaults.headers.common.jwt = $cookies.jwt; $scope.selectedDomain = false; var domainService = new HttpService('domains'); $scope.getDomains = function(){ domainService.get() .success(function(domains){ $scope.domains = domains; }); }; $scope.getDomains(); // run on view load var visitService = new HttpService('visits'); $scope.getVisits = function(domain_id){ $scope.selectedDomain = domain_id; visitService.get(domain_id.toString()) .success(function(visits){ $scope.visits = visits; }); }; /** * Add domains */ $scope.addDomain = function() { domainService.post($scope.newDomain, {}); $scope.newDomain = ''; }; } ]); };
'use strict'; module.exports = function(app) { app.controller('dataController', [ '$scope', 'HttpService', '$http', '$cookies', function($scope, HttpService, $http, $cookies) { $http.defaults.headers.common.jwt = $cookies.jwt; $scope.selectedDomain = false; var domainService = new HttpService('domains'); $scope.getDomains = function(){ domainService.get() .success(function(domains){ $scope.domains = domains; }); }; $scope.getDomains(); // run on view load var visitService = new HttpService('visits'); $scope.getVisits = function(domain_id){ $scope.selectedDomain = domain_id; visitService.get(domain_id.toString()) .success(function(visits){ $scope.visits = visits; }); }; } ]); };
Fix range slider merged values tooltip
import React, { forwardRef, useLayoutEffect } from 'react' import PropTypes from 'prop-types' import styles from './styles.module.scss' const MergedValues = forwardRef(({ handles, ...props }, ref) => { const values = handles.map(el => el.value).filter(value => isFinite(value)) const percent = handles.reduce((acc, el) => acc + el.percent / handles.length, 0) useLayoutEffect(() => { ref.current.style.left = `${percent}%` }, [percent, ref]) return ( <div className={styles.mergedValues} ref={ref} {...props}> {`${Math.min(...values).toFixed()} - ${Math.max(...values).toFixed()}`} </div> ) }) MergedValues.propTypes = { handles: PropTypes.array.isRequired } MergedValues.displayName = 'MergedValues' export default MergedValues
import React, { forwardRef, useLayoutEffect } from 'react' import PropTypes from 'prop-types' import styles from './styles.module.scss' const MergedValues = forwardRef(({ handles, ...props }, ref) => { const values = handles.map(el => el.value).filter(value => isFinite(value)) const percent = handles.reduce((acc, el) => acc + el.percent / handles.length, 0) useLayoutEffect(() => { ref.current.style.left = `${percent}%` }, [percent, ref]) return ( <div className={styles.mergedValues} ref={ref} {...props}> {`${Math.max(...values).toFixed()} – ${Math.min(...values).toFixed()}`} </div> ) }) MergedValues.propTypes = { handles: PropTypes.array.isRequired } MergedValues.displayName = 'MergedValues' export default MergedValues
Use native streams in sitemap
// Collect urls to include in sitemap // 'use strict'; const stream = require('stream'); module.exports = function (N, apiPath) { N.wire.on(apiPath, function get_users_sitemap(data) { let user_stream = new stream.Transform({ objectMode: true, transform(user, encoding, callback) { this.push({ loc: N.router.linkTo('users.member', { user_hid: user.hid }), lastmod: user.last_active_ts }); callback(); } }); stream.pipeline( N.models.users.User.find() .where('exists').equals(true) .select('hid last_active_ts') .sort('hid') .lean(true) .stream(), user_stream, () => {} ); data.streams.push({ name: 'users', stream: user_stream }); }); };
// Collect urls to include in sitemap // 'use strict'; const pumpify = require('pumpify'); const through2 = require('through2'); module.exports = function (N, apiPath) { N.wire.on(apiPath, function get_users_sitemap(data) { let stream = pumpify.obj( N.models.users.User.collection .find({ exists: true }, { hid: 1, last_active_ts: 1 }) .sort({ hid: 1 }) .stream(), through2.obj(function (user, encoding, callback) { this.push({ loc: N.router.linkTo('users.member', { user_hid: user.hid }), lastmod: user.last_active_ts }); callback(); }) ); data.streams.push({ name: 'users', stream }); }); };
Fix the engine's APM plugin and add some documentation.
from collections import Counter class APMTracker(object): """ Builds ``player.aps`` and ``player.apm`` dictionaries where an action is any Selection, Hotkey, or Ability event. Also provides ``player.avg_apm`` which is defined as the sum of all the above actions divided by the number of seconds played by the player (not necessarily the whole game) multiplied by 60. APM is 0 for games under 1 minute in length. """ def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.aps.values())/float(player.seconds_played)*60 else: player.avg_apm = 0
from collections import Counter class APMTracker(object): def handleInitGame(self, event, replay): for player in replay.players: player.apm = Counter() player.aps = Counter() player.seconds_played = replay.length.seconds def handlePlayerActionEvent(self, event, replay): event.player.aps[event.second] += 1 event.player.apm[event.second/60] += 1 def handlePlayerLeaveEvent(self, event, replay): event.player.seconds_played = event.second def handleEndGame(self, event, replay): print "Handling End Game" for player in replay.players: if len(player.apm.keys()) > 0: player.avg_apm = sum(player.apm.values())/float(player.seconds_played)*60 else: player.avg_apm = 0
Add comment telling where to get updated geoip database
from __future__ import unicode_literals, print_function, division import pygeoip import os.path import sys import socket # http://dev.maxmind.com/geoip/legacy/geolite/ DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def command_geoip(bot, user, channel, args): """Determine the user's country based on host""" if not args: return bot.say(channel, 'usage: .geoip HOST') try: country = gi4.country_name_by_name(args) except socket.gaierror: country = None if country: return bot.say(channel, "%s is in %s" % (args, country))
from __future__ import unicode_literals, print_function, division import pygeoip import os.path import sys import socket DATAFILE = os.path.join(sys.path[0], "GeoIP.dat") # STANDARD = reload from disk # MEMORY_CACHE = load to memory # MMAP_CACHE = memory using mmap gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE) def command_geoip(bot, user, channel, args): """Determine the user's country based on host""" if not args: return bot.say(channel, 'usage: .geoip HOST') try: country = gi4.country_name_by_name(args) except socket.gaierror: country = None if country: return bot.say(channel, "%s is in %s" % (args, country))
Use a better function (lambda) name git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@40 806ff5bb-693f-0410-b502-81bc3482ff28
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google 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. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. IsFunction = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], IsFunction) if __name__ == '__main__': main(sys.argv)
#!/usr/bin/env python # # Copyright 2007 Neal Norwitz # Portions Copyright 2007 Google 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. """Find and print the functions in a source file.""" import sys from cpp import ast def main(argv): # TODO(nnorwitz): need to ignore friend method declarations. condition = lambda node: isinstance(node, ast.Function) ast.PrintAllIndentifiers(argv[1:], condition) if __name__ == '__main__': main(sys.argv)
[Telemetry] Raise robohornetpro timeout. Is it timing out on cros. BUG=266129 Review URL: https://chromiumcodereview.appspot.com/21297004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@214925 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2012 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. """Runs Microsoft's RoboHornet Pro benchmark.""" import os from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.page import page_set class RobohornetProMeasurement(page_measurement.PageMeasurement): def MeasurePage(self, _, tab, results): tab.ExecuteJavaScript('ToggleRoboHornet()') done = 'document.getElementById("results").innerHTML.indexOf("Total") != -1' def _IsDone(): return tab.EvaluateJavaScript(done) util.WaitFor(_IsDone, 120) result = int(tab.EvaluateJavaScript('stopTime - startTime')) results.Add('Total', 'ms', result) class RobohornetPro(test.Test): test = RobohornetProMeasurement def CreatePageSet(self, options): return page_set.PageSet.FromDict({ 'archive_data_file': '../data/robohornetpro.json', # Measurement require use of real Date.now() for measurement. 'make_javascript_deterministic': False, 'pages': [ { 'url': 'http://ie.microsoft.com/testdrive/performance/robohornetpro/' } ] }, os.path.abspath(__file__))
# Copyright (c) 2012 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. """Runs Microsoft's RoboHornet Pro benchmark.""" import os from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.page import page_set class RobohornetProMeasurement(page_measurement.PageMeasurement): def MeasurePage(self, _, tab, results): tab.ExecuteJavaScript('ToggleRoboHornet()') done = 'document.getElementById("results").innerHTML.indexOf("Total") != -1' def _IsDone(): return tab.EvaluateJavaScript(done) util.WaitFor(_IsDone, 60) result = int(tab.EvaluateJavaScript('stopTime - startTime')) results.Add('Total', 'ms', result) class RobohornetPro(test.Test): test = RobohornetProMeasurement def CreatePageSet(self, options): return page_set.PageSet.FromDict({ 'archive_data_file': '../data/robohornetpro.json', # Measurement require use of real Date.now() for measurement. 'make_javascript_deterministic': False, 'pages': [ { 'url': 'http://ie.microsoft.com/testdrive/performance/robohornetpro/' } ] }, os.path.abspath(__file__))
Use url path instead of full url for threads
var Vue = require('vue'); var CommentService = require('./services/comment-service.js'); var template = require('./list.html'); new Vue({ el: '#platon-comment-thread', render: template.render, staticRenderFns: template.staticRenderFns, data: { loading: true, comments: [] }, components: { 'platon-comment': require('./components/comment'), 'platon-comment-form': require('./components/comment-form') }, methods: { addComment: function(newComment) { this.comments.push(newComment); } }, created: function () { var vm = this; CommentService.getComments(window.location.pathname) .then(function updateModel(comments) { vm.comments = comments; vm.loading = false; }) .catch(function displayError(reason) { alert(reason); }); } });
var Vue = require('vue'); var CommentService = require('./services/comment-service.js'); var template = require('./list.html'); new Vue({ el: '#platon-comment-thread', render: template.render, staticRenderFns: template.staticRenderFns, data: { loading: true, comments: [] }, components: { 'platon-comment': require('./components/comment'), 'platon-comment-form': require('./components/comment-form') }, methods: { addComment: function(newComment) { this.comments.push(newComment); } }, created: function () { var vm = this; CommentService.getComments(window.location.href) .then(function updateModel(comments) { vm.comments = comments; vm.loading = false; }) .catch(function displayError(reason) { alert(reason); }); } });
Correct the hash tag test
<?php if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) { print "This script must be run from the command line\n"; exit(); } define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); define('LACONICA', true); require_once INSTALLDIR . '/lib/common.php'; class HashTagDetectionTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provider * */ public function testProduction($content, $expected) { $rendered = common_render_text($content); $this->assertEquals($expected, $rendered); } static public function provider() { return array( array('hello', 'hello'), array('#hello', '#<span class="tag"><a href="' . common_local_url('tag', array('tag' => common_canonical_tag('hello'))) . '" rel="tag">hello</a></span>'), ); } }
<?php if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) { print "This script must be run from the command line\n"; exit(); } define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); define('LACONICA', true); require_once INSTALLDIR . '/lib/common.php'; class HashTagDetectionTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provider * */ public function testProduction($content, $expected) { $rendered = common_render_text($content); $this->assertEquals($expected, $rendered); } static public function provider() { return array( array('hello', 'hello'), array('#hello', '<a href="/tag/hello">hello</a>'), ); } }
Add process.env inside plugins to react understand that we are at production env
var debug = process.env.NODE_ENV !== "production"; var webpack = require('webpack'); var path = require('path'); module.exports = { context: path.join(__dirname, "src"), devtool: debug ? "inline-sourcemap" : null, entry: "./js/app.js", module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'], } } ] }, output: { path: __dirname + "/src/", filename: "bundle.js" }, plugins: debug ? [] : [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
var debug = process.env.NODE_ENV !== "production"; var webpack = require('webpack'); var path = require('path'); module.exports = { context: path.join(__dirname, "src"), devtool: debug ? "inline-sourcemap" : null, entry: "./js/app.js", module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'], } } ] }, output: { path: __dirname + "/src/", filename: "bundle.js" }, plugins: debug ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
Remove accidentally added UserGreeting from example app.
from flask import Flask, render_template from flask_nav import Nav from flask_nav.elements import * nav = Nav() # registers the "top" menubar nav.register_element('top', Navbar( View('Widgits, Inc.', 'index'), View('Our Mission', 'about'), Subgroup( 'Products', View('Wg240-Series', 'products', product='wg240'), View('Wg250-Series', 'products', product='wg250'), Separator(), Text('Discontinued Products'), View('Wg10X', 'products', product='wg10x'), ), Link('Tech Support', 'http://techsupport.invalid/widgits_inc'), )) def create_app(configfile=None): app = Flask(__name__) nav.init_app(app) # not good style, but like to keep our examples short @app.route('/') def index(): return render_template('index.html') @app.route('/products/<product>/') def products(product): return render_template('index.html', msg='Buy our {}'.format(product)) @app.route('/about-us/') def about(): return render_template('index.html') return app
from flask import Flask, render_template from flask_nav import Nav from flask_nav.elements import * nav = Nav() class UserGreeting(Text): def __init__(self): pass @property def text(self): return 'Hello, {}'.format('bob') # registers the "top" menubar nav.register_element('top', Navbar( View('Widgits, Inc.', 'index'), View('Our Mission', 'about'), Subgroup( 'Products', View('Wg240-Series', 'products', product='wg240'), View('Wg250-Series', 'products', product='wg250'), Separator(), Text('Discontinued Products'), View('Wg10X', 'products', product='wg10x'), ), Link('Tech Support', 'http://techsupport.invalid/widgits_inc'), UserGreeting(), )) def create_app(configfile=None): app = Flask(__name__) nav.init_app(app) # not good style, but like to keep our examples short @app.route('/') def index(): return render_template('index.html') @app.route('/products/<product>/') def products(product): return render_template('index.html', msg='Buy our {}'.format(product)) @app.route('/about-us/') def about(): return render_template('index.html') return app
Fix inviting others to private messages.
/** The controls at the top of a private message in the map area. @class PrivateMessageMapComponent @extends Ember.Component @namespace Discourse @module Discourse **/ Discourse.PrivateMessageMapComponent = Ember.View.extend({ templateName: 'components/private-message-map', tagName: 'section', classNames: ['information'], details: Em.computed.alias('topic.details'), init: function() { this._super(); this.set('context', this); }, actions: { removeAllowedUser: function(user) { var self = this; bootbox.dialog(I18n.t("private_message_info.remove_allowed_user", {name: user.get('username')}), [ {label: I18n.t("no_value"), 'class': 'btn-danger rightg'}, {label: I18n.t("yes_value"), 'class': 'btn-primary', callback: function() { self.get('topic.details').removeAllowedUser(user); } } ]); }, showPrivateInvite: function() { this.get('controller').send('showPrivateInviteAction'); } } });
/** The controls at the top of a private message in the map area. @class PrivateMessageMapComponent @extends Ember.Component @namespace Discourse @module Discourse **/ Discourse.PrivateMessageMapComponent = Ember.View.extend({ templateName: 'components/private-message-map', tagName: 'section', classNames: ['information'], details: Em.computed.alias('topic.details'), init: function() { this._super(); this.set('context', this); this.set('controller', this); }, actions: { removeAllowedUser: function(user) { var self = this; bootbox.dialog(I18n.t("private_message_info.remove_allowed_user", {name: user.get('username')}), [ {label: I18n.t("no_value"), 'class': 'btn-danger rightg'}, {label: I18n.t("yes_value"), 'class': 'btn-primary', callback: function() { self.get('topic.details').removeAllowedUser(user); } } ]); }, showPrivateInvite: function() { this.sendAction('showPrivateInviteAction'); } } });
Mark gdal tests as requiring internet
""" Test gdal plugin functionality. """ import pytest from imageio.testing import run_tests_if_main, get_test_dir, need_internet import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" need_internet() filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main()
""" Test gdal plugin functionality. """ import pytest from imageio.testing import run_tests_if_main, get_test_dir import imageio from imageio.core import get_remote_file test_dir = get_test_dir() try: from osgeo import gdal except ImportError: gdal = None @pytest.mark.skipif('gdal is None') def test_gdal_reading(): """ Test reading gdal""" filename = get_remote_file('images/geotiff.tif') im = imageio.imread(filename, 'gdal') assert im.shape == (929, 699) R = imageio.read(filename, 'gdal') assert R.format.name == 'GDAL' meta_data = R.get_meta_data() assert 'TIFFTAG_XRESOLUTION' in meta_data # Fail raises = pytest.raises raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) run_tests_if_main()
Use more go-like error messages
package main import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" ) type Commands map[string]string func getCommands() (Commands, error) { var commands Commands jsonStream, err := ioutil.ReadFile("./commands.json") if err != nil { return commands, err } decoder := json.NewDecoder(bytes.NewReader(jsonStream)) if err := decoder.Decode(&commands); err != nil { return commands, err } return commands, nil } func commandForFile(path string) (string, error) { commands, err := getCommands() if err != nil { return "", err } extension := strings.Replace(filepath.Ext(path), ".", "", -1) if command := commands[extension]; command != "" { return strings.Replace(command, "%", path, -1), nil } return "", errors.New("run could not determine how to run this file because it does not have a known extension") } func start(args []string) error { if len(args) <= 1 { return errors.New("no files given") } command, err := commandForFile(args[1]) if err != nil { log.Fatal(err) } fmt.Println(command) return nil } func main() { if err := start(os.Args); err != nil { log.Fatal(err) } }
package main import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" ) type Commands map[string]string func getCommands() (Commands, error) { var commands Commands jsonStream, err := ioutil.ReadFile("./commands.json") if err != nil { return commands, err } decoder := json.NewDecoder(bytes.NewReader(jsonStream)) if err := decoder.Decode(&commands); err != nil { return commands, err } return commands, nil } func commandForFile(path string) (string, error) { commands, err := getCommands() if err != nil { return "", err } extension := strings.Replace(filepath.Ext(path), ".", "", -1) if command := commands[extension]; command != "" { return strings.Replace(command, "%", path, -1), nil } else { return "", errors.New("Run could not determine how to run this file because it does not have a known extension.") } } func start(args []string) error { if len(args) <= 1 { return errors.New("No files given.") } command, err := commandForFile(args[1]) if err != nil { log.Fatal(err) } fmt.Println(command) return nil } func main() { if err := start(os.Args); err != nil { log.Fatal(err) } }
Remove inline opacity style after transition complete (This was causing the raw tag editor to sometimes *not* display for fallback presets like "point", "line", "area")
// toggles the visibility of ui elements, using a combination of the // hide class, which sets display=none, and a d3 transition for opacity. // this will cause blinking when called repeatedly, so check that the // value actually changes between calls. iD.ui.Toggle = function(show, callback) { return function(selection) { selection .style('opacity', show ? 0 : 1) .classed('hide', false) .transition() .style('opacity', show ? 1 : 0) .each('end', function() { d3.select(this) .classed('hide', !show) .style('opacity', null); if (callback) callback.apply(this); }); }; };
// toggles the visibility of ui elements, using a combination of the // hide class, which sets display=none, and a d3 transition for opacity. // this will cause blinking when called repeatedly, so check that the // value actually changes between calls. iD.ui.Toggle = function(show, callback) { return function(selection) { selection .style('opacity', show ? 0 : 1) .classed('hide', false) .transition() .style('opacity', show ? 1 : 0) .each('end', function() { d3.select(this).classed('hide', !show); if (callback) callback.apply(this); }); }; };
feat(back): Add mapping to angular routes
const path = require('path'); const express = require('express'); const router = express.Router(); const log = require('../logger'); const wordsRepository = new (require("../repositories/word.repository"))(); router.get('/', (req, res) => { wordsRepository.getRandomWords(6) .then(words => { res.render("index", { "words": words.map(word => word.dataValues) }); }) .catch(error => { log.error(error); res.status(500).json(error); }) }); router.get([ '/chat', '/account', '/leaderboards', '/signin', '/signup', '/score'], (req, res) => { const mainFilePath = path.join(__dirname, '..', '..', 'front', 'dist', 'index.html'); res.sendFile(path.join(mainFilePath)); }); module.exports = router;
const path = require('path'); const express = require('express'); const router = express.Router(); const log = require('../logger'); const wordsRepository = new (require("../repositories/word.repository"))(); router.get('/', (req, res) => { wordsRepository.getRandomWords(6) .then(words => { res.render("index", { "words": words.map(word => word.dataValues) }); }) .catch(error => { log.error(error); res.status(500).json(error); }) }); router.get(['/chat', '/account', '/leaderboards'], (req, res) => { const mainFilePath = path.join(__dirname, '..', '..', 'front', 'dist', 'index.html'); res.sendFile(path.join(mainFilePath)); }); module.exports = router;
Fix formatting bug in repr
#!/usr/bin/env python import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time.delta / 1000000000.0, self.duration.delta / 1000000000.0 return '<TimeSlice, start: {0:.2f}, duration: {1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice)
#!/usr/bin/env python import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time, self.duration return '<TimeSlice, start:{0:.2f}, duration:{1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice)
Remove fatal error in workers
package main import ( "fmt" "time" "sync" ) var wg sync.WaitGroup func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { if j == -1 { wg.Done() break } fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } func printer(results <-chan int) { for r := range results { fmt.Println(r) } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) // This starts up 3 workers, initially blocked // because there are no jobs yet. for w := 1; w <= 3; w++ { wg.Add(1) go worker(w, jobs, results) } go printer(results) // Here we send 9 `jobs` and then `close` that // channel to indicate that's all the work we have. for j := 1; j <= 9; j++ { jobs <- j } for w := 1; w <= 3; w++ { jobs <- -1 } wg.Wait() }
package main import ( "fmt" "time" "sync" ) var wg sync.WaitGroup func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { if j == -1 { wg.Done() return } fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } func printer(results <-chan int) { for r := range results { fmt.Println(r) } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) // This starts up 3 workers, initially blocked // because there are no jobs yet. for w := 1; w <= 3; w++ { wg.Add(1) go worker(w, jobs, results) } go printer(results) // Here we send 9 `jobs` and then `close` that // channel to indicate that's all the work we have. for j := 1; j <= 9; j++ { jobs <- j } for w := 1; w <= 3; w++ { jobs <- -1 } wg.Wait() }
Modify block colors for greater contrast
import _merge from 'lodash/merge' import moment from 'moment' let today = moment().format('YYYY-MM-DD') export default { loading: true, schedule: {}, // Restore saved preferences to over default lunches and classes lunches: _merge({ 'Monday': 1, 'Tuesday': 1, 'Wednesday': 1, 'Thursday': 1, 'Friday': 1 }, JSON.parse(localStorage.getItem('lunches')) || {}), classes: _merge({ 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '' }, JSON.parse(localStorage.getItem('classes')) || {}), // Design constants colors: ['#3F51B5', '#1976D2', '#039BE5', '#00BCD4', '#009688', '#43A047', '#7CB342'], // Check if client is crawler so it doesn't see a countdown in the title! isCrawler: /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent), // Set default dates to determine week to display displayDate: today, today, // Set default countdown so checking each blocks begins with the first one countdown: { i: 0 }, // Queue for next countdown call (a timeout Promise) queue: null }
import _merge from 'lodash/merge' import moment from 'moment' let today = moment().format('YYYY-MM-DD') export default { loading: true, schedule: {}, // Restore saved preferences to over default lunches and classes lunches: _merge({ 'Monday': 1, 'Tuesday': 1, 'Wednesday': 1, 'Thursday': 1, 'Friday': 1 }, JSON.parse(localStorage.getItem('lunches')) || {}), classes: _merge({ 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '' }, JSON.parse(localStorage.getItem('classes')) || {}), // Design constants colors: ['#3F51B5', '#1976D2', '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A'], // Check if client is crawler so it doesn't see a countdown in the title! isCrawler: /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent), // Set default dates to determine week to display displayDate: today, today, // Set default countdown so checking each blocks begins with the first one countdown: { i: 0 }, // Queue for next countdown call (a timeout Promise) queue: null }
Fix encoding error happening on some Windows servers Fix error causing: “UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d”
from setuptools import setup def readme(): with open('README.rst', 'rb') as f: return f.read().decode('UTF-8') setup(name='housecanary', version='0.6.2', description='Client Wrapper for the HouseCanary API', long_description=readme(), url='http://github.com/housecanary/hc-api-python', author='HouseCanary', author_email='techops@housecanary.com', license='MIT', packages=['housecanary', 'housecanary.excel'], install_requires=['requests', 'docopt', 'openpyxl'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'mock'], entry_points={ 'console_scripts': [ 'hc_api_excel_concat=housecanary.hc_api_excel_concat.hc_api_excel_concat:main', 'hc_api_export=housecanary.hc_api_export.hc_api_export:main' ] })
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='housecanary', version='0.6.2', description='Client Wrapper for the HouseCanary API', long_description=readme(), url='http://github.com/housecanary/hc-api-python', author='HouseCanary', author_email='techops@housecanary.com', license='MIT', packages=['housecanary', 'housecanary.excel'], install_requires=['requests', 'docopt', 'openpyxl'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'mock'], entry_points={ 'console_scripts': [ 'hc_api_excel_concat=housecanary.hc_api_excel_concat.hc_api_excel_concat:main', 'hc_api_export=housecanary.hc_api_export.hc_api_export:main' ] })
Fix too long line issue
'use strict'; var Node = require('../node'); var dot = require('dot'); var TYPE = 'weighted-centroid'; var PARAMS = { source : Node.PARAM.NODE(Node.GEOMETRY.POINT), weight_column : Node.PARAM.STRING, category_column : Node.PARAM.STRING }; var WeightedCentroid = Node.create(TYPE, PARAMS, {cache: true}); module.exports = WeightedCentroid; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; var weightedCentroidTemplate = dot.template([ 'SELECT the_geom, class', 'FROM cdb_crankshaft.CDB_WeightedMean(', ' $weightedmean_query${{=it.query}}$weightedmean_query$,', ' \'{{=it.weight_column}}\',', ' \'{{=it.category_column}}\'', ')' ].join('\n')); function query(it) { return weightedCentroidTemplate(it); } WeightedCentroid.prototype.sql = function(){ return query({ query : this.source.getQuery(), weight_column : this.weight_column, category_column : this.category_column }); };
'use strict'; var Node = require('../node'); var dot = require('dot'); var TYPE = 'weighted-centroid'; var PARAMS = { source : Node.PARAM.NODE(Node.GEOMETRY.POINT), weight_column : Node.PARAM.STRING, category_column : Node.PARAM.STRING }; var WeightedCentroid = Node.create(TYPE, PARAMS, {cache: true}); module.exports = WeightedCentroid; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; var weightedCentroidTemplate = dot.template([ 'SELECT the_geom , class', 'FROM cdb_crankshaft.CDB_WeightedMean($weightedmean_query${{=it.query}}$weightedmean_query$,\'{{=it.weight_column}}\',\'{{=it.category_column}}\')' ].join('\n')); function query(it) { return weightedCentroidTemplate(it); } WeightedCentroid.prototype.sql = function(){ return query({ query : this.source.getQuery(), weight_column : this.weight_column, category_column : this.category_column }); };
Use material-ui Table for module table
import React, { PropTypes } from 'react'; import { Table, TableBody, TableRow, TableRowColumn } from 'material-ui/Table'; const ModuleTable = ({ modules, removeModule, }) => ( <Table selectable={false} style={{ tableLayout: 'auto' }} > <TableBody displayRowCheckbox={false} > {modules.map(module => <TableRow key={module.ModuleCode}> <TableRowColumn>{module.ModuleCode}</TableRowColumn> <TableRowColumn>{module.ModuleTitle}</TableRowColumn> <TableRowColumn> <button className="btn btn-sm btn-danger" onClick={() => removeModule(module.ModuleCode)} > Remove </button> </TableRowColumn> </TableRow> )} </TableBody> </Table> ); ModuleTable.propTypes = { modules: PropTypes.array.isRequired, removeModule: PropTypes.func.isRequired, }; export default ModuleTable;
import React, { PropTypes } from 'react'; const ModuleTable = ({ modules, removeModule, }) => ( <table className="table table-bordered"> <tbody> {modules.map(module => <tr key={module.ModuleCode}> <td>{module.ModuleCode}</td> <td>{module.ModuleTitle}</td> <td> <button className="btn btn-sm btn-danger" onClick={() => removeModule(module.ModuleCode)} > Remove </button> </td> </tr> )} </tbody> </table> ); ModuleTable.propTypes = { modules: PropTypes.array.isRequired, removeModule: PropTypes.func.isRequired, }; export default ModuleTable;
Fix study actions order on the toolbar
package com.jetbrains.edu.learning; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.Project; import com.jetbrains.edu.courseFormat.Course; import org.jetbrains.annotations.NotNull; public class PyStudyToolWindowConfigurator extends StudyBaseToolWindowConfigurator { @NotNull @Override public DefaultActionGroup getActionGroup(Project project) { final DefaultActionGroup baseGroup = super.getActionGroup(project); final DefaultActionGroup group = new DefaultActionGroup(); group.add(new PyStudyCheckAction()); group.addAll(baseGroup); return group; } @NotNull @Override public String getDefaultHighlightingMode() { return "python"; } @Override public boolean accept(@NotNull Project project) { StudyTaskManager taskManager = StudyTaskManager.getInstance(project); if (taskManager == null) return false; Course course = taskManager.getCourse(); return course != null && "Python".equals(course.getLanguage()) && "PyCharm".equals(course.getCourseType()); } }
package com.jetbrains.edu.learning; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.Project; import com.jetbrains.edu.courseFormat.Course; import org.jetbrains.annotations.NotNull; public class PyStudyToolWindowConfigurator extends StudyBaseToolWindowConfigurator { @NotNull @Override public DefaultActionGroup getActionGroup(Project project) { final DefaultActionGroup group = super.getActionGroup(project); group.add(new PyStudyCheckAction()); return group; } @NotNull @Override public String getDefaultHighlightingMode() { return "python"; } @Override public boolean accept(@NotNull Project project) { StudyTaskManager taskManager = StudyTaskManager.getInstance(project); if (taskManager == null) return false; Course course = taskManager.getCourse(); return course != null && "Python".equals(course.getLanguage()) && "PyCharm".equals(course.getCourseType()); } }
Add resolved debug and rtl values to plugin The Lazy Way ©
'use strict' var postcss = require('postcss') var defined = require('defined') var noop = postcss.plugin('noop', function () { return function (css) {} }) module.exports = postcss.plugin('@emilbayes/css-pipeline', function (options) { options = options || {} var rtl = defined(options.rtl, process.env.RTL == true, false) var debug = defined(options.debug, process.env.DEBUG == true, false) return Object.assign(postcss([ require('postcss-import')({ plugins: [ debug === true ? require('stylelint')(require('stylelint-config-standard')) : noop() ] }), require('postcss-url')({url: 'rebase'}), rtl === true ? require('rtlcss')() : noop(), require('postcss-cssnext')(), debug === false ? require('cssnano')({ autoprefixer: false }) : noop(), debug === true ? require('postcss-browser-reporter')() : noop() ]), {debug: debug, rtl: rtl}) })
'use strict' var postcss = require('postcss') var defined = require('defined') var noop = postcss.plugin('noop', function () { return function (css) {} }) module.exports = postcss.plugin('@emilbayes/css-pipeline', function (options) { options = options || {} var rtl = defined(options.rtl, process.env.RTL == true, false) var debug = defined(options.debug, process.env.DEBUG == true, false) return postcss([ require('postcss-import')({ plugins: [ debug === true ? require('stylelint')(require('stylelint-config-standard')) : noop() ] }), require('postcss-url')({url: 'rebase'}), rtl === true ? require('rtlcss')() : noop(), require('postcss-cssnext')(), debug === false ? require('cssnano')({ autoprefixer: false }) : noop(), debug === true ? require('postcss-browser-reporter')() : noop() ]) })
Add match error msg pattern like "<file>:<line>: syntax error" This error msg is available in iverilog 0.10.0 (devel).
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # https://github.com/jfcherng/SublimeLinter-contrib-iverilog # Copyright (c) 2015 jfcherng # # License: MIT # import sublime from SublimeLinter.lint import Linter, util class Iverilog(Linter): # linter basic settings syntax = ('verilog') cmd = 'iverilog -t null' tempfile_suffix = 'verilog' multiline = False error_stream = util.STREAM_BOTH # there is a ":" in the filepath under Windows # like C:\SOME_FOLDERS\...\FILE if sublime.platform() == 'windows': filepath = r'[^:]+:[^:]+' else: filepath = r'[^:]+' # what kind of message should be caught? regex = ( r'(?P<file>{0}):(?P<line>\d+): ' r'((?P<warning>warning: )|(?P<error>error: |))' r'(?P<message>.*)' .format(filepath) )
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2015 jfcherng # https://github.com/jfcherng/SublimeLinter-contrib-iverilog # # License: MIT # import sublime from SublimeLinter.lint import Linter, util class Iverilog(Linter): # linter basic settings syntax = ('verilog') cmd = 'iverilog -t null' tempfile_suffix = 'verilog' error_stream = util.STREAM_BOTH # what kind of message should be caught? if sublime.platform() == 'windows': regex = ( r'^([^:]+):.*:(?P<line>\d*):' r'.((?P<error>error)|(?P<warning>warning))?' r'(?P<message>.*)' ) else: regex = ( r'^([^:]+):(?P<line>\d+): ' r'(?:(?P<error>error)|(?P<warning>warning): )?' r'(?P<message>.+)' )
[REFACTOR] Remove "final" keyword on getItems and getDefaultId methods in dynamic list services.
<?php /** * event_ListAvailablemodelsService * @package modules.event.lib.services */ class event_ListAvailablemodelsService extends BaseService implements list_ListItemsService { /** * @var event_ListAvailablemodelsService */ private static $instance; /** * @return event_ListAvailablemodelsService */ public static function getInstance() { if (self::$instance === null) { self::$instance = self::getServiceClassInstance(get_class()); } return self::$instance; } /** * @see list_persistentdocument_dynamiclist::getItems() * @return list_Item[] */ public function getItems() { $items = array(); $ls = LocaleService::getInstance(); $baseModel = f_persistentdocument_PersistentDocumentModel::getInstance('event', 'baseevent'); foreach ($baseModel->getChildrenNames() as $modelName) { $model = f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName($modelName); if ($model->getName() == $modelName) { $items[] = new list_Item($ls->transBO($model->getLabelKey(), array('ucf')), $modelName); } } return $items; } /** * @var Array */ private $parameters = array(); /** * @see list_persistentdocument_dynamiclist::getListService() * @param array $parameters */ public function setParameters($parameters) { $this->parameters = $parameters; } }
<?php /** * event_ListAvailablemodelsService * @package modules.event.lib.services */ class event_ListAvailablemodelsService extends BaseService implements list_ListItemsService { /** * @var event_ListAvailablemodelsService */ private static $instance; /** * @return event_ListAvailablemodelsService */ public static function getInstance() { if (self::$instance === null) { self::$instance = self::getServiceClassInstance(get_class()); } return self::$instance; } /** * @see list_persistentdocument_dynamiclist::getItems() * @return list_Item[] */ public final function getItems() { $items = array(); $ls = LocaleService::getInstance(); $baseModel = f_persistentdocument_PersistentDocumentModel::getInstance('event', 'baseevent'); foreach ($baseModel->getChildrenNames() as $modelName) { $model = f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName($modelName); if ($model->getName() == $modelName) { $items[] = new list_Item($ls->transBO($model->getLabelKey(), array('ucf')), $modelName); } } return $items; } /** * @var Array */ private $parameters = array(); /** * @see list_persistentdocument_dynamiclist::getListService() * @param array $parameters */ public function setParameters($parameters) { $this->parameters = $parameters; } }
Use streams instead of strings for the response when reading.
<?php namespace h4cc\StackFlysystem\Handler; use DateTime; use h4cc\StackFlysystem\HandlerInterface; use League\Flysystem\Filesystem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\StreamedResponse; class Reader implements HandlerInterface { private $filesystem; public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } public function handlesRequest(Request $request) { return ('GET' == $request->getMethod()); } public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { /** @var \League\Flysystem\File $file */ $file = $this->filesystem->get($request->getRequestUri()); $response = new StreamedResponse(function () use ($file) { $stream = $file->readStream(); fpassthru($stream); }, 200); $response->headers->set('Content-Type', $file->getMimetype()); $timestamp = $file->getTimestamp(); if ($timestamp) { $response->setLastModified(new DateTime('@' . $timestamp)); } return $response; } }
<?php namespace h4cc\StackFlysystem\Handler; use h4cc\StackFlysystem\HandlerInterface; use League\Flysystem\Filesystem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class Reader implements HandlerInterface { private $filesystem; public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } public function handlesRequest(Request $request) { return ('GET' == $request->getMethod()); } public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { /** @var \League\Flysystem\File $file */ $file = $this->filesystem->get($request->getRequestUri()); $response = new Response($file->read(), 200); $response->headers->set('Content-Type', $file->getMimetype()); $timestamp = $file->getTimestamp(); if ($timestamp) { $response->setLastModified(new \DateTime('@' . $timestamp)); } return $response; } }
Fix test case to work with newest version of datastax java driver
package com.pardot.rhombus.functional; import static org.junit.Assert.*; import com.datastax.driver.core.exceptions.InvalidConfigurationInQueryException; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.pardot.rhombus.helpers.TestHelpers; import org.junit.Test; import com.datastax.driver.core.Session; import com.pardot.rhombus.ConnectionManager; import java.io.IOException; public class CassandraConnectionITCase { @Test public void testKeyspaceCreate() throws IOException { ConnectionManager cm = new ConnectionManager(TestHelpers.getTestCassandraConfiguration()); cm.buildCluster(); Session session = cm.getEmptySession(); assertNotNull(session); //Drop the functional keyspace if it exists try { session.execute("DROP KEYSPACE functional_create"); } catch (InvalidQueryException e) { //Ignore } //Create the functional keyspace session.execute("CREATE KEYSPACE functional_create WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }"); //Change to our functional testing keyspace session.execute("USE functional_create"); //Drop the functional keyspace try { session.execute("DROP KEYSPACE functional_create"); } catch (InvalidQueryException e) { //Ignore } //Shutdown the session session.shutdown(); //Teardown the connection manager cm.teardown(); } }
package com.pardot.rhombus.functional; import static org.junit.Assert.*; import com.datastax.driver.core.exceptions.InvalidConfigurationInQueryException; import com.pardot.rhombus.helpers.TestHelpers; import org.junit.Test; import com.datastax.driver.core.Session; import com.pardot.rhombus.ConnectionManager; import java.io.IOException; public class CassandraConnectionITCase { @Test public void testKeyspaceCreate() throws IOException { ConnectionManager cm = new ConnectionManager(TestHelpers.getTestCassandraConfiguration()); cm.buildCluster(); Session session = cm.getEmptySession(); assertNotNull(session); //Drop the functional keyspace if it exists try { session.execute("DROP KEYSPACE functional_create"); } catch (InvalidConfigurationInQueryException e) { //Ignore } //Create the functional keyspace session.execute("CREATE KEYSPACE functional_create WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }"); //Change to our functional testing keyspace session.execute("USE functional_create"); //Drop the functional keyspace try { session.execute("DROP KEYSPACE functional_create"); } catch (InvalidConfigurationInQueryException e) { //Ignore } //Shutdown the session session.shutdown(); //Teardown the connection manager cm.teardown(); } }
Use jsonpointer instead of my own terrible Reference class.
import json import jsonpointer class Schema(dict): """ Lightweight encapsulation of a JSON Schema. """ @classmethod def from_file(cls, path_or_stream): """ Create a schema from a file name or stream. """ if hasattr(path_or_stream, 'read'): return cls(json.load(path_or_stream)) else: with open(path_or_stream) as fp: return cls(json.load(fp)) def resolve_ref(self, ref): if not ref.startswith('#'): raise ValueError("non-fragment references are not supported (got: %s)" % ref) return jsonpointer.resolve_pointer(self, ref.lstrip('#'))
import json class Schema(dict): """ Lightweight encapsulation of a JSON Schema. """ @classmethod def from_file(cls, path_or_stream): """ Create a schema from a file name or stream. """ if hasattr(path_or_stream, 'read'): return cls(json.load(path_or_stream)) else: with open(path_or_stream) as fp: return cls(json.load(fp)) def resolve_ref(self, ref): return Reference(ref).resolve(self) class Reference(object): def __init__(self, ref): if not ref.startswith('#'): raise ValueError("non-fragment references are not supported (got: %s)" % ref) self.ref = ref def resolve(self, schema): # Very overly simplisitic - doesn't handle array indexes, etc. However, # works with Heroku's schema, so good enough for a prototype. node = schema for bit in self.ref.split('/')[1:]: node = node[bit] return node
Fix byte swap for Explicit VR Big Endian (retired)
/* eslint no-bitwise: 0 */ function swap16 (val) { return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF); } function decodeBigEndian (imageFrame, pixelData) { if (imageFrame.bitsAllocated === 16) { let arrayBuffer = pixelData.buffer; let offset = pixelData.byteOffset; const length = pixelData.length; // if pixel data is not aligned on even boundary, shift it so we can create the 16 bit array // buffers on it if (offset % 2) { arrayBuffer = arrayBuffer.slice(offset); offset = 0; } if (imageFrame.pixelRepresentation === 0) { imageFrame.pixelData = new Uint16Array(arrayBuffer, offset, length / 2); } else { imageFrame.pixelData = new Int16Array(arrayBuffer, offset, length / 2); } // Do the byte swap for (let i = 0; i < imageFrame.pixelData.length; i++) { imageFrame.pixelData[i] = swap16(imageFrame.pixelData[i]); } } else if (imageFrame.bitsAllocated === 8) { imageFrame.pixelData = pixelData; } return imageFrame; } export default decodeBigEndian;
/* eslint no-bitwise: 0 */ function swap16 (val) { return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF); } function decodeBigEndian (imageFrame, pixelData) { if (imageFrame.bitsAllocated === 16) { let arrayBuffer = pixelData.buffer; let offset = pixelData.byteOffset; const length = pixelData.length; // if pixel data is not aligned on even boundary, shift it so we can create the 16 bit array // buffers on it if (offset % 2) { arrayBuffer = arrayBuffer.slice(offset); offset = 0; } if (imageFrame.pixelRepresentation === 0) { imageFrame.pixelData = new Uint16Array(arrayBuffer, offset, length / 2); } else { imageFrame.pixelData = new Int16Array(arrayBuffer, offset, length / 2); } // Do the byte swap for (let i = 0; i < imageFrame.pixelData.length; i++) { imageFrame[i] = swap16(imageFrame.pixelData[i]); } } else if (imageFrame.bitsAllocated === 8) { imageFrame.pixelData = pixelData; } return imageFrame; } export default decodeBigEndian;
Fix `httpFileSystemLoader.Open` to not crash on nil The reason is that in certain cases (mainly in development) this loader might be configured with an empty file system – it accepts an interface so passing nil just works. If `Open` is called it shouldn’t crash.
package httpfs import ( "io" "net/http" "os" "github.com/CloudyKit/jet" ) type httpFileSystemLoader struct { fs http.FileSystem } // NewLoader returns an initialized loader serving the passed http.FileSystem. func NewLoader(fs http.FileSystem) jet.Loader { return &httpFileSystemLoader{fs: fs} } // Open opens the file via the internal http.FileSystem. It is the callers duty to close the file. func (l *httpFileSystemLoader) Open(name string) (io.ReadCloser, error) { if l.fs == nil { return nil, &os.PathError{Op: "open", Path: name, Err: os.ErrNotExist} } return l.fs.Open(name) } // Exists checks if the template name exists by walking the list of template paths // returns string with the full path of the template and bool true if the template file was found func (l *httpFileSystemLoader) Exists(name string) (string, bool) { if l.fs == nil { return "", false } if f, err := l.Open(name); err == nil { f.Close() return name, true } return "", false }
package httpfs import ( "io" "net/http" "os" "github.com/CloudyKit/jet" ) type httpFileSystemLoader struct { fs http.FileSystem } // NewLoader returns an initialized loader serving the passed http.FileSystem. func NewLoader(fs http.FileSystem) jet.Loader { return &httpFileSystemLoader{fs: fs} } // Open opens the file via the internal http.FileSystem. It is the callers duty to close the file. func (l *httpFileSystemLoader) Open(name string) (io.ReadCloser, error) { return l.fs.Open(name) } // Exists checks if the template name exists by walking the list of template paths // returns string with the full path of the template and bool true if the template file was found func (l *httpFileSystemLoader) Exists(name string) (string, bool) { if l.fs == nil { return "", false } if f, err := l.Open(name); err == nil { f.Close() return name, true } return "", false }
Add regex rule for repeater selector
var utilConfig = { regexList : [ { type : "attr", attrName : "ng-model", match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi }, { type : "attr", attrName : "ng-repeat", match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi }, { type : "cssAttr", match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi }, { type : "attr", attrName : "ng-bind", match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi }, { type: "attr", attrName : "ng-repeat", match: /[b|B]y\.repeater\(\s*['|"](.*? in .*?)['|"]\s*\)/gi } ], getRegexList : function(){ return this.regexList; } }; module.exports = utilConfig;
var utilConfig = { regexList : [ { type : "attr", attrName : "ng-model", match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi }, { type : "attr", attrName : "ng-repeat", match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi }, { type : "cssAttr", match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi }, { type : "attr", attrName : "ng-bind", match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi } ], getRegexList : function(){ return this.regexList; } }; module.exports = utilConfig;
Add preview images cache clearing
<?php namespace Craft; class WistiaPlugin extends BasePlugin { public function getName() { return 'Wistia'; } public function getDescription() { return 'Manage videos and output data using the Wistia API.'; } public function getVersion() { return '0.1.5'; } public function getDeveloper() { return 'Caddis'; } public function getDeveloperUrl() { return 'https://www.caddis.co'; } public function getDocumentationUrl() { return 'https://www.caddis.co/software/craft/wistia'; } public function getSchemaVersion() { return '1.0.0'; } protected function defineSettings() { return array( 'apiKey' => AttributeType::String, 'cacheDuration' => array( AttributeType::Number, 'default' => 24 ), 'thumbnailPath' => array( AttributeType::String, 'default' => '/images/videos/' ) ); } public function getSettingsHtml() { return craft()->templates->render('wistia/plugin/settings', array( 'settings' => $this->getSettings() )); } public function registerCachePaths() { return array( $_SERVER['DOCUMENT_ROOT'] . craft()->plugins->getPlugin('wistia')->getSettings()->thumbnailPath => Craft::t('Wistia Preview Images') ); } }
<?php namespace Craft; class WistiaPlugin extends BasePlugin { public function getName() { return 'Wistia'; } public function getDescription() { return 'Manage videos and output data using the Wistia API.'; } public function getVersion() { return '0.1.5'; } public function getDeveloper() { return 'Caddis'; } public function getDeveloperUrl() { return 'https://www.caddis.co'; } public function getDocumentationUrl() { return 'https://www.caddis.co/software/craft/wistia'; } public function getSchemaVersion() { return '1.0.0'; } protected function defineSettings() { return array( 'apiKey' => AttributeType::String, 'cacheDuration' => array( AttributeType::Number, 'default' => 24 ), 'thumbnailPath' => array( AttributeType::String, 'default' => '/images/videos/' ) ); } public function getSettingsHtml() { return craft()->templates->render('wistia/plugin/settings', array( 'settings' => $this->getSettings() )); } }
Add more 2 indexes to cache to improve invalidation speed
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", unique=True, name="unique gid") db.problems.ensure_index("pid", unique=True, name="unique pid") db.submissions.ensure_index("tid", name="submission tids") db.ssh.ensure_index("tid", unique=True, name="unique ssh tid") db.teams.ensure_index("team_name", unique=True, name="unique team names") db.shell_servers.ensure_index("name", unique=True, name="unique shell name") db.shell_servers.ensure_index("sid", unique=True, name="unique shell sid") db.cache.ensure_index("expireAt", expireAfterSeconds=0) db.cache.ensure_index("kwargs", name="kwargs") db.cache.ensure_index("kwargs.uid", name="kwargs.uid") db.cache.ensure_index("kwargs.tid", name="kwargs.tid") db.cache.ensure_index("args", name="args") db.shell_servers.ensure_index( "sid", unique=True, name="unique shell server id")
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", unique=True, name="unique gid") db.problems.ensure_index("pid", unique=True, name="unique pid") db.submissions.ensure_index("tid", name="submission tids") db.ssh.ensure_index("tid", unique=True, name="unique ssh tid") db.teams.ensure_index("team_name", unique=True, name="unique team names") db.shell_servers.ensure_index("name", unique=True, name="unique shell name") db.shell_servers.ensure_index("sid", unique=True, name="unique shell sid") db.cache.ensure_index("expireAt", expireAfterSeconds=0) db.cache.ensure_index("kwargs", name="kwargs") db.cache.ensure_index("args", name="args") db.shell_servers.ensure_index( "sid", unique=True, name="unique shell server id")
Use string template in place of concatenation (STRIPES-100)
import React from 'react'; import Route from 'react-router-dom/Route'; import { connectFor } from '@folio/stripes-connect'; import { modules } from 'stripes-loader'; // eslint-disable-line import AddContext from './AddContext'; if (!Array.isArray(modules.app) && modules.length < 0) { throw new Error('At least one module of type "app" must be enabled.'); } function getModuleRoutes(stripes) { return modules.app.map((module) => { const name = module.module.replace(/^@folio\//, ''); const perm = `module.${name}.enabled`; if (!stripes.hasPerm(perm)) return null; const connect = connectFor(module.module, stripes.epics, stripes.logger); const Current = connect(module.getModule()); const moduleStripes = stripes.clone({ connect }); return ( <Route path={module.route} key={module.route} render={props => <AddContext context={{ stripes: moduleStripes }}> <span id={`${name}-module-display`} data-module={module.module} data-version={module.version} > <Current {...props} connect={connect} stripes={moduleStripes} /> </span> </AddContext> } /> ); }).filter(x => x); } export default getModuleRoutes;
import React from 'react'; import Route from 'react-router-dom/Route'; import { connectFor } from '@folio/stripes-connect'; import { modules } from 'stripes-loader'; // eslint-disable-line import AddContext from './AddContext'; if (!Array.isArray(modules.app) && modules.length < 0) { throw new Error('At least one module of type "app" must be enabled.'); } function getModuleRoutes(stripes) { return modules.app.map((module) => { const name = module.module.replace(/^@folio\//, ''); const perm = `module.${name}.enabled`; if (!stripes.hasPerm(perm)) return null; const connect = connectFor(module.module, stripes.epics, stripes.logger); const Current = connect(module.getModule()); const moduleStripes = stripes.clone({ connect }); return ( <Route path={module.route} key={module.route} render={props => <AddContext context={{ stripes: moduleStripes }}> <span id={name+'-module-display'} data-module={module.module} data-version={module.version} > <Current {...props} connect={connect} stripes={moduleStripes} /> </span> </AddContext> } /> ); }).filter(x => x); } export default getModuleRoutes;
Add last version of Google Java Format to supported versions
package com.github.sherter.googlejavaformatgradleplugin.format; import com.google.common.collect.ImmutableList; /** Static factory method for creating new {@link Formatter}s. */ public class Gjf { public static final String GROUP_ID = "com.google.googlejavaformat"; public static final String ARTIFACT_ID = "google-java-format"; public static final ImmutableList<String> SUPPORTED_VERSIONS = ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7"); /** * Constructs a new formatter that delegates to <a * href="https://github.com/google/google-java-format">google-java-format</a>. * * @param classLoader load {@code google-java-format} classes from this {@code ClassLoader} * @param config configure the formatter according to this configuration * @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed */ public static Formatter newFormatter(ClassLoader classLoader, Configuration config) throws ReflectiveOperationException { return newFormatterFactory(classLoader, config).create(); } private static FormatterFactory newFormatterFactory( ClassLoader classLoader, Configuration config) { switch (config.version) { case "1.0": return new OneDotZeroFactory(classLoader, config); case "1.1": return new OneDotOneFactory(classLoader, config); default: return new OneDotOneFactory(classLoader, config); } } }
package com.github.sherter.googlejavaformatgradleplugin.format; import com.google.common.collect.ImmutableList; /** Static factory method for creating new {@link Formatter}s. */ public class Gjf { public static final String GROUP_ID = "com.google.googlejavaformat"; public static final String ARTIFACT_ID = "google-java-format"; public static final ImmutableList<String> SUPPORTED_VERSIONS = ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6"); /** * Constructs a new formatter that delegates to <a * href="https://github.com/google/google-java-format">google-java-format</a>. * * @param classLoader load {@code google-java-format} classes from this {@code ClassLoader} * @param config configure the formatter according to this configuration * @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed */ public static Formatter newFormatter(ClassLoader classLoader, Configuration config) throws ReflectiveOperationException { return newFormatterFactory(classLoader, config).create(); } private static FormatterFactory newFormatterFactory( ClassLoader classLoader, Configuration config) { switch (config.version) { case "1.0": return new OneDotZeroFactory(classLoader, config); case "1.1": return new OneDotOneFactory(classLoader, config); default: return new OneDotOneFactory(classLoader, config); } } }
Reorganize jsdoc, add @method tag
define(function () { "use strict"; var Edge = function (nodes) { this.setNodes(nodes); }; Edge.prototype.setNodes = function (nodes) { this._nodes = nodes; return this; }; Edge.prototype.getNodes = function () { return this._nodes; }; Edge.prototype.addTo = function (graph) { this._resolveIds(graph); graph.addEdge(this); return this; }; /** * Replace string IDs representing nodes with node references * @private * @method * * @param {G.Graph} graph - Graph to retrieve node references from IDs * @returns {undefined} */ Edge.prototype._resolveIds = function (graph) { if (typeof this._nodes[0] === "string") { this._nodes[0] = graph.getNode(this._nodes[0]); } if (typeof this._nodes[1] === "string") { this._nodes[1] = graph.getNode(this._nodes[1]); } }; return Edge; });
define(function () { "use strict"; var Edge = function (nodes) { this.setNodes(nodes); }; Edge.prototype.setNodes = function (nodes) { this._nodes = nodes; return this; }; Edge.prototype.getNodes = function () { return this._nodes; }; Edge.prototype.addTo = function (graph) { this._resolveIds(graph); graph.addEdge(this); return this; }; /** * Replace string IDs representing nodes with node references * @param {G.Graph} graph - Graph to retrieve node references from IDs * @returns {undefined} * @private */ Edge.prototype._resolveIds = function (graph) { if (typeof this._nodes[0] === "string") { this._nodes[0] = graph.getNode(this._nodes[0]); } if (typeof this._nodes[1] === "string") { this._nodes[1] = graph.getNode(this._nodes[1]); } }; return Edge; });
Reset incubation logger with deprecation logger
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.launcher.daemon.server.exec; import org.gradle.internal.deprecation.DeprecationLogger; import org.gradle.launcher.daemon.server.api.DaemonCommandAction; import org.gradle.launcher.daemon.server.api.DaemonCommandExecution; import org.gradle.util.IncubationLogger; public class ResetDeprecationLogger implements DaemonCommandAction { @Override public void execute(DaemonCommandExecution execution) { DeprecationLogger.reset(); IncubationLogger.reset(); execution.proceed(); } }
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.launcher.daemon.server.exec; import org.gradle.launcher.daemon.server.api.DaemonCommandAction; import org.gradle.launcher.daemon.server.api.DaemonCommandExecution; import org.gradle.internal.deprecation.DeprecationLogger; public class ResetDeprecationLogger implements DaemonCommandAction { @Override public void execute(DaemonCommandExecution execution) { DeprecationLogger.reset(); execution.proceed(); } }
Fix FC name pattern for NextSeq2000
"""Filesystem utilities.""" import contextlib import os import shutil RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{2,}_[AB0][A-Z\d\-]+$' @contextlib.contextmanager def chdir(new_dir): """Context manager to temporarily change to a new directory.""" cur_dir = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(cur_dir) def create_folder(target_folder): """ Ensure that a folder exists and create it if it doesn't, including any parent folders, as necessary. :param target_folder: the target folder :returns: True if the folder exists or was created, False if the folder does not exists and could not be created """ try: os.makedirs(target_folder) except OSError as e: pass return os.path.exists(target_folder) def touch(file): open(file, 'w').close() def do_symlink(src_file, dst_file): link_f = os.symlink if not os.path.isfile(dst_file): link_f(os.path.realpath(src_file), dst_file) def do_copy(src_path, dst_path): # copies folder structure and files (recursively) # if symlinks, will copy content, not the links # dst_path will be created, it must NOT exist shutil.copytree(src_path, dst_path)
"""Filesystem utilities.""" import contextlib import os import shutil RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{4}_[AB0][A-Z\d\-]+$' @contextlib.contextmanager def chdir(new_dir): """Context manager to temporarily change to a new directory.""" cur_dir = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(cur_dir) def create_folder(target_folder): """ Ensure that a folder exists and create it if it doesn't, including any parent folders, as necessary. :param target_folder: the target folder :returns: True if the folder exists or was created, False if the folder does not exists and could not be created """ try: os.makedirs(target_folder) except OSError as e: pass return os.path.exists(target_folder) def touch(file): open(file, 'w').close() def do_symlink(src_file, dst_file): link_f = os.symlink if not os.path.isfile(dst_file): link_f(os.path.realpath(src_file), dst_file) def do_copy(src_path, dst_path): # copies folder structure and files (recursively) # if symlinks, will copy content, not the links # dst_path will be created, it must NOT exist shutil.copytree(src_path, dst_path)