text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Increment version for deployment to PyPI
from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.8', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
Fix registering to the teleinfo service event.
var util = require('util'); var teleinfo = require('./teleinfo.js'); var request = require('request'); var trameEvents = teleinfo.teleinfo('/dev/ttyAMA0'); // Handle elec information trameEvents.on('onDecodedFrame', function (data) { sendData(data); }); /** * Sends the buffered data to the API and empty the buffer */ function sendData(data) { var options = { uri: 'http://theyetifield.tk/frames/', method: 'POST', json: { frames: [data] } }; request(options, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("Frames successfully sent."); } else { console.error('An error occurred when sending frames:', error); } }); }
var util = require('util'); var teleinfo = require('./teleinfo.js'); var request = require('request'); var trameEvents = teleinfo.teleinfo('/dev/ttyAMA0'); // Handle elec information trameEvents.on('tramedecodee', function (data) { sendData(data); }); /** * Sends the buffered data to the API and empty the buffer */ function sendData(data) { var options = { uri: 'http://theyetifield.tk/frames/', method: 'POST', json: { frames: [data] } }; request(options, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("Frames successfully sent."); } else { console.error('An error occurred when sending frames:', error); } }); }
Fix compatibility with Symfony 4.2
<?php declare(strict_types=1); namespace Arachne\Forms\Extension\Application\Type; use Arachne\Forms\Extension\Application\ApplicationRequestHandler; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Jáchym Toušek <enumag@gmail.com> */ class FormTypeApplicationExtension extends AbstractTypeExtension { /** * @var ApplicationRequestHandler */ private $requestHandler; public function __construct() { $this->requestHandler = new ApplicationRequestHandler(); } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setRequestHandler($this->requestHandler); } /** * {@inheritdoc} */ public static function getExtendedTypes(): iterable { yield FormType::class; } /** * @deprecated to be removed when Symfony 4.1 and older are no longer supported */ public function getExtendedType(): string { return FormType::class; } }
<?php declare(strict_types=1); namespace Arachne\Forms\Extension\Application\Type; use Arachne\Forms\Extension\Application\ApplicationRequestHandler; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Jáchym Toušek <enumag@gmail.com> */ class FormTypeApplicationExtension extends AbstractTypeExtension { /** * @var ApplicationRequestHandler */ private $requestHandler; public function __construct() { $this->requestHandler = new ApplicationRequestHandler(); } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setRequestHandler($this->requestHandler); } /** * {@inheritdoc} */ public function getExtendedType(): string { return FormType::class; } }
Add tests for positive and negative duration differences
package de.retest.recheck.printer.leaf; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.retest.ui.diff.DurationDifference; class DurationDifferencePrinterTest { DurationDifferencePrinter cut; @BeforeEach void setUp() { cut = new DurationDifferencePrinter(); } @Test void toString_should_handle_positive_difference() { final DurationDifference difference = mock( DurationDifference.class ); when( difference.getExpected() ).thenReturn( 0L ); when( difference.getActual() ).thenReturn( 1L ); final String string = cut.toString( difference ); assertThat( string ).isEqualTo( "0.001 s" ); } @Test void toString_should_handle_negative_difference() { final DurationDifference difference = mock( DurationDifference.class ); when( difference.getExpected() ).thenReturn( 1L ); when( difference.getActual() ).thenReturn( 0L ); final String string = cut.toString( difference ); assertThat( string ).isEqualTo( "-0.001 s" ); } @Test void toString_should_respect_indent() { final DurationDifference difference = mock( DurationDifference.class ); when( difference.getExpected() ).thenReturn( 0L ); when( difference.getActual() ).thenReturn( 1L ); final String string = cut.toString( difference, "____" ); assertThat( string ).startsWith( "____" ); } }
package de.retest.recheck.printer.leaf; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import de.retest.ui.diff.DurationDifference; class DurationDifferencePrinterTest { DurationDifferencePrinter cut; @BeforeEach void setUp() { cut = new DurationDifferencePrinter(); } @Test void toString_should_print_difference() { final DurationDifference difference = mock( DurationDifference.class ); when( difference.getExpected() ).thenReturn( 0L ); when( difference.getActual() ).thenReturn( 1L ); final String string = cut.toString( difference ); assertThat( string ).isEqualTo( "0.001 s" ); } @Test void toString_should_respect_indent() { final DurationDifference difference = mock( DurationDifference.class ); when( difference.getExpected() ).thenReturn( 0L ); when( difference.getActual() ).thenReturn( 1L ); final String string = cut.toString( difference, "____" ); assertThat( string ).startsWith( "____" ); } }
Set default linger to 1 second
import os import Pyro4 Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle') Pyro4.config.SERIALIZERS_ACCEPTED.add('dill') Pyro4.config.SERIALIZER = 'dill' Pyro4.config.THREADPOOL_SIZE = 16 Pyro4.config.SERVERTYPE = 'thread' Pyro4.config.REQUIRE_EXPOSE = False Pyro4.config.COMMTIMEOUT = 0. Pyro4.config.DETAILED_TRACEBACK = True os.environ['OSBRAIN_DEFAULT_TRANSPORT'] = 'ipc' os.environ['OSBRAIN_DEFAULT_SAFE'] = 'true' os.environ['OSBRAIN_DEFAULT_SERIALIZER'] = 'pickle' os.environ['OSBRAIN_DEFAULT_LINGER'] = '1' __version__ = '0.4.0' from .agent import Agent, AgentProcess, run_agent from .nameserver import run_nameserver from .proxy import Proxy, NSProxy from .address import SocketAddress, AgentAddress from .logging import Logger, run_logger
import os import Pyro4 Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle') Pyro4.config.SERIALIZERS_ACCEPTED.add('dill') Pyro4.config.SERIALIZER = 'dill' Pyro4.config.THREADPOOL_SIZE = 16 Pyro4.config.SERVERTYPE = 'thread' Pyro4.config.REQUIRE_EXPOSE = False Pyro4.config.COMMTIMEOUT = 0. Pyro4.config.DETAILED_TRACEBACK = True os.environ['OSBRAIN_DEFAULT_TRANSPORT'] = 'ipc' os.environ['OSBRAIN_DEFAULT_SAFE'] = 'true' os.environ['OSBRAIN_DEFAULT_SERIALIZER'] = 'pickle' os.environ['OSBRAIN_DEFAULT_LINGER'] = '-1' __version__ = '0.4.0' from .agent import Agent, AgentProcess, run_agent from .nameserver import run_nameserver from .proxy import Proxy, NSProxy from .address import SocketAddress, AgentAddress from .logging import Logger, run_logger
Use the right device orientation property in example
import Map from '../src/ol/Map.js'; import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import {toRadians} from '../src/ol/math.js'; import OSM from '../src/ol/source/OSM.js'; const view = new View({ center: [0, 0], zoom: 2 }); const map = new Map({ layers: [ new TileLayer({ source: new OSM() }) ], target: 'map', view: view }); function el(id) { return document.getElementById(id); } const gn = new GyroNorm(); gn.init().then(function() { gn.start(function(event) { const center = view.getCenter(); const resolution = view.getResolution(); const alpha = toRadians(event.do.alpha); const beta = toRadians(event.do.beta); const gamma = toRadians(event.do.gamma); el('alpha').innerText = alpha + ' [rad]'; el('beta').innerText = beta + ' [rad]'; el('gamma').innerText = gamma + ' [rad]'; center[0] -= resolution * gamma * 25; center[1] += resolution * beta * 25; view.setCenter(view.constrainCenter(center)); }); });
import Map from '../src/ol/Map.js'; import View from '../src/ol/View.js'; import TileLayer from '../src/ol/layer/Tile.js'; import {toRadians} from '../src/ol/math.js'; import OSM from '../src/ol/source/OSM.js'; const view = new View({ center: [0, 0], zoom: 2 }); const map = new Map({ layers: [ new TileLayer({ source: new OSM() }) ], target: 'map', view: view }); function el(id) { return document.getElementById(id); } const gn = new GyroNorm(); gn.init().then(function() { gn.start(function(event) { const center = view.getCenter(); const resolution = view.getResolution(); const alpha = toRadians(event.do.beta); const beta = toRadians(event.do.beta); const gamma = toRadians(event.do.gamma); el('alpha').innerText = alpha + ' [rad]'; el('beta').innerText = beta + ' [rad]'; el('gamma').innerText = gamma + ' [rad]'; center[0] -= resolution * gamma * 25; center[1] += resolution * beta * 25; view.setCenter(view.constrainCenter(center)); }); });
Allow to start infinite number of activities
package com.jraska.falcon.sample; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.view.Display; import android.view.Menu; import android.view.WindowManager; public class FloatingViewActivity extends SampleActivity { @Override protected void onCreate(Bundle savedInstanceState) { setupFloatingWindow(); super.onCreate(savedInstanceState); } private void setupFloatingWindow() { Point size = getSize(); WindowManager.LayoutParams params = getWindow().getAttributes(); params.width = size.x - 100; params.height = size.y / 2; params.alpha = 1; params.dimAmount = 0.4f; params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; getWindow().setAttributes(params); } @SuppressWarnings("deprecation") private Point getSize() { Point size = new Point(); Display defaultDisplay = getWindow().getWindowManager().getDefaultDisplay(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { defaultDisplay.getSize(size); } else { size.x = defaultDisplay.getWidth(); size.y = defaultDisplay.getHeight(); } return size; } static void start(Activity from) { Intent intent = new Intent(from, FloatingViewActivity.class); from.startActivity(intent); } }
package com.jraska.falcon.sample; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.os.Build; import android.os.Bundle; import android.view.Display; import android.view.Menu; import android.view.WindowManager; public class FloatingViewActivity extends SampleActivity { @Override protected void onCreate(Bundle savedInstanceState) { setupFloatingWindow(); super.onCreate(savedInstanceState); } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } private void setupFloatingWindow() { Point size = getSize(); WindowManager.LayoutParams params = getWindow().getAttributes(); params.width = size.x - 100; params.height = size.y / 2; params.alpha = 1; params.dimAmount = 0.4f; params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; getWindow().setAttributes(params); } @SuppressWarnings("deprecation") private Point getSize() { Point size = new Point(); Display defaultDisplay = getWindow().getWindowManager().getDefaultDisplay(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { defaultDisplay.getSize(size); } else { size.x = defaultDisplay.getWidth(); size.y = defaultDisplay.getHeight(); } return size; } static void start(Activity from) { Intent intent = new Intent(from, FloatingViewActivity.class); from.startActivity(intent); } }
Test Bubble Sort: Test for small arrays
/* eslint-env mocha */ const BubbleSort = require('../../../src').Algorithms.Sorting.BubbleSort; const assert = require('assert'); describe('BubbleSort', () => { it('should have no data when empty initialization', () => { const inst = new BubbleSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new BubbleSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); it('should sort 2 element array', () => { const inst = new BubbleSort([2, 1]); assert.equal(inst.size, 2); assert.deepEqual(inst.unsortedList, [2, 1]); assert.deepEqual(inst.sortedList, [1, 2]); assert.equal(inst.toString(), '1, 2'); }); it('should sort 1 element array', () => { const inst = new BubbleSort([1]); assert.equal(inst.size, 1); assert.deepEqual(inst.unsortedList, [1]); assert.deepEqual(inst.sortedList, [1]); assert.equal(inst.toString(), '1'); }); });
/* eslint-env mocha */ const BubbleSort = require('../../../src').Algorithms.Sorting.BubbleSort; const assert = require('assert'); describe('BubbleSort', () => { it('should have no data when empty initialization', () => { const inst = new BubbleSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new BubbleSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); });
Fix cell id vizzini test [#116491021] Signed-off-by: Nima Kaviani <0ebde517669f70c2aec92dc89d4950413b825ec0@us.ibm.com>
package vizzini_test import ( "strings" "code.cloudfoundry.org/bbs/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) var cell_z1_0 *models.CellPresence for _, cell := range cells { if strings.HasPrefix(cell.CellId, "cell_z1-0") { cell_z1_0 = cell break } } Expect(cell_z1_0).NotTo(BeNil()) Expect(cell_z1_0.CellId).To(HavePrefix("cell_z1-0")) Expect(cell_z1_0.Zone).To(Equal("z1")) Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0)) Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0)) }) })
package vizzini_test import ( "code.cloudfoundry.org/bbs/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) var cell_z1_0 *models.CellPresence for _, cell := range cells { if cell.CellId == "cell_z1-0" { cell_z1_0 = cell break } } Expect(cell_z1_0).NotTo(BeNil()) Expect(cell_z1_0.CellId).To(Equal("cell_z1-0")) Expect(cell_z1_0.Zone).To(Equal("z1")) Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0)) Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0)) }) })
Print localhost instead of 0.0.0.0 as latter doesn't work on Windows
#!/usr/bin/env node const ArgumentParser = require('argparse').ArgumentParser const opn = require('opn') const packageJson = require('../package.json') const { createServer } = require('../lib/backend') if (process.env.NODE_ENV === 'production') { console.error(clc.red('Do not run this in production!')) process.exit(1) } const parser = new ArgumentParser({ description: packageJson.description, version: packageJson.version, }) parser.addArgument(['-o', '--open'], { action: 'storeTrue', help: 'Open server URL in default browser on start', }) parser.addArgument(['-p', '--port'], { type: 'int', defaultValue: 8001, help: 'Port to run on (default: 8001)', }) const args = parser.parseArgs() const app = createServer(); const port = process.env.PORT || args.port const server = app.listen(port); server.on('listening', () => { const address = server.address(); const url = `http://localhost:${address.port}`; console.log(` dynamodb-admin listening on ${url} (alternatively http://0.0.0.0:${address.port})`); if (args.open) { opn(url) } });
#!/usr/bin/env node const ArgumentParser = require('argparse').ArgumentParser const opn = require('opn') const packageJson = require('../package.json') const { createServer } = require('../lib/backend') if (process.env.NODE_ENV === 'production') { console.error(clc.red('Do not run this in production!')) process.exit(1) } const parser = new ArgumentParser({ description: packageJson.description, version: packageJson.version, }) parser.addArgument(['-o', '--open'], { action: 'storeTrue', help: 'Open server URL in default browser on start', }) parser.addArgument(['-p', '--port'], { type: 'int', defaultValue: 8001, help: 'Port to run on (default: 8001)', }) const args = parser.parseArgs() const app = createServer(); const port = process.env.PORT || args.port const server = app.listen(port); server.on('listening', () => { const address = server.address(); const url = `http://0.0.0.0:${address.port}`; console.log(` dynamodb-admin listening on ${url}`); if (args.open) { opn(url) } });
Add more information that will be saved upon receiving a /WHO reply
package heufybot.core; public class User { private String nickname; private String login; private String hostmask; private String realname; private boolean isOper; public User(String nickname, String login, String hostmask) { this.nickname = nickname; this.login = login; this.hostmask = hostmask; } public User(String nickname) { this.nickname = nickname; } public String getNickname() { return nickname; } public String getLogin() { return login; } public String getHostmask() { return hostmask; } public void setNickname(String nickname) { this.nickname = nickname; } public void setLogin(String login) { this.login = login; } public void setHostmask(String hostmask) { this.hostmask = hostmask; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public boolean isOper() { return isOper; } public void setOper(boolean isOper) { this.isOper = isOper; } }
package heufybot.core; public class User { private String nickname; private String login; private String hostmask; public User(String nickname, String login, String hostmask) { this.nickname = nickname; this.login = login; this.hostmask = hostmask; } public User(String nickname) { this.nickname = nickname; } public String getNickname() { return nickname; } public String getLogin() { return login; } public String getHostmask() { return hostmask; } public void setNickname(String nickname) { this.nickname = nickname; } public void setLogin(String login) { this.login = login; } public void setHostmask(String hostmask) { this.hostmask = hostmask; } }
Remove decode from block branches check It’s now done by `bash()`.
# # # # # # # # # # # # # # # CAPTAINHOOK IDENTIFIER # # # # # # # # # # # # # # # import argparse from .utils import bash CHECK_NAME = 'block_branch' def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in argos.branches: return ("Branch '{0}' is blocked from being " "committed to.".format(current_branch)) def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('branches', metavar='B', nargs='+', help='a branch to block commits to') return parser
# # # # # # # # # # # # # # # CAPTAINHOOK IDENTIFIER # # # # # # # # # # # # # # # import argparse from .utils import bash CHECK_NAME = 'block_branch' def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value().decode('utf-8') current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in argos.branches: return ("Branch '{0}' is blocked from being " "committed to.".format(current_branch)) def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('branches', metavar='B', nargs='+', help='a branch to block commits to') return parser
Update Sami theme as default.
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, array( 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, [ 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
Insert new access token for testing.
package com.uwetrottmann.getglue; import junit.framework.TestCase; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import java.io.IOException; public abstract class BaseTestCase extends TestCase { protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3"; protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4"; private static final String TEMPORARY_ACCESS_TOKEN = "57EDD19812FCD9BFD12589AF24B9D2"; /* Expires April 23, 2014, 3:49 a.m. */ protected static final String REDIRECT_URI = "http://localhost"; private final GetGlue mManager = new GetGlue(); @Override protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException { getManager().setIsDebug(true); getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN); } protected final GetGlue getManager() { return mManager; } }
package com.uwetrottmann.getglue; import junit.framework.TestCase; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import java.io.IOException; public abstract class BaseTestCase extends TestCase { protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3"; protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4"; private static final String TEMPORARY_ACCESS_TOKEN = "B341108A36B7499839648979D4739E"; /* Expires Feb. 20, 2014, 10:20 a.m. */ protected static final String REDIRECT_URI = "http://localhost"; private final GetGlue mManager = new GetGlue(); @Override protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException { getManager().setIsDebug(true); getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN); } protected final GetGlue getManager() { return mManager; } }
Fix function signature to match base one
<?php /** * @package plugins.metadata * @subpackage model */ class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer { public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage) { /** @var MetadataProfileField $profileField */ $subMetadataProfileId = $profileField->getRelatedMetadataProfileId(); $subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId); if (!$subMetadataProfile) { $errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found'; return false; } $subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds); if (count($subMetadataObjects) != count($objectIds)) { $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId; return false; } return true; } public static function getEntry($objectId) { return null; } public static function validateMetadataObjectAccess($objectId, $objectType) { return true; } }
<?php /** * @package plugins.metadata * @subpackage model */ class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer { public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage) { /** @var MetadataProfileField $profileField */ $subMetadataProfileId = $profileField->getRelatedMetadataProfileId(); $subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId); if (!$subMetadataProfile) { $errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found'; return false; } $subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds); if (count($subMetadataObjects) != count($objectIds)) { $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId; return false; } return true; } public static function getEntry($objectId) { return null; } public static function validateMetadataObjectAccess(metadata $dbMetadata) { return true; } }
Increment version since the change from M2Crypto to cryptography is fairly significant
# Copyright (c) 2013 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. __version__ = "3.3.0-dev"
# Copyright (c) 2013 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. __version__ = "3.2.1-dev"
Fix to local data filepath
import os import urllib from xml.etree import ElementTree as ET from astropy.tests.helper import pytest from ...utils.testing_tools import MockResponse from ... import open_exoplanet_catalogue as oec @pytest.fixture(autouse=True) def patch_urlopen(request): mp = request.getfuncargvalue("monkeypatch") mp.setattr(urllib, 'urlopen', get_mock_return) return mp def get_mock_return(url, params=None, timeout=10,**kwargs): # dummy function to replace urllib get functionality # function returns what the http request would but with local data content = open('data/systems.xml.gz', "r").read() return MockResponse(content, **kwargs) # get file path of a static data file for testing def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'data') return os.path.join(data_dir, filename) def test_function(patch_urlopen): cata = oec.get_catalogue() assert len(cata.findall('.//planet')) > 0 kepler67b = cata.find(".//planet[name='Kepler-67 b']") assert kepler67b.findtext('name') == "Kepler-67 b" assert kepler67b.findtext('discoverymethod') == "transit" kepler67 = cata.find(".//system[name='Kepler-67']") assert kepler67.findvalue('distance') == 1107
import os import urllib from xml.etree import ElementTree as ET from astropy.tests.helper import pytest from ...utils.testing_tools import MockResponse from ... import open_exoplanet_catalogue as oec @pytest.fixture(autouse=True) def patch_urlopen(request): mp = request.getfuncargvalue("monkeypatch") mp.setattr(urllib, 'urlopen', get_mock_return) return mp def get_mock_return(url, params=None, timeout=10,**kwargs): # dummy function to replace urllib get functionality # function returns what the http request would but with local data content = open(data_path('systems.xml.gz'), "r").read() return MockResponse(content, **kwargs) # get file path of a static data file for testing def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'data') return os.path.join(data_dir, filename) def test_function(patch_urlopen): cata = oec.get_catalogue() assert len(cata.findall('.//planet')) > 0 kepler67b = cata.find(".//planet[name='Kepler-67 b']") assert kepler67b.findtext('name') == "Kepler-67 b" assert kepler67b.findtext('discoverymethod') == "transit" kepler67 = cata.find(".//system[name='Kepler-67']") assert kepler67.findvalue('distance') == 1107
Initialize Tcl/Tk interpreter only when actually running benchmarks.
package gothic import ( "testing" "time" ) var ir *Interpreter func irinit(b *testing.B) { if ir == nil { ir = NewInterpreter(nil) time.Sleep(200 * time.Millisecond) } b.ResetTimer() } func BenchmarkTcl(b *testing.B) { irinit(b) ir.Set("N", b.N) ir.Eval(` for {set i 1} {$i < $N} {incr i} { set x 10 } `) } func BenchmarkForeignGo(b *testing.B) { irinit(b) for i := 0; i < b.N; i++ { ir.Eval(`set x 10`) } } func BenchmarkNativeGo(b *testing.B) { irinit(b) ir.UnregisterCommand("test") ir.RegisterCommand("test", func() { for i := 0; i < b.N; i++ { ir.Eval(`set x 10`) } }) ir.Eval(`test`) }
package gothic import ( "testing" "time" ) var ir *Interpreter func init() { ir = NewInterpreter(nil) time.Sleep(200 * time.Millisecond) } func BenchmarkTcl(b *testing.B) { ir.Set("N", b.N) ir.Eval(` for {set i 1} {$i < $N} {incr i} { set x 10 } `) } func BenchmarkForeignGo(b *testing.B) { for i := 0; i < b.N; i++ { ir.Eval(`set x 10`) } } func BenchmarkNativeGo(b *testing.B) { ir.UnregisterCommand("test") ir.RegisterCommand("test", func() { for i := 0; i < b.N; i++ { ir.Eval(`set x 10`) } }) ir.Eval(`test`) }
Add colour to gulp output
var gulp = require('gulp'); var webpack = require('webpack'); var clientConfig = require('./config/webpack.prod.client.js') var serverConfig = require('./config/webpack.prod.server.js') gulp.task('bundle-client', function(done) { webpack( clientConfig ).run(onBundle(done)) }); gulp.task('bundle-server', function(done) { webpack( serverConfig ).run(onBundle(done)) }); gulp.task('move-assets', function() { gulp.src('./src/assets/**/*', {base: './src'}).pipe(gulp.dest('./app/')) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); gulp.task('build', ['bundle', 'move-assets']) // TODO - elctron build function onBundle(done) { return function(err, stats) { if (err) console.log('Error', err); else console.log(stats.toString({chunks: false, colors: true})); done() } }
var gulp = require('gulp'); var webpack = require('webpack'); var clientConfig = require('./config/webpack.prod.client.js') var serverConfig = require('./config/webpack.prod.server.js') gulp.task('bundle-client', function(done) { webpack( clientConfig ).run(onBundle(done)) }); gulp.task('bundle-server', function(done) { webpack( serverConfig ).run(onBundle(done)) }); gulp.task('move-assets', function() { gulp.src('./src/assets/**/*', {base: './src'}).pipe(gulp.dest('./app/')) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); gulp.task('build', ['bundle', 'move-assets']) // TODO - elctron build function onBundle(done) { return function(err, stats) { if (err) console.log('Error', err); else console.log(stats.toString()); done() } }
Fix for broken build on PHP < 5.6
<?php namespace GraphQL\Error; final class Warning { const NAME_WARNING = 1; const ASSIGN_WARNING = 2; const CONFIG_WARNING = 4; const ALL = 7; static $enableWarnings = self::ALL; static $warned = []; static function suppress($suppress = true) { if (true === $suppress) { self::$enableWarnings = 0; } else if (false === $suppress) { self::$enableWarnings = self::ALL; } else { $suppress = (int) $suppress; self::$enableWarnings &= ~$suppress; } } static function warnOnce($errorMessage, $warningId) { if ((self::$enableWarnings & $warningId) > 0 && !isset(self::$warned[$warningId])) { self::$warned[$warningId] = true; trigger_error($errorMessage, E_USER_WARNING); } } static function warn($errorMessage, $warningId) { if ((self::$enableWarnings & $warningId) > 0) { trigger_error($errorMessage, E_USER_WARNING); } } }
<?php namespace GraphQL\Error; final class Warning { const NAME_WARNING = 1; const ASSIGN_WARNING = 2; const CONFIG_WARNING = 4; const ALL = self::NAME_WARNING | self::ASSIGN_WARNING | self::CONFIG_WARNING; static $enableWarnings = self::ALL; static $warned = []; static function suppress($suppress = true) { if (true === $suppress) { self::$enableWarnings = 0; } else if (false === $suppress) { self::$enableWarnings = self::ALL; } else { $suppress = (int) $suppress; self::$enableWarnings &= ~$suppress; } } static function warnOnce($errorMessage, $warningId) { if ((self::$enableWarnings & $warningId) > 0 && !isset(self::$warned[$warningId])) { self::$warned[$warningId] = true; trigger_error($errorMessage, E_USER_WARNING); } } static function warn($errorMessage, $warningId) { if ((self::$enableWarnings & $warningId) > 0) { trigger_error($errorMessage, E_USER_WARNING); } } }
Remove syscall package in favor of unix package
// Copyright 2013-2017 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // mkfifo creates a named pipe. // // Synopsis: // mkfifo [OPTIONS] NAME... // // Options: // -m: mode (default 0600) // package main import ( "flag" "log" "os" "golang.org/x/sys/unix" ) const ( defaultMode = 0660 | unix.S_IFIFO cmd = "mkfifo [-m] NAME..." ) var mode = flag.Int("mode", defaultMode, "Mode to create fifo") func init() { defUsage := flag.Usage flag.Usage = func() { os.Args[0] = cmd defUsage() } flag.Parse() } func main() { flag.Parse() if flag.NArg() < 1 { log.Fatal("please provide a path, or multiple, to create a fifo") } for _, path := range flag.Args() { if err := unix.Mkfifo(path, uint32(*mode)); err != nil { log.Fatalf("Error while creating fifo, %v", err) } } }
// Copyright 2013-2017 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // mkfifo creates a named pipe. // // Synopsis: // mkfifo [OPTIONS] NAME... // // Options: // -m: mode (default 0600) // package main import ( "flag" "log" "os" "syscall" "golang.org/x/sys/unix" ) const ( defaultMode = 0660 | unix.S_IFIFO cmd = "mkfifo [-m] NAME..." ) var mode = flag.Int("mode", defaultMode, "Mode to create fifo") func init() { defUsage := flag.Usage flag.Usage = func() { os.Args[0] = cmd defUsage() } flag.Parse() } func main() { flag.Parse() if flag.NArg() < 1 { log.Fatal("please provide a path, or multiple, to create a fifo") } for _, path := range flag.Args() { if err := syscall.Mkfifo(path, uint32(*mode)); err != nil { log.Fatalf("Error while creating fifo, %v", err) } } }
Return static response in doGet()
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that returns comments from and adds comments to Datastore. */ @WebServlet("/search") public class SearchServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("plain/text"); response.getWriter().println("Hello world"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that returns comments from and adds comments to Datastore. */ @WebServlet("/search") public class SearchServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { } }
Return false on click event
import Ember from 'ember'; const { Component } = Ember; /** * @module * @augments ember/Component */ export default Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes /** @type {String[]} */ attributeBindings: [ 'href' ], /** @type {String[]} */ classNameBindings: [ 'active:ef-active', 'disabled:ef-disabled' ], /** @type {String[]} */ classNames: [ 'ef-nav-list-link' ], /** @type {String} */ tagName: 'a', // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events /** * Click event handler * * Execute bound action * * @function * @param {Event} event - The raw click event * @returns {Boolean} false */ click() { this.get( 'onClick' )(); return false; }, // ------------------------------------------------------------------------- // Properties /** * Whether represents an active link * * @type {Boolean} */ active: false, /** * Whether represents a disabled link * * @type {Boolean} */ disabled: false, /** * `href` attribute value * * @type {String} */ href: '#' // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods });
import Ember from 'ember'; const { Component } = Ember; /** * @module * @augments ember/Component */ export default Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes /** @type {String[]} */ attributeBindings: [ 'href' ], /** @type {String[]} */ classNameBindings: [ 'active:ef-active', 'disabled:ef-disabled' ], /** @type {String[]} */ classNames: [ 'ef-nav-list-link' ], /** @type {String} */ tagName: 'a', // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events /** * Click event handler * * Execute bound action * * @function * @param {Event} event - The raw click event * @returns {undefined} */ click() { this.get( 'onClick' )(); }, // ------------------------------------------------------------------------- // Properties /** * Whether represents an active link * * @type {Boolean} */ active: false, /** * Whether represents a disabled link * * @type {Boolean} */ disabled: false, /** * `href` attribute value * * @type {String} */ href: '#' // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods });
Handle exception in nearestPackageRoot test
var nearestPackageRoot = require('../../lib/resolver/nearest-package-root'); var assert = require('assert'); var path = require('path'); var fixturesPath = path.resolve.bind(null, __dirname, '..', 'fixtures', 'nearest-package-root-test' ) describe('nearestPackageRoot', function () { it('finds the nearest module folder based on the import origin', function (done) { var sourcePath = fixturesPath('index.scss'); nearestPackageRoot('test-module', sourcePath).then(function (result) { assert.equal(result, fixturesPath('node_modules', 'test-module')); }) .then(done) .catch(done); }); it('works with nested dependencies', function (done) { var sourcePath = fixturesPath('node_modules', 'test-module', 'index.scss'); nearestPackageRoot('nested-module', sourcePath).then(function (result) { assert.equal(result, fixturesPath('node_modules', 'test-module', 'node_modules', 'nested-module')); }) .then(done) .catch(done); }); });
var nearestPackageRoot = require('../../lib/resolver/nearest-package-root'); var assert = require('assert'); var path = require('path'); var fixturesPath = path.resolve.bind(null, __dirname, '..', 'fixtures', 'nearest-package-root-test' ) describe('nearestPackageRoot', function () { it('finds the nearest module folder based on the import origin', function (done) { var sourcePath = fixturesPath('index.scss'); nearestPackageRoot('test-module', sourcePath).then(function (result) { assert.equal(result, fixturesPath('node_modules', 'test-module')); done(); }); }); it('works with nested dependencies', function (done) { var sourcePath = fixturesPath('node_modules', 'test-module', 'index.scss'); nearestPackageRoot('nested-module', sourcePath).then(function (result) { assert.equal(result, fixturesPath('node_modules', 'test-module', 'node_modules', 'nested-module')); done(); }); }); });
Fix parameters on test nodes
""" Nodetree test nodes. """ from __future__ import absolute_import import types from . import node class Number(node.Node): """A number constant.""" intypes = [] outtype = types.IntType parameters = [ dict(name="num", value=0), ] def _eval(self): return self._params.get("num") class Arithmetic(node.Node): """Operate on two numbers""" intypes = [types.IntType, types.IntType] outtype = types.IntType parameters = [ dict(name="operator", value="+", choices=[ "+", "-", "*", "/", ]), ] def _eval(self): op = self._params.get("operator") lhs = self.eval_input(0) rhs = self.eval_input(1) if op == "+": return lhs + rhs elif op == "-": return lhs - rhs elif op == "*": return lhs * rhs elif op == "/": return lhs / rhs
""" Nodetree test nodes. """ from __future__ import absolute_import import types from . import node class Number(node.Node): """A number constant.""" intypes = [] outtype = types.IntType _parameters = [ dict(name="num", value=0), ] def _eval(self): return self._params.get("num") class Arithmetic(node.Node): """Operate on two numbers""" intypes = [types.IntType, types.IntType] outtype = types.IntType _parameters = [ dict(name="operator", value="+", choices=[ "+", "-", "*", "/", ]), ] def _eval(self): op = self._params.get("operator") lhs = self.eval_input(0) rhs = self.eval_input(1) if op == "+": return lhs + rhs elif op == "-": return lhs - rhs elif op == "*": return lhs * rhs elif op == "/": return lhs / rhs
Add six as a dependency.
#!/usr/bin/env python import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '1.2' distutils.core.setup( name='linersock', version=version, author='Kale Kundert and Alex Mitchell', url='https://github.com/kxgames/linersock', download_url='https://github.com/kxgames/linersock/tarball/'+version, license='LICENSE.txt', description="A thin layer between you and your sockets that helps prevent chafing.", long_description=open('README.rst').read(), keywords=['nonblocking', 'socket', 'wrapper', 'library'], packages=['linersock'], install_requires=[ 'six', ], )
#!/usr/bin/env python import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '1.1' distutils.core.setup( name='linersock', version=version, author='Kale Kundert and Alex Mitchell', packages=['linersock'], url='https://github.com/kxgames/linersock', download_url='https://github.com/kxgames/linersock/tarball/'+version, license='LICENSE.txt', description="A thin layer between you and your sockets that helps prevent chafing.", long_description=open('README.rst').read(), keywords=['nonblocking', 'socket', 'wrapper', 'library'])
bootstrap: Add support for multiple random key encodings Added support for base64 and base64safe (as well as the existing hex). Signed-off-by: Jonathan Rudenberg <3692bfa45759a67d83aedf0045f6cb635a966abf@titanous.com>
package bootstrap import ( "encoding/base64" "fmt" "github.com/flynn/flynn/pkg/random" ) type GenRandomAction struct { ID string `json:"id"` Length int `json:"length"` Data string `json:"data"` Encoding string `json:"encoding"` ControllerKey bool `json:"controller_key"` } func init() { Register("gen-random", &GenRandomAction{}) } type RandomData struct { Data string `json:"data"` } func (d *RandomData) String() string { return d.Data } func (a *GenRandomAction) Run(s *State) error { if a.Length == 0 { a.Length = 16 } data := interpolate(s, a.Data) if data == "" { switch a.Encoding { case "", "hex": data = random.Hex(a.Length) case "base64": data = base64.StdEncoding.EncodeToString(random.Bytes(a.Length)) case "base64safe": data = random.Base64(a.Length) default: return fmt.Errorf("bootstrap: unknown random type: %q", a.Encoding) } } s.StepData[a.ID] = &RandomData{Data: data} if a.ControllerKey { s.SetControllerKey(data) } return nil }
package bootstrap import "github.com/flynn/flynn/pkg/random" type GenRandomAction struct { ID string `json:"id"` Length int `json:"length"` Data string `json:"data"` ControllerKey bool `json:"controller_key"` } func init() { Register("gen-random", &GenRandomAction{}) } type RandomData struct { Data string `json:"data"` } func (d *RandomData) String() string { return d.Data } func (a *GenRandomAction) Run(s *State) error { if a.Length == 0 { a.Length = 16 } data := interpolate(s, a.Data) if data == "" { data = random.Hex(a.Length) } s.StepData[a.ID] = &RandomData{Data: data} if a.ControllerKey { s.SetControllerKey(data) } return nil }
Add try catch and log
<?php namespace App\Http\Controllers; use App\Models\Check; use Barryvdh\Snappy\Facades\SnappyPdf; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\URL; class EvaluationController extends Controller { public function index(Check $check) { return view('evaluation.show', ['check' => $check]); } public function download(Check $check) { $css = url(mix('/css/app.css')); try { $pdf = SnappyPdf::loadView('evaluation.pdf', ['check' => $check, 'css' => $css])->setOrientation('landscape'); $name = str_replace(' ', '_', $check->name) . "_" . Carbon::now()->format('d_m_Y'); return $pdf->download($name . '.pdf'); } catch (\Exception $exception) { Log::error($exception); session()->flash('status', ['message' => 'Das PDF kann gerade nicht erstellt werden', 'level' => 'error']); return redirect()->back(); } } }
<?php namespace App\Http\Controllers; use App\Models\Check; use Barryvdh\Snappy\Facades\SnappyPdf; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\URL; class EvaluationController extends Controller { public function index(Check $check) { return view('evaluation.show', ['check' => $check]); } public function download(Check $check) { $css = url(mix('/css/app.css')); $pdf = SnappyPdf::loadView('evaluation.pdf', ['check' => $check, 'css' => $css])->setOrientation('landscape'); $name = str_replace(' ', '_', $check->name) . "_" . Carbon::now()->format('d_m_Y'); return $pdf->download($name . '.pdf'); } }
Remove hardcoded sauce connect port
import SauceConnectLauncher from 'sauce-connect-launcher' class SauceLaunchService { /** * modify config and launch sauce connect */ onPrepare (config) { if (!config.sauceConnect) { return } this.sauceConnectOpts = Object.assign({ username: config.user, accessKey: config.key }, config.sauceConnectOpts) config.host = 'localhost' config.port = this.sauceConnectOpts.port || 4445 return new Promise((resolve, reject) => SauceConnectLauncher(this.sauceConnectOpts, (err, sauceConnectProcess) => { if (err) { return reject(err) } this.sauceConnectProcess = sauceConnectProcess resolve() })) } /** * shut down sauce connect */ onComplete () { if (!this.sauceConnectProcess) { return } return new Promise((r) => this.sauceConnectProcess.close(r)) } } export default SauceLaunchService
import SauceConnectLauncher from 'sauce-connect-launcher' class SauceLaunchService { /** * modify config and launch sauce connect */ onPrepare (config) { if (!config.sauceConnect) { return } config.host = 'localhost' config.port = 4445 this.sauceConnectOpts = Object.assign({ username: config.user, accessKey: config.key }, config.sauceConnectOpts) return new Promise((resolve, reject) => SauceConnectLauncher(this.sauceConnectOpts, (err, sauceConnectProcess) => { if (err) { return reject(err) } this.sauceConnectProcess = sauceConnectProcess resolve() })) } /** * shut down sauce connect */ onComplete () { if (!this.sauceConnectProcess) { return } return new Promise((r) => this.sauceConnectProcess.close(r)) } } export default SauceLaunchService
Modify env var before request in server test
package clienttest import ( check "gopkg.in/check.v1" "github.com/radanalyticsio/oshinko-cli/rest/version" "github.com/radanalyticsio/oshinko-cli/rest/helpers/info" "os" ) func (s *OshinkoRestTestSuite) TestServerInfo(c *check.C) { val := os.Getenv("OSHINKO_CLUSTER_IMAGE") os.Setenv("OSHINKO_CLUSTER_IMAGE", "") resp, _ := s.cli.Server.GetServerInfo(nil) expectedName := version.GetAppName() expectedVersion := version.GetVersion() expectedImage := info.GetSparkImage() observedName := resp.Payload.Application.Name observedVersion := resp.Payload.Application.Version observedImage := resp.Payload.Application.DefaultClusterImage c.Assert(*observedName, check.Equals, expectedName) c.Assert(*observedVersion, check.Equals, expectedVersion) c.Assert(*observedImage, check.Equals, expectedImage) os.Setenv("OSHINKO_CLUSTER_IMAGE", "bobby") expectedImage = "bobby" resp, _ = s.cli.Server.GetServerInfo(nil) observedImage = resp.Payload.Application.DefaultClusterImage c.Assert(*observedImage, check.Equals, expectedImage) os.Setenv("OSHINKO_CLUSTER_IMAGE", val) }
package clienttest import ( check "gopkg.in/check.v1" "github.com/radanalyticsio/oshinko-cli/rest/version" "github.com/radanalyticsio/oshinko-cli/rest/helpers/info" "os" ) func (s *OshinkoRestTestSuite) TestServerInfo(c *check.C) { resp, _ := s.cli.Server.GetServerInfo(nil) val := os.Getenv("OSHINKO_CLUSTER_IMAGE") os.Setenv("OSHINKO_CLUSTER_IMAGE", "") expectedName := version.GetAppName() expectedVersion := version.GetVersion() expectedImage := info.GetSparkImage() observedName := resp.Payload.Application.Name observedVersion := resp.Payload.Application.Version observedImage := resp.Payload.Application.DefaultClusterImage c.Assert(*observedName, check.Equals, expectedName) c.Assert(*observedVersion, check.Equals, expectedVersion) c.Assert(*observedImage, check.Equals, expectedImage) os.Setenv("OSHINKO_CLUSTER_IMAGE", "bobby") expectedImage = "bobby" resp, _ = s.cli.Server.GetServerInfo(nil) observedImage = resp.Payload.Application.DefaultClusterImage c.Assert(*observedImage, check.Equals, expectedImage) os.Setenv("OSHINKO_CLUSTER_IMAGE", val) }
Add greeting line about chaos text.
package net.silentchaos512.gems.lib; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.lib.util.PlayerHelper; public class Greetings { public static final String PREFIX = "misc.silentgems:alpha"; public static void greetPlayer(EntityPlayer player) { // Reset the random object, because it seems to yield the same value each time. Huh? SilentGems.instance.random.setSeed(System.currentTimeMillis()); List<String> list = SilentGems.instance.localizationHelper.getDescriptionLines(PREFIX); String msg = SilentGems.instance.localizationHelper.getLocalizedString(PREFIX + "Prefix") + " "; int index = SilentGems.instance.random.nextInt(list.size()); // SilentGems.instance.logHelper.debug(list.size(), index); msg += list.get(index); PlayerHelper.addChatMessage(player, TextFormatting.RED + msg); // TODO: Remove this later. PlayerHelper.addChatMessage(player, "Yes, the numbers in the upper-left are my fault. I'm working on it."); } }
package net.silentchaos512.gems.lib; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.silentchaos512.gems.SilentGems; public class Greetings { public static final String PREFIX = "misc.silentgems:alpha"; public static void greetPlayer(EntityPlayer player) { // Reset the random object, because it seems to yield the same value each time. Huh? SilentGems.instance.random.setSeed(System.currentTimeMillis()); List<String> list = SilentGems.instance.localizationHelper.getDescriptionLines(PREFIX); String msg = SilentGems.instance.localizationHelper.getLocalizedString(PREFIX + "Prefix") + " "; int index = SilentGems.instance.random.nextInt(list.size()); // SilentGems.instance.logHelper.debug(list.size(), index); msg += list.get(index); player.addChatMessage(new TextComponentString(TextFormatting.RED + msg)); } }
:new: Add resolve.root support to getRootDirectory helper in motion-webpack-npm
/* @flow */ const MODULE_EXTRACTION_REGEX = /^(\w[^\/\\]+)/ export function extractModuleName(moduleName: string): ?string { if (moduleName.indexOf(' ') !== -1) { return null } const matches = MODULE_EXTRACTION_REGEX.exec(moduleName) if (matches) { return matches[1] } return null } export function getRootDirectory(compiler: Object): string { const options = compiler.options const rootDirectory = options.resolve && options.resolve.root if (rootDirectory) { return Array.isArray(rootDirectory) ? rootDirectory[0] : rootDirectory } return process.cwd() } export function getModuleName(moduleName: string, loader: boolean): string { if (loader && !moduleName.match(/\-loader$/)) { moduleName += '-loader' } return moduleName } export function isBuiltin(moduleName: string): boolean { try { return require.resolve(moduleName) === moduleName } catch (_) { return false } }
/* @flow */ const MODULE_EXTRACTION_REGEX = /^(\w[^\/\\]+)/ export function extractModuleName(moduleName: string): ?string { if (moduleName.indexOf(' ') !== -1) { return null } const matches = MODULE_EXTRACTION_REGEX.exec(moduleName) if (matches) { return matches[1] } return null } export function getRootDirectory(): string { // TODO: Make this actually work // NOTE: `npm-install-webpack-plugin` does the same by the way return process.cwd() } export function getModuleName(moduleName: string, loader: boolean): string { if (loader && !moduleName.match(/\-loader$/)) { moduleName += '-loader' } return moduleName } export function isBuiltin(moduleName: string): boolean { try { return require.resolve(moduleName) === moduleName } catch (_) { return false } }
fix(docs): Set GDPR cookie expiration date
import { Cookies, Notify, openURL } from 'quasar' if (Cookies.has('gdpr') !== true) { Notify.create({ message: `Our third-party tools use cookies, which are necessary for its functioning and required to achieve the purposes illustrated in the cookie policy.`, multiline: true, classes: 'doc-gdpr', timeout: 0, position: 'bottom-right', actions: [ { label: 'Accept', color: 'yellow', handler () { Cookies.set('gdpr', true, { expires: 5 * 365 }) } }, { label: 'Learn more', color: 'grey', noDismiss: true, handler () { openURL('https://www.iubenda.com/privacy-policy/40685560/cookie-policy?an=no&s_ck=false&newmarkup=yes') } } ] }) }
import { Cookies, Notify, openURL } from 'quasar' if (Cookies.has('gdpr') !== true) { Notify.create({ message: `Our third-party tools use cookies, which are necessary for its functioning and required to achieve the purposes illustrated in the cookie policy.`, multiline: true, classes: 'doc-gdpr', timeout: 0, position: 'bottom-right', actions: [ { label: 'Accept', color: 'yellow', handler () { Cookies.set('gdpr', true) } }, { label: 'Learn more', color: 'grey', noDismiss: true, handler () { openURL('https://www.iubenda.com/privacy-policy/40685560/cookie-policy?an=no&s_ck=false&newmarkup=yes') } } ] }) }
Add specialization call to map key lookup.
package org.metaborg.meta.interpreter.framework; import com.github.krukow.clj_ds.PersistentMap; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; public class MapUtils { @TruffleBoundary public static <K, V> PersistentMap<K, V> plus(PersistentMap<K, V> one, PersistentMap<K, V> other) { PersistentMap<K, V> nmap = one; for (K key : other.keySet()) { nmap = nmap.plus(key, other.get(key)); } return nmap; } @TruffleBoundary @SuppressWarnings("unchecked") public static <K, V> PersistentMap<K, V> add(PersistentMap<K, V> map, K key, V val) { return map.plus( (K) (key instanceof IGenericNode ? ((IGenericNode) key) .specialize() : key), (V) (val instanceof IGenericNode ? ((IGenericNode) val) .specialize() : val)); } @TruffleBoundary public static <K, V> V get(PersistentMap<K, V> map, K key) { return map.get(key instanceof IGenericNode ? ((IGenericNode) key) .specialize() : key); } }
package org.metaborg.meta.interpreter.framework; import com.github.krukow.clj_ds.PersistentMap; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; public class MapUtils { @TruffleBoundary public static <K, V> PersistentMap<K, V> plus(PersistentMap<K, V> one, PersistentMap<K, V> other) { PersistentMap<K, V> nmap = one; for (K key : other.keySet()) { nmap = nmap.plus(key, other.get(key)); } return nmap; } @TruffleBoundary @SuppressWarnings("unchecked") public static <K, V> PersistentMap<K, V> add(PersistentMap<K, V> map, K key, V val) { return map.plus( (K) (key instanceof IGenericNode ? ((IGenericNode) key) .specialize() : key), (V) (val instanceof IGenericNode ? ((IGenericNode) val) .specialize() : val)); } @TruffleBoundary public static <K, V> V get(PersistentMap<K, V> map, K key) { return map.get(key); } }
Set title only if data is empty
<?php namespace kato\behaviors; use yii\base\Behavior; use yii\db\ActiveRecord; class DefaultTitle extends Behavior { /** * @var string attribute */ public $attribute = "title"; public $defaultPrefix = 'New'; /** * @inheritdoc */ public function events() { return [ActiveRecord::EVENT_BEFORE_INSERT => 'setDefaultValue']; } public function setDefaultValue() { if (!empty($this->owner->{$this->attribute})) { return true; } $id = $this->getLastRow()->id + 1; $this->owner->{$this->attribute} = $this->defaultPrefix . '-' . $id; } /** * Return last row inserted * @return mixed */ public function getLastRow() { return $this->owner->find() ->orderBy('id DESC') ->one(); } }
<?php namespace kato\behaviors; use yii\base\Behavior; use yii\db\ActiveRecord; class DefaultTitle extends Behavior { /** * @var string attribute */ public $attribute = "title"; public $defaultPrefix = 'New'; /** * @inheritdoc */ public function events() { return [ActiveRecord::EVENT_BEFORE_INSERT => 'setDefaultValue']; } public function setDefaultValue() { $id = $this->getLastRow()->id + 1; $this->owner->{$this->attribute} = $this->defaultPrefix . '-' . $id; } /** * Return last row inserted * @return mixed */ public function getLastRow() { return $this->owner->find() ->orderBy('id DESC') ->one(); } }
Use Upper case for SQL keywords
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests; import io.prestosql.tests.tpch.TpchQueryRunnerBuilder; import org.testng.annotations.Test; import static io.prestosql.SystemSessionProperties.WORK_PROCESSOR_PIPELINES; public class TestWorkProcessorPipelineQueries extends AbstractTestQueryFramework { protected TestWorkProcessorPipelineQueries() { super(() -> TpchQueryRunnerBuilder .builder() .amendSession(builder -> builder.setSystemProperty(WORK_PROCESSOR_PIPELINES, "true")) .build()); } @Test public void testTopN() { assertQuery("SELECT * FROM orders ORDER BY totalprice LIMIT 10"); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests; import io.prestosql.tests.tpch.TpchQueryRunnerBuilder; import org.testng.annotations.Test; import static io.prestosql.SystemSessionProperties.WORK_PROCESSOR_PIPELINES; public class TestWorkProcessorPipelineQueries extends AbstractTestQueryFramework { protected TestWorkProcessorPipelineQueries() { super(() -> TpchQueryRunnerBuilder .builder() .amendSession(builder -> builder.setSystemProperty(WORK_PROCESSOR_PIPELINES, "true")) .build()); } @Test public void testTopN() { assertQuery("select * from orders order by totalprice limit 10"); } }
QueueSet: Raise QueueEmpty when all queues has been tried.
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queues = map(self.backend.Queue, queues) self.cycle = cycle(self.queues) def get(self): while True: try: return self.cycle.next().get() except QueueEmpty: pass
Fix setting the expense value in add expense form
import { SET_EXPENSE_VALUE, SET_EXPENSE_CATEGORY, SET_EXPENSE_ITEM, RESET_ADD_EXPENSE_FORM, NEW_EXPENSE, SET_EXPENSE_DATE, } from '../constants/ActionTypes'; export const setExpenseValue = (value) => { return { type: SET_EXPENSE_VALUE, value: Math.abs(value) * (-1) }; }; export const setExpenseCategory = (categoryId) => { return { type: SET_EXPENSE_CATEGORY, categoryId }; }; export const setExpenseItem = (itemId) => { return { type: SET_EXPENSE_ITEM, itemId }; }; export const setExpenseDate = (date) => { return { type: SET_EXPENSE_DATE, date }; }; export const resetAddExpenseForm = () => { return { type: RESET_ADD_EXPENSE_FORM, }; }; export const addNewExpense = (expense) => { return { type: NEW_EXPENSE, expense }; };
import { SET_EXPENSE_VALUE, SET_EXPENSE_CATEGORY, SET_EXPENSE_ITEM, RESET_ADD_EXPENSE_FORM, NEW_EXPENSE, SET_EXPENSE_DATE, } from '../constants/ActionTypes'; export const setExpenseValue = (value) => { return { type: SET_EXPENSE_VALUE, value: value * (-1) }; }; export const setExpenseCategory = (categoryId) => { return { type: SET_EXPENSE_CATEGORY, categoryId }; }; export const setExpenseItem = (itemId) => { return { type: SET_EXPENSE_ITEM, itemId }; }; export const setExpenseDate = (date) => { return { type: SET_EXPENSE_DATE, date }; }; export const resetAddExpenseForm = () => { return { type: RESET_ADD_EXPENSE_FORM, }; }; export const addNewExpense = (expense) => { return { type: NEW_EXPENSE, expense }; };
Use nose to run the testsuite.
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', zip_safe=False )
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='tests', zip_safe=False )
Return proper WWW-Authenticate header if API authentication fails
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from werkzeug.datastructures import WWWAuthenticate from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): www_authenticate = WWWAuthenticate('Bearer') abort(401, www_authenticate=www_authenticate) return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): abort(401, www_authenticate='Bearer') return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
Check to make sure the channel isn't set. git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@611 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { if (message.getChannel() == null) message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } }
package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } }
Correct copyright on new file
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.rx; import javax.annotation.Nullable; /** The result of an operation that can return either true, false, or fail with an exception. */ public class BooleanResult extends Result<Boolean> { private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) { super(value, error); } public static BooleanResult ofTrue() { return new BooleanResult(true, null); } public static BooleanResult ofFalse() { return new BooleanResult(false, null); } public static BooleanResult error(Throwable t) { return new BooleanResult(null, t); } /** * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note * that false is also returned if the operation failed in error. */ public boolean isTrue() { return get().orElse(false); } }
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.rx; import javax.annotation.Nullable; /** The result of an operation that can return either true, false, or fail with an exception. */ public class BooleanResult extends Result<Boolean> { private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) { super(value, error); } public static BooleanResult ofTrue() { return new BooleanResult(true, null); } public static BooleanResult ofFalse() { return new BooleanResult(false, null); } public static BooleanResult error(Throwable t) { return new BooleanResult(null, t); } /** * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note * that false is also returned if the operation failed in error. */ public boolean isTrue() { return get().orElse(false); } }
Add skewness to beta prime namespace
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace betaprime */ var betaprime = {}; /** * @name mean * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/mean} */ setReadOnly( betaprime, 'mean', require( '@stdlib/math/base/dist/betaprime/mean' ) ); /** * @name skewness * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/skewness} */ setReadOnly( betaprime, 'skewness', require( '@stdlib/math/base/dist/betaprime/skewness' ) ); /** * @name variance * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/variance} */ setReadOnly( betaprime, 'variance', require( '@stdlib/math/base/dist/betaprime/variance' ) ); // EXPORTS // module.exports = betaprime;
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace betaprime */ var betaprime = {}; /** * @name mean * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/mean} */ setReadOnly( betaprime, 'mean', require( '@stdlib/math/base/dist/betaprime/mean' ) ); /** * @name variance * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/variance} */ setReadOnly( betaprime, 'variance', require( '@stdlib/math/base/dist/betaprime/variance' ) ); // EXPORTS // module.exports = betaprime;
Make use of new thread policy.
/* * JGrapes Event Driven Framework * Copyright (C) 2017-2018 Michael N. Lipp * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. */ package org.jgrapes.examples.core.helloworld; import org.jgrapes.core.Component; import org.jgrapes.core.Components; import org.jgrapes.core.annotation.Handler; import org.jgrapes.core.events.Start; /** * A component that displays "Hello World" on start. */ public class Greeter extends Component { @Handler public void onStart(Start event) { System.out.println("Hello World!"); } public static void main(String[] args) throws InterruptedException { Components.start(new Greeter()); } }
/* * JGrapes Event Driven Framework * Copyright (C) 2017-2018 Michael N. Lipp * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. */ package org.jgrapes.examples.core.helloworld; import org.jgrapes.core.Component; import org.jgrapes.core.Components; import org.jgrapes.core.annotation.Handler; import org.jgrapes.core.events.Start; /** * A component that displays "Hello World" on start. */ public class Greeter extends Component { @Handler public void onStart(Start event) { System.out.println("Hello World!"); } public static void main(String[] args) throws InterruptedException { Components.start(new Greeter()); Components.awaitExhaustion(); System.exit(0); } }
Update test to reflect new default version for node
import sys import logging import subprocess sys.path.insert(0, '..') from unittest2 import TestCase class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def reset(self): self.messages = { 'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': [], } class TestNode(TestCase): def test_is_installed(self): proc = subprocess.Popen(['node', '--version'], stdout=subprocess.PIPE) output = proc.stdout.read() self.assertEquals(output.strip(), 'v0.10.26')
import sys import logging import subprocess sys.path.insert(0, '..') from unittest2 import TestCase class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def reset(self): self.messages = { 'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': [], } class TestNode(TestCase): def test_is_installed(self): proc = subprocess.Popen(['node', '--version'], stdout=subprocess.PIPE) output = proc.stdout.read() self.assertEquals(output.strip(), 'v0.8.11')
Add 'Commands' directory scan for artisan commands
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ Commands\DeleteExpiredActivations::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire')->hourly(); $schedule->command('activations:clean')->daily(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ Commands\DeleteExpiredActivations::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire')->hourly(); $schedule->command('activations:clean')->daily(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
Fix for opening Saka in chrome and firefox
export function toggleHelpMenu () { // TODO } export function toggleSaka () { try { const extensionId = SAKA_PLATFORM === 'chrome' ? 'nbdfpcokndmapcollfpjdpjlabnibjdi' : '{7d7cad35-2182-4457-972d-5a41a2051240}' console.log('ID: ', extensionId) browser.runtime.sendMessage(extensionId, 'toggleSaka') } catch (e) { console.error( 'Install Saka at https://chrome.google.com/webstore/detail/saka/nbdfpcokndmapcollfpjdpjlabnibjdi' ) } } export function passOneKey (event) { // preventDefault() to suppress keypress event // no way to suppress keyup event, so Pass mode must ignore // first keyup event event.preventDefault() event.passKeyType = 'one' return 'Pass' } export function passAllKeys (event) { event.preventDefault() event.passKeyType = 'all' return 'Pass' }
export function toggleHelpMenu () { // TODO } export function toggleSaka () { try { browser.runtime.sendMessage( 'nbdfpcokndmapcollfpjdpjlabnibjdi', 'toggleSaka' ) } catch (e) { console.error( 'Install Saka at https://chrome.google.com/webstore/detail/saka/nbdfpcokndmapcollfpjdpjlabnibjdi' ) } } export function passOneKey (event) { // preventDefault() to suppress keypress event // no way to suppress keyup event, so Pass mode must ignore // first keyup event event.preventDefault() event.passKeyType = 'one' return 'Pass' } export function passAllKeys (event) { event.preventDefault() event.passKeyType = 'all' return 'Pass' }
Convert promise chain to async await.
import Twitter from 'twitter' import S3TweetRepository from './lib/s3-tweet-repository' import slscrypt from '../node_modules/serverless-crypt/dists/slscrypt' const tweetRepository = new S3TweetRepository(process.env.TWEET_CACHE_BUCKET_NAME) const createParams = () => { return { screen_name: 'RealTimeWWII', trim_user: true, exclude_replies: true, include_rts: false, count: 200, tweet_mode: 'extended' } } const handler = async (event, context, callback) => { try { const client = await createTwitterClient(process.env.TWITTER_REST_BASE_URL) const tweets = await client.get('statuses/user_timeline', createParams()) await tweetRepository.saveLatestTweets(tweets) } catch (err) { callback(err) } } const createTwitterClient = async (twitterRestBaseUrl) => { return new Twitter({ consumer_key: await slscrypt.get('twitter_consumer_key'), consumer_secret: await slscrypt.get('twitter_consumer_secret'), access_token_key: await slscrypt.get('twitter_access_token_key'), access_token_secret: await slscrypt.get('twitter_access_token_secret'), rest_base: twitterRestBaseUrl }) } export {handler}
import Twitter from 'twitter' import S3TweetRepository from './lib/s3-tweet-repository' import slscrypt from '../node_modules/serverless-crypt/dists/slscrypt' const tweetRepository = new S3TweetRepository(process.env.TWEET_CACHE_BUCKET_NAME) const handler = (event, context, callback) => { return createTwitterClient(process.env.TWITTER_REST_BASE_URL) .then(client => { const params = { screen_name: 'RealTimeWWII', trim_user: true, exclude_replies: true, include_rts: false, count: 200, tweet_mode: 'extended' } return client.get('statuses/user_timeline', params) }) .then(tweets => tweetRepository.saveLatestTweets(tweets)) .catch(err => callback(err)) } const createTwitterClient = async (twitterRestBaseUrl) => { return new Twitter({ consumer_key: await slscrypt.get('twitter_consumer_key'), consumer_secret: await slscrypt.get('twitter_consumer_secret'), access_token_key: await slscrypt.get('twitter_access_token_key'), access_token_secret: await slscrypt.get('twitter_access_token_secret'), rest_base: twitterRestBaseUrl }) } export {handler}
Fix for NullPointerException when decompiling with `-r`.
package com.strobel.decompiler.languages; import java.util.Collections; import java.util.List; /** * <code>TypeCompilationResults</code> holds the result of decompiling a single type. */ public class TypeDecompilationResults { /** * the mapping from original line numbers to post-compiled line numbers */ private final List<LineNumberPosition> _lineNumberPositions; /** * Constructs decompilation results. * * @param lineNumberPositions * the mapping of original to decompiled line numbers, or <code>null</code> if the * decompilation target language does not support line numbers. */ public TypeDecompilationResults(final List<LineNumberPosition> lineNumberPositions) { _lineNumberPositions = lineNumberPositions; } /** * Returns the line number positions resulting from a decompilation. * * @return an unmodifiable list containing the line number positions resulting * from a decompilation. May be null if the decompilation target language * does not support line numbers. */ public List<LineNumberPosition> getLineNumberPositions() { if (_lineNumberPositions == null) { return Collections.emptyList(); } return Collections.unmodifiableList(_lineNumberPositions); } }
package com.strobel.decompiler.languages; import java.util.Collections; import java.util.List; /** * <code>TypeCompilationResults</code> holds the result of decompiling a single type. */ public class TypeDecompilationResults { /** the mapping from original line numbers to post-compiled line numbers */ private final List<LineNumberPosition> _lineNumberPositions; /** * Constructs decompilation results. * * @param lineNumberPositions the mapping of original to decompiled line numbers, * or <code>null</code> if the decompilation target language does not support * line numbers. */ public TypeDecompilationResults( List<LineNumberPosition> lineNumberPositions) { _lineNumberPositions = lineNumberPositions; } /** * Returns the line number positions resulting from a decompilation. * * @return an unmodifiable list containing the line number positions resulting * from a decompilation. May be null if the decompilation target language * does not support line numbers. */ public List<LineNumberPosition> getLineNumberPositions() { return Collections.unmodifiableList( _lineNumberPositions); } }
Format keyword arguments like PEP-8.
#! /usr/bin/env python from lsapi import lsapi l = lsapi('my-access-id', 'my-secret-key') # As you may have noticed, there are lots of columns available # I did what I could to make them easily-accessible, but there # are a lot, and the names are long. So, the API calls have # defaults # Let's get some URL metrics. Results are now an array of dictionaries # the i'th dictionary is the results for the i'th URL metrics = l.urlMetrics(['www.moz.com', 'www.moz.com/blog']) # Now let's say we only want specific columns in the results authorities = l.urlMetrics(['www.moz.com'], lsapi.UMCols.domainAuthority | lsapi.UMCols.pageAuthority) # Or if you just need results for one URL mozMetrics = l.urlMetrics('www.moz.com') # Now for some anchor text results anchorResults = l.anchorText('www.moz.com/blog') # Or for just specific columns anchorTermResults = l.anchorText('www.moz.com/blog', cols=lsapi.ATCols.term) # Now for some links results links = l.links('www.moz.com') # The links API has more columns to specify, as well as sort, scope, etc. links = l.links('www.moz.com', scope='domain_to_domain', sort='domain_authority', filters=['external', 'nofollow'], targetCols=lsapi.UMCols.url)
#! /usr/bin/env python from lsapi import lsapi l = lsapi('my-access-id', 'my-secret-key') # As you may have noticed, there are lots of columns available # I did what I could to make them easily-accessible, but there # are a lot, and the names are long. So, the API calls have # defaults # Let's get some URL metrics. Results are now an array of dictionaries # the i'th dictionary is the results for the i'th URL metrics = l.urlMetrics(['www.moz.com', 'www.moz.com/blog']) # Now let's say we only want specific columns in the results authorities = l.urlMetrics(['www.moz.com'], lsapi.UMCols.domainAuthority | lsapi.UMCols.pageAuthority) # Or if you just need results for one URL mozMetrics = l.urlMetrics('www.moz.com') # Now for some anchor text results anchorResults = l.anchorText('www.moz.com/blog') # Or for just specific columns anchorTermResults = l.anchorText('www.moz.com/blog', cols=lsapi.ATCols.term) # Now for some links results links = l.links('www.moz.com') # The links API has more columns to specify, as well as sort, scope, etc. links = l.links('www.moz.com', scope='domain_to_domain', sort='domain_authority', filters=['external', 'nofollow'], targetCols = lsapi.UMCols.url)
Add strongly connected components's methods
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _previsit(): pass def _postvisit(): pass def dfs(): pass def _transpose_graph(): pass def _inverse_postvisit_vertex(): pass def strongly_connected_components(): """Strongly connected components for graph. Procedure: - Call (Depth First Search) DFS on graph G to compute finish times for each vertex. - Compute the transpose graph G^T of graph G. - Call DFS on G^T, but in the main loop of DFS, feed the vertex in the decreasing order of postvisit times. - Outpu the vertices of each tree in the DFS forest as separate strongly connected components. """ pass def main(): # 3 strongly connected graphs: {A, B, D, E, G}, {C}, {F, H, I}. adj_dict = { 'A': ['B'], 'B': ['C', 'E'], 'C': ['C', 'F'], 'D': ['B', 'G'], 'E': ['A', 'D'], 'F': ['H'], 'G': ['E'], 'H': ['I'], 'I': ['F'] } strongly_connected_components(adj_dict) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def strongly_connected_components(): """Strongly connected components for graph. Procedure: - Call (Depth First Search) DFS on graph G to compute finish times for each vertex. - Compute the transpose graph G^T of graph G. - Call DFS on G^T, but in the main loop of DFS, feed the vertex in the decreasing order of finish times. - Outpu the vertices of each tree in the DFS forest as separate strongly connected components. """ pass def main(): # 3 strongly connected graphs: {A, B, D, E, G}, {C}, {F, H, I}. adj_dict = { 'A': ['B'], 'B': ['C', 'E'], 'C': ['C', 'F'], 'D': ['B', 'G'], 'E': ['A', 'D'], 'F': ['H'], 'G': ['E'], 'H': ['I'], 'I': ['F'] } strongly_connected_components(adj_dict) if __name__ == '__main__': main()
Kill any hanging processes when grunt exits
'use strict'; var lpad = require('lpad'); var cpCache = []; module.exports = function (grunt) { grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () { var spawnOptions; var cb = this.async(); var options = this.options(); // Set the tasks based on the config format var tasks = this.data.tasks || this.data; // Optionally log the task output if (options.logConcurrentOutput) { spawnOptions = { stdio: 'inherit' }; } lpad.stdout(' '); grunt.util.async.forEach(tasks, function (task, next) { var cp = grunt.util.spawn({ grunt: true, args: [task].concat(grunt.option.flags()), opts: spawnOptions }, function (err, result, code) { if (err || code > 0) { grunt.warn(result.stderr || result.stdout); } grunt.log.writeln('\n' + result.stdout); next(); }); cpCache.push(cp); }, function () { lpad.stdout(); cb(); }); }); }; // make sure all child processes are killed when grunt exits process.on('exit', function () { cpCache.forEach(function (el) { el.kill(); }); });
'use strict'; var lpad = require('lpad'); module.exports = function (grunt) { grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () { var spawnOptions; var cb = this.async(); var options = this.options(); // Set the tasks based on the config format var tasks = this.data.tasks || this.data; // Optionally log the task output if (options.logConcurrentOutput) { spawnOptions = { stdio: 'inherit' }; } lpad.stdout(' '); grunt.util.async.forEach(tasks, function (task, next) { grunt.util.spawn({ grunt: true, args: [task].concat(grunt.option.flags()), opts: spawnOptions }, function (err, result, code) { if (err || code > 0) { grunt.warn(result.stderr || result.stdout); } grunt.log.writeln('\n' + result.stdout); next(); }); }, function () { lpad.stdout(); cb(); }); }); };
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. - The constraint will be reset by the ORM later. - Not doing it may both slow the migration and abort it altogether.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey" ) cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
Fix bug - pick list name and property swapped.
import declare from 'dojo/_base/declare'; import _ModelBase from 'argos/Models/_ModelBase'; import MODEL_NAMES from '../Names'; import getResource from 'argos/I18n'; const resource = getResource('opportunityContactModel'); const contactResource = getResource('contactModel'); const opportunityResource = getResource('opportunityModel'); const __class = declare('crm.Models.OpportunityContact.Base', [_ModelBase], { entityName: 'OpportunityContact', entityDisplayName: resource.entityDisplayName, entityDisplayNamePlural: resource.entityDisplayNamePlural, iconClass: 'fa fa-user fa-lg', resourceKind: 'opportunityContacts', modelName: MODEL_NAMES.OPPORTUNITYCONTACT, security: 'Entities/Contact/View', createPicklists: function createPicklists() { return this.picklists || (this.picklists = [{ name: 'Role', property: 'SalesRole', }, { name: 'Standing', property: 'Standing', }]); }, createRelationships: function createRelationships() { const rel = this.relationships || (this.relationships = [{ name: 'Contact', displayName: contactResource.entityDisplayName, type: 'OneToOne', relatedEntity: 'Contact', relatedProperty: 'ContactId', }, { name: 'Opportunity', displayName: opportunityResource.entityDisplayNamePlural, type: 'OneToOne', relatedEntity: 'Opportunity', relatedProperty: 'OpportunityId', }]); return rel; }, }); export default __class;
import declare from 'dojo/_base/declare'; import _ModelBase from 'argos/Models/_ModelBase'; import MODEL_NAMES from '../Names'; import getResource from 'argos/I18n'; const resource = getResource('opportunityContactModel'); const contactResource = getResource('contactModel'); const opportunityResource = getResource('opportunityModel'); const __class = declare('crm.Models.OpportunityContact.Base', [_ModelBase], { entityName: 'OpportunityContact', entityDisplayName: resource.entityDisplayName, entityDisplayNamePlural: resource.entityDisplayNamePlural, iconClass: 'fa fa-user fa-lg', resourceKind: 'opportunityContacts', modelName: MODEL_NAMES.OPPORTUNITYCONTACT, security: 'Entities/Contact/View', createPicklists: function createPicklists() { return this.picklists || (this.picklists = [{ name: 'SalesRole', property: 'Role', }, { name: 'Standing', property: 'Standing', }]); }, createRelationships: function createRelationships() { const rel = this.relationships || (this.relationships = [{ name: 'Contact', displayName: contactResource.entityDisplayName, type: 'OneToOne', relatedEntity: 'Contact', relatedProperty: 'ContactId', }, { name: 'Opportunity', displayName: opportunityResource.entityDisplayNamePlural, type: 'OneToOne', relatedEntity: 'Opportunity', relatedProperty: 'OpportunityId', }]); return rel; }, }); export default __class;
Fix passing tasks as arguments in CLI
'use strict'; // exit cleanly on Ctrl + C process.on('SIGINT', () => { process.exit(0); }); // modules > 3rd party const _ = require('lodash'); // modules > gulp const gulp = require('gulp'); global.ENV = process.env.NODE_ENV || 'development'; global.PWD = process.env.PWD; const args = process.argv.slice(2); // use tasks from arguments list if present, otherwise use tasks from // configuration (environment specific) let tasks = args.length > 0 ? args : require('./config').tasks; // only require used tasks _.flatten(tasks, true).forEach(task => require(`./tasks/${task}`)); tasks = tasks.map((task) => { if (Array.isArray(task)) { return gulp.parallel(...task); } return task; }); // set up the 'default' task to use runSequence to run all tasks gulp.task('default', gulp.series(...tasks));
'use strict'; // exit cleanly on Ctrl + C process.on('SIGINT', () => { process.exit(0); }); // modules > 3rd party const _ = require('lodash'); // modules > gulp const gulp = require('gulp'); global.ENV = process.env.NODE_ENV || 'development'; global.PWD = process.env.PWD; const args = process.argv.slice(2); // use tasks from arguments list if present, otherwise use tasks from // configuration (environment specific) let { tasks } = args.length > 0 ? args : require('./config'); // only require used tasks _.flatten(tasks, true).forEach(task => require(`./tasks/${task}`)); tasks = tasks.map((task) => { if (Array.isArray(task)) { return gulp.parallel(...task); } return task; }); // set up the 'default' task to use runSequence to run all tasks gulp.task('default', gulp.series(...tasks));
Remove programmatic focus from monitor tests Signed-off-by: Charlie Vieth <ea3f0b85bda195c42ceb97da0f596f9d6d014e12@pivotal.io>
package monitor import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Stats collector", func() { Context("when calculating CPU usage", func() { It("should correctly format it for usage by stats.CPUStats", func() { m := &Monitor{ user: CPUTime{load: 0.25}, kernel: CPUTime{load: 0.50}, idle: CPUTime{load: 0.00}, } c := collector{m: m} cpu, err := c.GetCPUStats() Expect(err).To(HaveOccurred()) Expect(matchFloat(cpu.UserPercent().FractionOf100(), m.user.load*100)).To(Succeed()) Expect(matchFloat(cpu.SysPercent().FractionOf100(), m.kernel.load*100)).To(Succeed()) }) }) })
package monitor import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Stats collector", func() { FContext("when calculating CPU usage", func() { It("should correctly format it for usage by stats.CPUStats", func() { m := &Monitor{ user: CPUTime{load: 0.25}, kernel: CPUTime{load: 0.50}, idle: CPUTime{load: 0.00}, } c := collector{m: m} cpu, err := c.GetCPUStats() Expect(err).To(HaveOccurred()) Expect(matchFloat(cpu.UserPercent().FractionOf100(), m.user.load*100)).To(Succeed()) Expect(matchFloat(cpu.SysPercent().FractionOf100(), m.kernel.load*100)).To(Succeed()) }) }) })
Fix bluetooth characteristic intdef copy-paste typo. PERMISSION_READ_ENCRYPTED_MITM was duplicated and PERMISSION_WRITE_ENCRYPTED_MITM was missing. Full list of available values: https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html
package org.assertj.android.api.bluetooth; import android.bluetooth.BluetoothGattCharacteristic; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; @IntDef( flag = true, value = { BluetoothGattCharacteristic.PERMISSION_READ, BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED, BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM, BluetoothGattCharacteristic.PERMISSION_WRITE, BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED, BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM, BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED, BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM } ) @Retention(SOURCE) @interface BluetoothGattCharacteristicPermissions { }
package org.assertj.android.api.bluetooth; import android.bluetooth.BluetoothGattCharacteristic; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; @IntDef( flag = true, value = { BluetoothGattCharacteristic.PERMISSION_READ, BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED, BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM, BluetoothGattCharacteristic.PERMISSION_WRITE, BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED, BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM, BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED, BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM } ) @Retention(SOURCE) @interface BluetoothGattCharacteristicPermissions { }
Set up rpath properly on OS X.
// 13 december 2015 package ui // #cgo LDFLAGS: -L${SRCDIR} -lui -framework CoreFoundation -lpthread -rpath @executable_path // /* (thanks to http://jorgen.tjer.no/post/2014/05/20/dt-rpath-ld-and-at-rpath-dyld/ for the @executable_path clarifiaction */ // #include <CoreFoundation/CoreFoundation.h> // #include <pthread.h> // extern void _CFRunLoopSetCurrent(CFRunLoopRef); // extern pthread_t _CFMainPThread; import "C" // OS X cares very deeply if we don't run on the very first thread the OS creates // why? who knows. it's stupid and completely indefensible. let's use undocumented APIs to get around it. // apple uses them too: http://www.opensource.apple.com/source/kext_tools/kext_tools-19.2/kextd_main.c?txt // apple HAS SUGGESTED them too: http://lists.apple.com/archives/darwin-development/2002/Sep/msg00250.html // gstreamer uses them too: http://cgit.freedesktop.org/gstreamer/gst-plugins-good/tree/sys/osxvideo/osxvideosink.m func ensureMainThread() { // TODO set to nil like the apple code? C._CFRunLoopSetCurrent(C.CFRunLoopGetMain()) // TODO is this part necessary? C._CFMainPThread = C.pthread_self() }
// 13 december 2015 package ui // #cgo LDFLAGS: -L${SRCDIR} -lui -framework CoreFoundation -lpthread // #include <CoreFoundation/CoreFoundation.h> // #include <pthread.h> // extern void _CFRunLoopSetCurrent(CFRunLoopRef); // extern pthread_t _CFMainPThread; import "C" // OS X cares very deeply if we don't run on the very first thread the OS creates // why? who knows. it's stupid and completely indefensible. let's use undocumented APIs to get around it. // apple uses them too: http://www.opensource.apple.com/source/kext_tools/kext_tools-19.2/kextd_main.c?txt // apple HAS SUGGESTED them too: http://lists.apple.com/archives/darwin-development/2002/Sep/msg00250.html // gstreamer uses them too: http://cgit.freedesktop.org/gstreamer/gst-plugins-good/tree/sys/osxvideo/osxvideosink.m func ensureMainThread() { // TODO set to nil like the apple code? C._CFRunLoopSetCurrent(C.CFRunLoopGetMain()) // TODO is this part necessary? C._CFMainPThread = C.pthread_self() }
Use constant and fix formatting issues
package com.bridge; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class echoes a string called from JavaScript. */ public class Open extends CordovaPlugin { public static final String OPEN_ACTION = "open"; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals(OPEN_ACTION)) { String path = args.getString(0); this.chooseIntent(path, callbackContext); return true; } return false; } private void chooseIntent(String path, CallbackContext callbackContext) { if (path != null && path.length() > 0) { callbackContext.success(path); } else { callbackContext.error("Expected one non-empty string argument."); } } }
package com.bridge; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class echoes a string called from JavaScript. */ public class Open extends CordovaPlugin { @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { String path = args.getString(0); this.chooseIntent(path, callbackContext); return true; } return false; } private void chooseIntent(String path, CallbackContext callbackContext) { if (path != null && path.length() > 0) { callbackContext.success(path); } else { callbackContext.error("Expected one non-empty string argument."); } } }
Add support for other countries
(function( $ ) { var requests = {}; var zipValid = { us: /[0-9]{5}(-[0-9]{4})?/ }; $.ziptastic = function(country, zip, callback){ country = country.toUpperCase(); // Only make unique requests if(!requests[country]) { requests[country] = {}; } if(!requests[country][zip]) { requests[country][zip] = $.getJSON('http://zip.elevenbasetwo.com/v2/' + country + '/' + zip); } // Bind to the finished request requests[country][zip].done(function(data) { if (typeof callback == 'function') { callback(data.country, data.state, data.city, zip); } }); // Allow for binding to the deferred object return requests[country][zip]; }; $.fn.ziptastic = function( options ) { return this.each(function() { var ele = $(this); ele.on('keyup', function() { var zip = ele.val(); // TODO Non-US zip codes? if(zipValid.us.test(zip)) { $.ziptastic('US', zip, function(country, state, city) { // Trigger the updated information ele.trigger('zipChange', [country, state, city, zip]); }); } }); }); }; })( jQuery );
(function( $ ) { var requests = {}; var zipValid = { us: /[0-9]{5}(-[0-9]{4})?/ }; $.ziptastic = function(zip, callback){ // Only make unique requests if(!requests[zip]) { requests[zip] = $.getJSON('http://zip.elevenbasetwo.com/v2/US/' + zip); } // Bind to the finished request requests[zip].done(function(data) { callback(data.country, data.state, data.city, zip); }); // Allow for binding to the deferred object return requests[zip]; }; $.fn.ziptastic = function( options ) { return this.each(function() { var ele = $(this); ele.on('keyup', function() { var zip = ele.val(); // TODO Non-US zip codes? if(zipValid.us.test(zip)) { $.ziptastic(zip, function(country, state, city) { // Trigger the updated information ele.trigger('zipChange', [country, state, city, zip]); }) } }); }); }; })( jQuery );
Fix e2e Exit Code Handling
/* * Copyright 2014 WebFilings, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var spawn = require('child_process').spawn; describe('e2e', function() { it('should successfully run `grunt` in project', function(done) { spawn('grunt', [], { cwd: './test/sample', stdio: 'inherit' }) .on('error', done) .on('exit', function(code) { if (code === 0) { done(); } else { done(new Error('Grunt exited with error ' + code)); } }); }, 20000); });
/* * Copyright 2014 WebFilings, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var spawn = require('child_process').spawn; describe('e2e', function() { it('should successfully run `grunt` in project', function(done) { spawn('grunt', [], { cwd: './test/sample', stdio: 'inherit' }) .on('error', done) .on('exit', function(code) { if (code) { done(new Error('Aborted due to warnings!')); } else { done(); } }); }, 20000); });
Add a test for the banscore deprecation Summary: This is what the `rpc_deprecated.py` test is for. Test Plan: ./test/functional/test_runner.py rpc_deprecated Reviewers: #bitcoin_abc, majcosta Reviewed By: #bitcoin_abc, majcosta Differential Revision: https://reviews.bitcoinabc.org/D8915
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=banscore"]] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # In set_test_params: # self.extra_args = [[], ["-deprecatedrpc=generate"]] # # In run_test: # self.log.info("Test generate RPC") # assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1) # self.nodes[1].generate(1) self.log.info("Test deprecated banscore") assert 'banscore' not in self.nodes[0].getpeerinfo()[0] assert 'banscore' in self.nodes[1].getpeerinfo()[0] if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework # from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # In set_test_params: # self.extra_args = [[], ["-deprecatedrpc=generate"]] # # In run_test: # self.log.info("Test generate RPC") # assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1) # self.nodes[1].generate(1) self.log.info("No tested deprecated RPC methods") if __name__ == '__main__': DeprecatedRpcTest().main()
Remove print message in mocks
# -*- coding: utf-8 -*- """ Mocks for tests on other HW than Raspberry Pi. """ class GPIO(object): BOARD = 'board' IN = 'in' OUT = 'out' PUD_UP = 'pud_up' FALLING = 'falling' HIGH = 'high' LOW = 'low' @classmethod def setmode(cls, mode): print("Mock: set GPIO mode {}".format(mode)) @classmethod def setup(cls, pin, direction, **kwargs): print("Mock: setup GPIO pin {} to {}".format(pin, direction)) @classmethod def output(cls, pin, status): pass @classmethod def add_event_detect(cls, pin, status, **kwargs): print("Mock: detect GPIO pin {} when {}".format(pin, status)) @classmethod def cleanup(cls): print("Mock: quit GPIO")
# -*- coding: utf-8 -*- """ Mocks for tests on other HW than Raspberry Pi. """ class GPIO(object): BOARD = 'board' IN = 'in' OUT = 'out' PUD_UP = 'pud_up' FALLING = 'falling' HIGH = 'high' LOW = 'low' @classmethod def setmode(cls, mode): print("Mock: set GPIO mode {}".format(mode)) @classmethod def setup(cls, pin, direction, **kwargs): print("Mock: setup GPIO pin {} to {}".format(pin, direction)) @classmethod def output(cls, pin, status): print("Mock: output GPIO pin {} to {}".format(pin, status)) @classmethod def add_event_detect(cls, pin, status, **kwargs): print("Mock: detect GPIO pin {} when {}".format(pin, status)) @classmethod def cleanup(cls): print("Mock: quit GPIO")
Create PyPI Release for 1.9.5.0. R=ozarov DELTA=3 (0 added, 0 deleted, 3 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=7045
"""Setup specs for packaging, distributing, and installing gcs lib.""" import distribute_setup distribute_setup.use_setuptools() import setuptools setuptools.setup( name="GoogleAppEngineCloudStorageClient", version="1.9.5.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine cloud storage", url="https://code.google.com/p/appengine-gcs-client/", license="Apache License 2.0", description=("This library is the preferred way of accessing Google " "Cloud Storage from App Engine. It was designed to " "replace the Files API. As a result it contains much " "of the same functionality (streaming reads and writes but " "not the complete set of GCS APIs). It also provides key " "stability improvements and a better overall developer " "experience."), exclude_package_data={"": ["README"]}, zip_safe=True, )
"""Setup specs for packaging, distributing, and installing gcs lib.""" import distribute_setup distribute_setup.use_setuptools() import setuptools setuptools.setup( name="GoogleAppEngineCloudStorageClient", version="1.9.0.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine cloud storage", url="https://code.google.com/p/appengine-gcs-client/", license="Apache License 2.0", description=("This library is the preferred way of accessing Google " "Cloud Storage from App Engine. It was designed to " "replace the Files API. As a result it contains much " "of the same functionality (streaming reads and writes but " "not the complete set of GCS APIs). It also provides key " "stability improvements and a better overall developer " "experience."), exclude_package_data={"": ["README"]}, zip_safe=True, )
Remove preview link until preview is restored
import React from 'react' import styles from './PreviewTools.styl' export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) => ( <div className={styles.container}> <div> Layout: <select value={layout} onChange={onLayoutChanged}> <option value="none">None</option> <option value="blog">Blog</option> <option value="centered">Centered</option> </select> </div> <div> Theme: <select value={theme} onChange={onThemeChanged}> <option value="none">None</option> <option value="idyll">Idyll</option> <option value="github">GitHub</option> </select> </div> {/* <a href={href} target="_blank"> Open in New Window </a> */} </div> )
import React from 'react' import styles from './PreviewTools.styl' export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) => <div className={styles.container}> <div> Layout: <select value={layout} onChange={onLayoutChanged}> <option value="none">None</option> <option value="blog">Blog</option> <option value="centered">Centered</option> </select> </div> <div> Theme: <select value={theme} onChange={onThemeChanged}> <option value="none">None</option> <option value="idyll">Idyll</option> <option value="github">GitHub</option> </select> </div> <a href={href} target="_blank"> Open in New Window </a> </div>
Rewrite apn push a little bit
var apn = require('apn'); var util = require('util'); var BasePushNotification = require('./BasePushNotification'); util.inherits(APNPushNotification, BasePushNotification); /** * Create new APN Push Notification * @param {Object} options * @returns {APNPushNotification} * @constructor */ function APNPushNotification(options) { BasePushNotification.apply(this, arguments); this.setProvider(new apn.Connection({ cert: '', key: '' })); } /** * Create device instance * @param {Object} config * @returns {*} * @private */ APNPushNotification.prototype._createDevice = function (config) { return new apn.Device(config); }; /** * Create notification instance * @param {Object} config * @returns {*} * @private */ APNPushNotification.prototype._createNotification = function (config) { return new apn.Notification(config); }; /** * Send push notification to device * @returns {APNPushNotification} */ APNPushNotification.prototype.send = function () { this .getProvider() .pushNotification(this._createNotification(this.getConfig('notification')), this._createDevice(this.getConfig('device'))); return this; }; module.exports = APNPushNotification;
var apn = require('apn'); var util = require('util'); var BasePushNotification = require('./BasePushNotification'); connection = new apn.Connection({ cert: '', key: '' }).on('error', console.log.bind(console.log)).on('transmissionError', console.log.bind(console.log)); util.inherits(APNPushNotification, BasePushNotification); /** * Create new APN Push Notification * @param {Object} options * @returns {APNPushNotification} * @constructor */ function APNPushNotification(options) { BasePushNotification.apply(this, arguments); options = extend(true, {}, { device: '', notification: { aps: { alert: "\uD83D\uDCE7 \u2709 You have a new message", sound: 'ping.aiff', badge: 1 }, payload: {} } }, options); this.device = new apn.Device(options.device); this.notification = new apn.Notification(options.notification); } /** * Send push notification to device * @returns {APNPushNotification} */ APNPushNotification.prototype.send = function () { connection.pushNotification(this.notification, this.device); return this; }; module.exports = APNPushNotification;
Update vstutils version and fix capability in settings.
''' ### Polemarch is ansible based service for orchestration infrastructure. * [Documentation](http://polemarch.readthedocs.io/) * [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues) * [Source Code](https://gitlab.com/vstconsulting/polemarch) ''' import os import warnings try: from vstutils.environment import prepare_environment, cmd_execution except ImportError: warnings.warn('"vstutils" was not installed', ImportWarning) prepare_environment = lambda *args, **kwargs: () cmd_execution = prepare_environment default_settings = { # ansible specific environment variables "ANSIBLE_HOST_KEY_CHECKING": 'False', "ANSIBLE_FORCE_COLOR": "true", # celery specific "C_FORCE_ROOT": "true", # django settings module "DJANGO_SETTINGS_MODULE": os.getenv( "DJANGO_SETTINGS_MODULE", 'polemarch.main.settings' ), # VSTUTILS settings "VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'), "VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'), } __version__ = "1.4.5" prepare_environment(**default_settings)
''' ### Polemarch is ansible based service for orchestration infrastructure. * [Documentation](http://polemarch.readthedocs.io/) * [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues) * [Source Code](https://gitlab.com/vstconsulting/polemarch) ''' import os import warnings try: from vstutils.environment import prepare_environment, cmd_execution except ImportError: warnings.warn('"vstutils" was not installed', ImportWarning) prepare_environment = lambda *args, **kwargs: () cmd_execution = prepare_environment default_settings = { # ansible specific environment variables "ANSIBLE_HOST_KEY_CHECKING": 'False', "ANSIBLE_FORCE_COLOR": "true", # celery specific "C_FORCE_ROOT": "true", # django settings module "DJANGO_SETTINGS_MODULE": os.getenv( "DJANGO_SETTINGS_MODULE", 'polemarch.main.settings' ), # VSTUTILS settings "VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'), "VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'), } __version__ = "1.4.4" prepare_environment(**default_settings)
Support currently removed for gifs because of bugs
#!/usr/bin/env python ''' Author : Bhavyanshu Parasher Email : bhavyanshu@codershangout.org Description : This file contains all the main functions for the GUI. ''' try: from easygui import * except ImportError: raise ImportError,"The easygui module is required to run this program" import sys try: import Image from tesseract import image_to_string except ImportError: raise ImportError,"The Tesseract module is required to run this program" def AskForFile(): fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"]) content=image_to_string(Image.open(fname)) choices=['Copy to Clipboard','Wrong output? Try again!'] textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0) def help(): # create a function called Dump msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!") def Post(): # create a function called Post f = open(fname, "a"); # open the file defined in Ask. message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox. f.write("\n"); # write a newline to the file. f.write(message) # write your message to the file. def Die(): # Define the function Die. sys.exit() # Quit The Program.
#!/usr/bin/env python ''' Author : Bhavyanshu Parasher Email : bhavyanshu@codershangout.org Description : This file contains all the main functions for the GUI. ''' try: from easygui import * except ImportError: raise ImportError,"The easygui module is required to run this program" import sys try: import Image from tesseract import image_to_string except ImportError: raise ImportError,"The Tesseract module is required to run this program" def AskForFile(): fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ]) content=image_to_string(Image.open(fname)) choices=['Copy to Clipboard','Wrong output? Try again!'] textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0) def help(): # create a function called Dump msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!") def Post(): # create a function called Post f = open(fname, "a"); # open the file defined in Ask. message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox. f.write("\n"); # write a newline to the file. f.write(message) # write your message to the file. def Die(): # Define the function Die. sys.exit() # Quit The Program.
Replace hardcoded reference to http with https - This allows our tests to pass in deployments that do not allow http traffic [#101144102] Signed-off-by: Lyle Franklin <31e283733c7a4b3b6cb03b95ab535671c2112bbe@pivotal.io>
package riak_cs_service import ( "github.com/cloudfoundry-incubator/cf-test-helpers/runner" . "github.com/onsi/ginkgo" ) var _ = Describe("Riak CS Nodes Register a Route", func() { It("Allows users to access the riak-cs service using external url instead of IP of single machine after register the route", func() { endpointURL := TestConfig.RiakCsScheme + TestConfig.RiakCsHost + "/riak-cs/ping" runner.NewCmdRunner(runner.Curl("-k", endpointURL), TestContext.ShortTimeout()).WithOutput("OK").Run() }) }) var _ = Describe("Riak Broker Registers a Route", func() { It("Allows users to access the riak-cs broker using a url", func() { endpointURL := "https://" + TestConfig.BrokerHost + "/v2/catalog" // check for 401 because it means we reached the endpoint, but did not supply credentials. // a failure would be a 404 runner.NewCmdRunner(runner.Curl("-k", "-s", "-w", "%{http_code}", endpointURL, "-o", "/dev/null"), TestContext.ShortTimeout()).WithOutput("401").Run() }) })
package riak_cs_service import ( "github.com/cloudfoundry-incubator/cf-test-helpers/runner" . "github.com/onsi/ginkgo" ) var _ = Describe("Riak CS Nodes Register a Route", func() { It("Allows users to access the riak-cs service using external url instead of IP of single machine after register the route", func() { endpointURL := TestConfig.RiakCsScheme + TestConfig.RiakCsHost + "/riak-cs/ping" runner.NewCmdRunner(runner.Curl("-k", endpointURL), TestContext.ShortTimeout()).WithOutput("OK").Run() }) }) var _ = Describe("Riak Broker Registers a Route", func() { It("Allows users to access the riak-cs broker using a url", func() { endpointURL := "http://" + TestConfig.BrokerHost + "/v2/catalog" // check for 401 because it means we reached the endpoint, but did not supply credentials. // a failure would be a 404 runner.NewCmdRunner(runner.Curl("-k", "-s", "-w", "%{http_code}", endpointURL, "-o", "/dev/null"), TestContext.ShortTimeout()).WithOutput("401").Run() }) })
Update up to changes to site-tree
'use strict'; var normalizeOptions = require('es5-ext/object/normalize-options') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , ensureObject = require('es5-ext/object/valid-object') , ensureStringifiable = require('es5-ext/object/validate-stringifiable-value') , d = require('d') , htmlToDom = require('html-template-to-dom') , SiteTree = require('site-tree') , defineProperty = Object.defineProperty, defineProperties = Object.defineProperties; var HtmlSiteTree = defineProperties(setPrototypeOf(function (document, inserts) { if (!(this instanceof HtmlSiteTree)) return new HtmlSiteTree(document, inserts); SiteTree.call(this, document); defineProperty(this, 'inserts', d(ensureObject(inserts))); }, SiteTree), { ensureTemplate: d(ensureStringifiable) }); HtmlSiteTree.prototype = Object.create(SiteTree.prototype, { constructor: d(HtmlSiteTree), _resolveTemplate: d(function (tpl, context) { return htmlToDom(this.document, tpl, normalizeOptions(this.inserts, context)); }) }); module.exports = HtmlSiteTree;
'use strict'; var normalizeOptions = require('es5-ext/object/normalize-options') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , ensureObject = require('es5-ext/object/valid-object') , ensureStringifiable = require('es5-ext/object/validate-stringifiable-value') , d = require('d') , htmlToDom = require('html-template-to-dom') , SiteTree = require('site-tree') , defineProperty = Object.defineProperty, defineProperties = Object.defineProperties; var HtmlSiteTree = defineProperties(setPrototypeOf(function (document, inserts) { if (!(this instanceof HtmlSiteTree)) return new HtmlSiteTree(document, inserts); SiteTree.call(this, document); defineProperty(this, 'inserts', d(ensureObject(inserts))); }, SiteTree), { ensureTemplate: d(ensureStringifiable) }); HtmlSiteTree.prototype = Object.create(SiteTree.prototype, { constructor: d(HtmlSiteTree), resolveTemplate: d(function (tpl, context) { return htmlToDom(this.document, tpl, normalizeOptions(this.inserts, context)); }) }); module.exports = HtmlSiteTree;
Upgrade to using twp.sqlachemy3 3.1.0 which hosts search itself thus needing a change to setup.py requirements
AUTHOR = 'Chris Dent' AUTHOR_EMAIL = 'cdent@peermore.com' NAME = 'tiddlywebplugins.mysql3' DESCRIPTION = 'MySQL-based store for tiddlyweb' VERSION = '3.0.13' # don't forget to update __init__.py too import os from setuptools import setup, find_packages setup( namespace_packages = ['tiddlywebplugins'], name = NAME, version = VERSION, description = DESCRIPTION, long_description = open(os.path.join(os.path.dirname(__file__), 'README')).read(), author = AUTHOR, author_email = AUTHOR_EMAIL, url = 'http://pypi.python.org/pypi/%s' % NAME, platforms = 'Posix; MacOS X; Windows', packages = find_packages(exclude=['test']), install_requires = ['setuptools', 'tiddlyweb>=1.4.2', 'tiddlywebplugins.sqlalchemy3>=3.1.0', 'MySQL-python', ], zip_safe = False, license = 'BSD' )
AUTHOR = 'Chris Dent' AUTHOR_EMAIL = 'cdent@peermore.com' NAME = 'tiddlywebplugins.mysql3' DESCRIPTION = 'MySQL-based store for tiddlyweb' VERSION = '3.0.13' # don't forget to update __init__.py too import os from setuptools import setup, find_packages setup( namespace_packages = ['tiddlywebplugins'], name = NAME, version = VERSION, description = DESCRIPTION, long_description = open(os.path.join(os.path.dirname(__file__), 'README')).read(), author = AUTHOR, author_email = AUTHOR_EMAIL, url = 'http://pypi.python.org/pypi/%s' % NAME, platforms = 'Posix; MacOS X; Windows', packages = find_packages(exclude=['test']), install_requires = ['setuptools', 'tiddlyweb>=1.4.2', 'tiddlywebplugins.sqlalchemy3>=3.0.15', 'sqlalchemy>=0.7.0', 'MySQL-python', 'pyparsing<2.0.0', ], zip_safe = False, license = 'BSD' )
Use express server instead of brunch default
module.exports.config = { files: { javascripts: { joinTo: { "js/app.js": /^app/, "js/vendor.js": /^(?!app)/ }, order: { before: [ "bower_components/jquery/dist/jquery.js", "bower_components/underscore/underscore.js", "bower_components/bluebird/js/browser/bluebird.js", "bower_components/react/react.js" ] } }, stylesheets: { joinTo: "css/app.css" }, templates: { joinTo: "js/app.js" } }, plugins: { react: { autoIncludeCommentBlock: true, harmony: true, transformOptions : { sourceMap : true } }, reactTags: { verbose: true } }, server: { path: 'app.js', port: 3333, run: true } };
module.exports.config = { files: { javascripts: { joinTo: { "js/app.js": /^app/, "js/vendor.js": /^(?!app)/ }, order: { before: [ "bower_components/jquery/dist/jquery.js", "bower_components/underscore/underscore.js", "bower_components/react/react.js" ] } }, stylesheets: { joinTo: "css/app.css" }, templates: { joinTo: "js/app.js" } }, plugins: { react: { autoIncludeCommentBlock: true, harmony: true, transformOptions : { sourceMap : true } }, reactTags: { verbose: true } }, server: { port: 3333, run: true } };
Fix if no video link element in speech
'use strict'; var got = require('got'); var cheerio = require('cheerio'); var md = require('html-md'); module.exports = function(id, callback) { var url = 'http://www.stm.dk/_p_' + id + '.html'; got(url, function(err, data){ var $ = cheerio.load(data); var meta = $('meta[name="created"]'); var speech = $('.maininner.maininner-page'); speech.find('h1').remove(); speech.find('.nedtonet').remove(); var data = { source: url, date: meta.attr('content'), html: speech.html(), markdown: md(speech.html(), {inline: true}).replace(/\\/gi, '') }; var linkElement = speech.find('a[onclick]'); if(linkElement.length){ var link = linkElement.attr('onclick').split('\'')[1]; linkElement.attr('href', link); data.video = link; speech.children().last().remove(); speech.children().last().remove(); speech.children().last().remove(); } callback(null, data) }); };
'use strict'; var got = require('got'); var cheerio = require('cheerio'); var md = require('html-md'); module.exports = function(id, callback) { var url = 'http://www.stm.dk/_p_' + id + '.html'; got(url, function(err, data){ var $ = cheerio.load(data); var meta = $('meta[name="created"]'); var speech = $('.maininner.maininner-page'); speech.find('h1').remove(); speech.find('.nedtonet').remove(); var linkElement = speech.find('a[onclick]'); var link = linkElement.attr('onclick').split('\'')[1]; linkElement.attr('href', link); speech.children().last().remove(); speech.children().last().remove(); speech.children().last().remove(); callback(null, { source: url, video: link, date: meta.attr('content'), html: speech.html(), markdown: md(speech.html(), {inline: true}).replace(/\\/gi, '') }) }); };
Add a command line argument for enabling instatrace globally
import argparse import logging import sys from . import commands parser = argparse.ArgumentParser(description="Cobe control") parser.add_argument("-b", "--brain", default="cobe.brain") parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS) parser.add_argument("--instatrace", metavar="FILE", help="log performance statistics to FILE") subparsers = parser.add_subparsers(title="Commands") commands.ConsoleCommand.add_subparser(subparsers) commands.InitCommand.add_subparser(subparsers) commands.LearnCommand.add_subparser(subparsers) commands.LearnIrcLogCommand.add_subparser(subparsers) def main(): args = parser.parse_args() formatter = logging.Formatter("%(levelname)s: %(message)s") console = logging.StreamHandler() console.setFormatter(formatter) logging.root.addHandler(console) if args.debug: logging.root.setLevel(logging.DEBUG) else: logging.root.setLevel(logging.INFO) if args.instatrace: instatrace.Instatrace().init(args.instatrace) try: args.run(args) except KeyboardInterrupt: print sys.exit(1) if __name__ == "__main__": main()
import argparse import logging import sys from . import commands parser = argparse.ArgumentParser(description="Cobe control") parser.add_argument("-b", "--brain", default="cobe.brain") parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS) subparsers = parser.add_subparsers(title="Commands") commands.ConsoleCommand.add_subparser(subparsers) commands.InitCommand.add_subparser(subparsers) commands.LearnCommand.add_subparser(subparsers) commands.LearnIrcLogCommand.add_subparser(subparsers) def main(): args = parser.parse_args() formatter = logging.Formatter("%(levelname)s: %(message)s") console = logging.StreamHandler() console.setFormatter(formatter) logging.root.addHandler(console) if args.debug: logging.root.setLevel(logging.DEBUG) else: logging.root.setLevel(logging.INFO) try: args.run(args) except KeyboardInterrupt: print sys.exit(1) if __name__ == "__main__": main()
Remove config parameter from mathJaxUrl.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. require.config({ config : { 'workers/WorkerProxy' : {'workerUrl' : '/scripts/readium-worker.js'}, 'EpubLibraryManager' : { 'canHandleUrl' : true, 'canHandleDirectory' : true }, 'EpubReader' : { 'annotationCssUrl' : self.location.origin + '/css/annotations.css', 'mathJaxUrl' : self.location.origin + '/scripts/mathjax/MathJax.js' } } });
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. require.config({ config : { 'workers/WorkerProxy' : {'workerUrl' : '/scripts/readium-worker.js'}, 'EpubLibraryManager' : { 'canHandleUrl' : true, 'canHandleDirectory' : true }, 'EpubReader' : { 'annotationCssUrl' : self.location.origin + '/css/annotations.css', 'mathJaxUrl' : self.location.origin + '/scripts/mathjax/MathJax.js?config=readium-iframe' } } });
Fix issue with building the wheel The build trips on an empty string requirement, throwing: ``` $ python setup.py sdist bdist_wheel ... ValueError: ('No requirements found', '') ```
import sys from setuptools import setup, find_packages import querylist tests_require = [ 'nose>=1.3.6,<1.4', 'spec>=1.2.2,<1.3', ] if sys.version_info < (2, 7): # spec causes python setup.py test to fail. This import fixes that for # some reason. import multiprocessing # noqa # If we're still on python 2.6, we need unittest2 tests_require.append('unittest2<1.2') setup( name='querylist', version=querylist.__version__, url='https://github.com/thomasw/querylist', download_url='https://github.com/thomasw/querylist/downloads', author=querylist.__author__, author_email='thomas.welfley+querylist@gmail.com', description='This package provides a QueryList class with django ' 'ORM-esque filtering, excluding, and getting for lists. It ' 'also provides BetterDict, a dot lookup/assignment capable ' 'wrapper for dicts that is 100% backwards compatible.', packages=find_packages(), tests_require=tests_require, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries', ], test_suite='nose.collector', )
import sys from setuptools import setup, find_packages import querylist unittest2_module = '' if sys.version_info < (2, 7): # spec causes python setup.py test to fail. This import fixes that for # some reason. import multiprocessing # noqa # If we're still on python 2.6, we need unittest2 unittest2_module = 'unittest2<1.2' setup( name='querylist', version=querylist.__version__, url='https://github.com/thomasw/querylist', download_url='https://github.com/thomasw/querylist/downloads', author=querylist.__author__, author_email='thomas.welfley+querylist@gmail.com', description='This package provides a QueryList class with django ' 'ORM-esque filtering, excluding, and getting for lists. It ' 'also provides BetterDict, a dot lookup/assignment capable ' 'wrapper for dicts that is 100% backwards compatible.', packages=find_packages(), tests_require=[ 'nose>=1.3.6,<1.4', 'spec>=1.2.2,<1.3', unittest2_module ], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries', ], test_suite='nose.collector', )
Add sequence key to make sorting easier (w/ thanks to @curiousdannii)
#!/usr/bin/env node var readline = require('readline'); var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser; var bcv = new bcv_parser(); var formatter = require('bible-reference-formatter/es6/tr'); bcv.set_options({ 'sequence_combination_strategy': 'separate' }); bcv.include_apocrypha(true); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); var references = []; function extract_references (data) { var res = bcv.parse(data).parsed_entities(); res.forEach(function(match) { var ref = {}; ref.original = data.slice(match.indices[0], match.indices[1]); ref.osis = match.osis; ref.seq = bcv.translations.default.order[match.start.b] * 1000000 + match.start.c * 1000 + match.start.v; ref.reformat = formatter('yc-long', match.osis); references.push(ref); }); } function output_references () { var output = JSON.stringify(references, null, ' '); process.stdout.write(output); } rl.on('line', extract_references); rl.on('close', output_references);
#!/usr/bin/env node var readline = require('readline'); var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser; var bcv = new bcv_parser(); var formatter = require('bible-reference-formatter/es6/tr'); bcv.set_options({ 'sequence_combination_strategy': 'separate' }); bcv.include_apocrypha(true); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); var references = []; function extract_references (data) { var res = bcv.parse(data).osis_and_indices(); res.forEach(function(match) { var ref = {}; ref.original = data.slice(match.indices[0], match.indices[1]); ref.osis = match.osis; ref.reformat = formatter('yc-long', match.osis); references.push(ref); }); } function output_references () { var output = JSON.stringify(references, null, ' '); process.stdout.write(output); } rl.on('line', extract_references); rl.on('close', output_references);
Use the new fancy refactored remote logic
from stanczyk.util import _getRemote from twisted.internet import endpoints, reactor from txampext.multiplexing import ProxyingFactory def connectProxy(namespace, identifier, _reactor=reactor): """Start listening on some free local port; connections will be proxied to the virtual server with the given identifier. """ endpoint = endpoints.TCP4ServerEndpoint(_reactor, 0, interface="localhost") factory = ProxyingFactory(_getRemote(namespace), identifier) d = endpoint.listen(factory) d.addCallback(_listening, namespace, identifier) return None def _listening(listeningPort, namespace, identifier): """Started listening; report success to terminal. """ host = listeningPort.getHost() template = "{id} is now listening on {h.host}:{h.port}" namespace["manhole"].writeLine(template.format(h=host, id=identifier))
from twisted.internet import endpoints, reactor from txampext.multiplexing import ProxyingFactory def connectProxy(namespace, identifier, _reactor=reactor): """Start listening on some free local port; connections will be proxied to the virtual server with the given identifier. """ remote = namespace.get("remote") if remote is None: raise RuntimeError("You are not connected to the exercise server. " "Call ``connect``.") factory = ProxyingFactory(remote, identifier) endpoint = endpoints.TCP4ServerEndpoint(_reactor, 0, interface="localhost") d = endpoint.listen(factory) d.addCallback(_listening, namespace, identifier) return None def _listening(listeningPort, namespace, identifier): """Started listening; report success to terminal. """ host = listeningPort.getHost() template = "{id} is now listening on {h.host}:{h.port}" namespace["manhole"].writeLine(template.format(h=host, id=identifier))
Abort if req.flick doesn't exists (ie. the `payload()` hasn't been called/used).
function handle( req, res, done ) { if( !req.flick ) { return done(); } var payload = req.flick.payload, repository = payload.repository.owner.name + '/' + payload.repository.name, index = 0, self = this; function next( err ) { var handler = self.stack[ index++ ]; if( !handler || err ) { return done( err ); } if( !~[ '*', repository ].indexOf( handler.repository ) ) { return next(); } handler.handle( req, res, next ); } next(); } exports.handle = handle; function use( repository, fn ) { if( !fn ) { fn = repository; repository = '*'; } this.stack.push( { repository: repository, handle: fn } ); } exports.use = use;
function handle( req, res, done ) { var payload = req.flick.payload, repository = payload.repository.owner.name + '/' + payload.repository.name, index = 0, self = this; function next( err ) { var handler = self.stack[ index++ ]; if( !handler || err ) { return done( err ); } if( !~[ '*', repository ].indexOf( handler.repository ) ) { return next(); } handler.handle( req, res, next ); } next(); } exports.handle = handle; function use( repository, fn ) { if( !fn ) { fn = repository; repository = '*'; } this.stack.push( { repository: repository, handle: fn } ); } exports.use = use;
Stop fetching status from my laptop please
var params = location.hash.slice(1).split("/"), url = "", email = params[0], ids = params[1].split(","); function showError() { $(".alert").html( "Sorry. There was an error. Are your order numbers correct?" ).removeClass("hidden"); }; function showStatus(data) { $.each(data.orders, function(_, order) { $(".js-status-rows").append( [ '<div class="panel panel-default">', '<div class="panel-heading">', '<h3 class="panel-title">', '<code>', order.number, '</code>', order.progress + " " + order.message, '</h3>', '</div>', '<div class="panel-body">', order.description, '</div>', '</div>' ].join("") ); }); }; $.get( [url, email, ids.join(",")].join("/") ).done(function(data) { $(".status").removeClass("hidden"); showStatus(data); }).fail(function() { showError(); }).always(function() { $(".spinner").addClass("hidden"); });
var params = location.hash.slice(1).split("/"), url = "http://localhost:5000", email = params[0], ids = params[1].split(","); function showError() { $(".alert").html( "Sorry. There was an error. Are your order numbers correct?" ).removeClass("hidden"); }; function showStatus(data) { $.each(data.orders, function(_, order) { $(".js-status-rows").append( [ '<div class="panel panel-default">', '<div class="panel-heading">', '<h3 class="panel-title">', '<code>', order.number, '</code>', order.progress + " " + order.message, '</h3>', '</div>', '<div class="panel-body">', order.description, '</div>', '</div>' ].join("") ); }); }; $.get( [url, email, ids.join(",")].join("/") ).done(function(data) { $(".status").removeClass("hidden"); showStatus(data); }).fail(function() { showError(); }).always(function() { $(".spinner").addClass("hidden"); });
Fix broken reference to node_type.
from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * import duralex.tree class ForkReferenceVisitor(AbstractVisitor): def visit_node(self, node): if duralex.tree.is_reference(node) and 'children' in node and len(node['children']) > 1: ref_nodes = filter(lambda n: duralex.tree.is_reference(n), node['children']) for i in range(1, len(ref_nodes)): ref = ref_nodes[i] fork = copy_node(node, recursive=False) remove_node(node, ref) push_node(fork, ref) push_node(node['parent'], fork) super(ForkReferenceVisitor, self).visit_node(node)
from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * import duralex.node_type class ForkReferenceVisitor(AbstractVisitor): def visit_node(self, node): if duralex.tree.is_reference(node) and 'children' in node and len(node['children']) > 1: ref_nodes = filter(lambda n: duralex.tree.is_reference(n), node['children']) for i in range(1, len(ref_nodes)): ref = ref_nodes[i] fork = copy_node(node, recursive=False) remove_node(node, ref) push_node(fork, ref) push_node(node['parent'], fork) super(ForkReferenceVisitor, self).visit_node(node)
Deal with Substance Image -> ImageNode
import ImageNode from 'substance/packages/image/ImageNode' import ImageComponent from 'substance/packages/image/ImageComponent' import ImageMarkdownComponent from './ImageMarkdownComponent' import ImageHTMLConverter from 'substance/packages/image/ImageHTMLConverter' import ImageXMLConverter from 'substance/packages/image/ImageXMLConverter' import ImageMacro from './ImageMacro' import ImageTool from './ImageTool' export default { name: 'image', configure: function (config) { config.addNode(ImageNode) config.addComponent('image', ImageComponent) config.addComponent('image-markdown', ImageMarkdownComponent) config.addConverter('html', ImageHTMLConverter) config.addConverter('xml', ImageXMLConverter) config.addMacro(new ImageMacro()) config.addTool('image', ImageTool) config.addIcon('image', { 'fontawesome': 'fa-image' }) config.addLabel('image', { en: 'Image', de: 'Überschrift' }) } }
import Image from 'substance/packages/image/Image' import ImageComponent from 'substance/packages/image/ImageComponent' import ImageMarkdownComponent from './ImageMarkdownComponent' import ImageHTMLConverter from 'substance/packages/image/ImageHTMLConverter' import ImageXMLConverter from 'substance/packages/image/ImageXMLConverter' import ImageMacro from './ImageMacro' import ImageTool from './ImageTool' export default { name: 'image', configure: function (config) { config.addNode(Image) config.addComponent('image', ImageComponent) config.addComponent('image-markdown', ImageMarkdownComponent) config.addConverter('html', ImageHTMLConverter) config.addConverter('xml', ImageXMLConverter) config.addMacro(new ImageMacro()) config.addTool('image', ImageTool) config.addIcon('image', { 'fontawesome': 'fa-image' }) config.addLabel('image', { en: 'Image', de: 'Überschrift' }) } }
refactor: Add extra accepted props for general alerts
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Alert } from '@blueprintjs/core'; export default class GenAlert extends PureComponent { static propTypes = { cancelText: PropTypes.string, confirmText: PropTypes.string.isRequired, intent: PropTypes.number.isRequired, isOpen: PropTypes.bool.isRequired, message: PropTypes.oneOfType([ PropTypes.string, PropTypes.node ]).isRequired, closeGeneralAlert: PropTypes.func.isRequired, onConfirm: PropTypes.func }; whenConfirm = () => { const { closeGeneralAlert, onConfirm } = this.props; if (typeof onConfirm === 'function') onConfirm(); closeGeneralAlert(); }; render() { const { cancelText, confirmText, intent, isOpen, message, closeGeneralAlert } = this.props; return ( <Alert isOpen={isOpen} cancelButtonText={cancelText} confirmButtonText={confirmText} intent={intent} onCancel={closeGeneralAlert} onConfirm={this.whenConfirm} > {message} </Alert> ); } }
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Alert } from '@blueprintjs/core'; export default class GenAlert extends PureComponent { static propTypes = { cancelText: PropTypes.string, confirmText: PropTypes.string.isRequired, intent: PropTypes.number.isRequired, isOpen: PropTypes.bool.isRequired, message: PropTypes.string.isRequired, closeGeneralAlert: PropTypes.func.isRequired, onConfirm: PropTypes.func }; whenConfirm = () => { const { closeGeneralAlert, onConfirm } = this.props; if (typeof onConfirm === 'function') onConfirm(); closeGeneralAlert(); }; render() { const { cancelText, confirmText, intent, isOpen, message, closeGeneralAlert } = this.props; return ( <Alert isOpen={isOpen} cancelButtonText={cancelText} confirmButtonText={confirmText} intent={intent} onCancel={closeGeneralAlert} onConfirm={this.whenConfirm} > {message} </Alert> ); } }
Prepare for release of 0.0.4
#!/usr/bin/env python from setuptools import setup setup(name='tap-awin', version='0.0.4', description='Singer.io tap for extracting data from the Affiliate Window API', author='Onedox', url='https://github.com/onedox/tap-awin', classifiers=['Programming Language :: Python :: 3 :: Only'], py_modules=['tap_awin'], install_requires=[ 'zeep>=1.4.1', 'singer-python>=3.6.3', 'tzlocal>=1.3', ], entry_points=''' [console_scripts] tap-awin=tap_awin:main ''', packages=['tap_awin'], package_data = { 'tap_awin/schemas': [ "transactions.json", "merchants.json", ], }, include_package_data=True, )
#!/usr/bin/env python from setuptools import setup setup(name='tap-awin', version='0.0.3', description='Singer.io tap for extracting data from the Affiliate Window API', author='Onedox', url='https://github.com/onedox/tap-awin', classifiers=['Programming Language :: Python :: 3 :: Only'], py_modules=['tap_awin'], install_requires=[ 'zeep>=1.4.1', 'singer-python>=3.6.3', 'tzlocal>=1.3', ], entry_points=''' [console_scripts] tap-awin=tap_awin:main ''', packages=['tap_awin'], package_data = { 'tap_awin/schemas': [ "transactions.json", "merchants.json", ], }, include_package_data=True, )
Add correct function to script endpoint
from setuptools import setup, find_packages setup( name='Matador', version='0.0.1', author='Owen Campbell', author_email='owen.campbell@empiria.co.uk', entry_points={ 'console_scripts': [ 'matador = core.management:execute_command', ], }, url='http://www.empiria.co.uk', packages=find_packages(), license='The MIT License (MIT)', description='Change management for Agresso systems', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Natural Language :: English' ] )
from setuptools import setup, find_packages setup( name='Matador', version='0.0.1', author='Owen Campbell', author_email='owen.campbell@empiria.co.uk', entry_points={ 'console_scripts': [ 'matador = core.management:hello', ], }, url='http://www.empiria.co.uk', packages=find_packages(), license='The MIT License (MIT)', description='Change management for Agresso systems', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Natural Language :: English' ] )
Remove unused argument/flag when tweeting
package com.tmitim.twittercli.commands; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.github.rvesse.airline.SingleCommand; import com.github.rvesse.airline.annotations.Arguments; import com.github.rvesse.airline.annotations.Command; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * Tweet to twitter * */ @Command(name = "tweet", description = "Tweet your thoughts") public class Tweet implements Runnable { @Arguments(description = "Additional arguments") private List<String> args; public static void main(String[] args) { SingleCommand<Tweet> parser = SingleCommand.singleCommand(Tweet.class); Tweet cmd = parser.parse(args); cmd.run(); } @Override public void run() { Twitter twitter = TwitterFactory.getSingleton(); try { Status status = twitter.updateStatus(StringUtils.join(args, " ")); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } catch (TwitterException e) { e.printStackTrace(); } } }
package com.tmitim.twittercli.commands; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.github.rvesse.airline.SingleCommand; import com.github.rvesse.airline.annotations.Arguments; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * Tweet to twitter * */ @Command(name = "tweet", description = "Tweet your thoughts") public class Tweet implements Runnable { @Option(name = { "-f", "--flag" }, description = "An option that requires no values") private boolean flag = false; @Arguments(description = "Additional arguments") private List<String> args; public static void main(String[] args) { SingleCommand<Tweet> parser = SingleCommand.singleCommand(Tweet.class); Tweet cmd = parser.parse(args); cmd.run(); } public void run() { Twitter twitter = TwitterFactory.getSingleton(); try { Status status = twitter.updateStatus(StringUtils.join(args, " ")); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Flag was " + (this.flag ? "set" : "not set")); if (args != null) System.out.println("Arguments were " + StringUtils.join(args, " ")); } }
Fix config file hashing on app start
/* global rm, mkdir, exec, ls, mv*/ require('shelljs/global'); var fs = require('fs'); var crypto = require('crypto'); var ms = require('ms'); var start = new Date(); // NOTE: Webpack's hash also uses the absolute path on the filesystem // Since config is built in `start.sh` and apps can be on different // servers and directory, we implement our own hashing using the file's content function getHash(str) { var hash = crypto.createHash('md5'); hash.update(str); return hash.digest('hex').substr(0, 20); } console.log('Building config...'); exec('webpack --entry \'./config.app.js\' --output-library \'config\' --output-file \'config.js\' --colors --progress'); var hash = getHash(fs.readFileSync('dist/config.js')); var filename = 'config.' + hash + '.js'; console.log('Renaming to ' + filename + '...'); mv('-f', 'dist/config.js', 'dist/' + filename); console.log('Updating "dist/index.html"...'); var indexHtml = fs.readFileSync('dist/index.html', 'utf8'); indexHtml = indexHtml.replace('<!-- config -->', '<script type="text/javascript" src="' + filename + '"></script>' ); indexHtml.to('dist/index.html'); var end = new Date(); console.log('Config built in ' + ms(end - start));
/* global rm, mkdir, exec, ls*/ require('shelljs/global'); var fs = require('fs'); var ms = require('ms'); var start = new Date(); console.log('Building config...'); exec('webpack --entry \'./config.app.js\' --output-library \'config\' --output-file \'config.[hash].js\' --colors --progress'); function getBundleFilename() { var matches = ls('dist/config.*.js'); if (!(matches && matches.length)) { throw new Error('Expected to find "dist/config.[hash].js"'); } return matches[0].replace('dist/', ''); } console.log('Updating "dist/index.html"...'); var indexHtml = fs.readFileSync('dist/index.html', 'utf8'); indexHtml = indexHtml.replace('<!-- config -->', '<script type="text/javascript" src="' + getBundleFilename() + '"></script>' ); indexHtml.to('dist/index.html'); var end = new Date(); console.log('Config built in ' + ms(end - start));
Allow string as expectedKeys parameter and update jsdocs
/*global require, module*/ /*! * missing-keys <https://github.com/tobiasoberrauch/missing-keys> * * Copyright (c) 2015, Tobias Oberrauch. * Licensed under the MIT License. */ 'use strict'; (function (factory) { if (typeof module === "object" && typeof module.exports === "object") { module.exports = factory(); } else if (typeof window === "object") { window.missingKeys = factory(); } }(function () { /** * * @param {object} object * @param {string|object} expectedKeys * @returns {Array.<T>|*} */ function missingKeys(object, expectedKeys) { expectedKeys = Object.prototype.toString.call(expectedKeys) === '[object Array]' ? expectedKeys : [expectedKeys]; var actualKeys = Object.keys(object); return expectedKeys.filter(function (expectedKey) { return actualKeys.indexOf(expectedKey) === -1; }); } /** * @type {missingKeys} */ missingKeys.get = missingKeys; /** * * @param {object} object * @param {string|object} expectedKeys * @returns {boolean} */ missingKeys.has = function (object, expectedKeys) { return missingKeys(object, expectedKeys).length > 0; }; return missingKeys; }));
/*global require, module*/ /*! * missing-keys <https://github.com/tobiasoberrauch/missing-keys> * * Copyright (c) 2015, Tobias Oberrauch. * Licensed under the MIT License. */ 'use strict'; (function (factory) { if (typeof module === "object" && typeof module.exports === "object") { module.exports = factory(); } else if (typeof window === "object") { window.missingKeys = factory(); } }(function () { /** * * @param object * @param expectedKeys * @returns {Array.<T>|*} */ function missingKeys(object, expectedKeys) { var actualKeys = Object.keys(object); return expectedKeys.filter(function (expectedKey) { return actualKeys.indexOf(expectedKey) === -1; }); } /** * @type {missingKeys} */ missingKeys.get = missingKeys; /** * * @param object * @param expectedKeys * @returns {boolean} */ missingKeys.has = function (object, expectedKeys) { return missingKeys(object, expectedKeys).length > 0; }; return missingKeys; }));
FIX manager using ESM in dev-kits example
module.exports = { stories: ['./stories/*.*'], webpack: async (config, { configType }) => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.(ts|tsx)$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, resolve: { ...config.resolve, extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'], }, }), managerWebpack: async config => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /manager\.js$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, }), };
module.exports = { stories: ['./stories/*.*'], webpack: async (config, { configType }) => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.(ts|tsx)$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, resolve: { ...config.resolve, extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'], }, }), };
Add fallback "UNKNOWN" notification type
package com.namelessmc.NamelessAPI; public class Notification { private final String message; private final String url; private final NotificationType type; public Notification(final String message, final String url, final NotificationType type) { this.message = message; this.url = url; this.type = type; } public String getMessage() { return this.message; } public String getUrl() { return this.url; } public NotificationType getType() { return this.type; } public static enum NotificationType { TAG, MESSAGE, LIKE, PROFILE_COMMENT, COMMENT_REPLY, THREAD_REPLY, FOLLOW, UNKNOWN; public static NotificationType fromString(final String string) { try { return NotificationType.valueOf(string.replace('-', '_').toUpperCase()); } catch (final IllegalArgumentException e) { return NotificationType.UNKNOWN; } } } }
package com.namelessmc.NamelessAPI; public class Notification { private String message; private String url; private NotificationType type; public Notification(String message, String url, NotificationType type) { this.message = message; this.url = url; this.type = type; } public String getMessage() { return message; } public String getUrl() { return url; } public NotificationType getType() { return type; } public static enum NotificationType { TAG, MESSAGE, LIKE, PROFILE_COMMENT, COMMENT_REPLY, THREAD_REPLY, FOLLOW; public static NotificationType fromString(String string) { return NotificationType.valueOf(string.replace('-', '_').toUpperCase()); } } }
Use __version__ from fuzzywuzzy package
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 SeatGeek # This file is part of fuzzywuzzy. from fuzzywuzzy import __version__ import os try: from setuptools import setup except ImportError: from distutils.core import setup def open_file(fname): return open(os.path.join(os.path.dirname(__file__), fname)) setup( name='fuzzywuzzy', version=__version__, author='Adam Cohen', author_email='adam@seatgeek.com', packages=['fuzzywuzzy'], url='https://github.com/seatgeek/fuzzywuzzy', license=open('LICENSE.txt').read(), classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ], description='Fuzzy string matching in python', long_description=open_file('README.rst').read(), zip_safe=True, )
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 SeatGeek # This file is part of fuzzywuzzy. import os try: from setuptools import setup except ImportError: from distutils.core import setup def open_file(fname): return open(os.path.join(os.path.dirname(__file__), fname)) setup( name='fuzzywuzzy', version=0.3.1, author='Adam Cohen', author_email='adam@seatgeek.com', packages=['fuzzywuzzy'], url='https://github.com/seatgeek/fuzzywuzzy', license=open('LICENSE.txt').read(), classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ], description='Fuzzy string matching in python', long_description=open_file('README.rst').read(), zip_safe=True, )
Remove this haystack setting as well.
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DEBUG = False CELERY_ALWAYS_EAGER = False MEDIA_URL = 'http://media.readthedocs.org/' ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' CACHE_BACKEND = 'memcached://localhost:11211/' SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" #HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://odin:8983/solr' SLUMBER_API_HOST = 'http://readthedocs.org' try: from local_settings import * except: pass
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DEBUG = False CELERY_ALWAYS_EAGER = False MEDIA_URL = 'http://media.readthedocs.org/' ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' CACHE_BACKEND = 'memcached://localhost:11211/' SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://odin:8983/solr' SLUMBER_API_HOST = 'http://readthedocs.org' try: from local_settings import * except: pass
Fix for jira neo 996. BP GetObject() does not return an entire object, if the original file had been blobbed. Using a bulk get per object restored. Making write channel builder create the file if it doesn't exist.
package channels import ( "io" "os" helperModels "github.com/SpectraLogic/ds3_go_sdk/helpers/models" ) // Implements the WriteChannelBuilder interface and uses a file as the WriteCloser implementation. // This channel functions as a random-access and can be used concurrently so long as two writers // are not writing to the same location within the file. type ObjectWriteChannelBuilder struct { name string } func NewWriteChannelBuilder(name string) helperModels.WriteChannelBuilder { return &ObjectWriteChannelBuilder{name:name} } func (builder *ObjectWriteChannelBuilder) IsChannelAvailable(offset int64) bool { return true } func (builder *ObjectWriteChannelBuilder) GetChannel(offset int64) (io.WriteCloser, error) { f, err := os.OpenFile(builder.name, os.O_WRONLY | os.O_CREATE, os.ModePerm) if err != nil { return nil, err } f.Seek(offset, io.SeekStart) return f, nil } func (builder *ObjectWriteChannelBuilder) OnDone(writer io.WriteCloser) { writer.Close() }
package channels import ( "io" "os" helperModels "github.com/SpectraLogic/ds3_go_sdk/helpers/models" ) // Implements the WriteChannelBuilder interface and uses a file as the WriteCloser implementation. // This channel functions as a random-access and can be used concurrently so long as two writers // are not writing to the same location within the file. type ObjectWriteChannelBuilder struct { name string } func NewWriteChannelBuilder(name string) helperModels.WriteChannelBuilder { return &ObjectWriteChannelBuilder{name:name} } func (builder *ObjectWriteChannelBuilder) IsChannelAvailable(offset int64) bool { return true } func (builder *ObjectWriteChannelBuilder) GetChannel(offset int64) (io.WriteCloser, error) { f, err := os.OpenFile(builder.name, os.O_WRONLY, defaultPermissions) if err != nil { return nil, err } f.Seek(offset, io.SeekStart) return f, nil } func (builder *ObjectWriteChannelBuilder) OnDone(writer io.WriteCloser) { writer.Close() }
Make an image of a gaussian
import numpy as np class Gaussian: """ An object of this class is a 2D elliptical gaussian """ def __init__(self): """ Constructor sets up a standard gaussian """ self.xc, self.yc, self.mass, self.width, self.q, self.theta =\ 0., 0., 1., 1., 1., 0. def evaluate(self, x, y): """ Evaluate the density. """ xx = (x - self.xc)*np.cos(self.theta) + (y - self.yc)*np.sin(self.theta) yy = -(x - self.xc)*np.sin(self.theta) + (y - self.yc)*np.cos(self.theta) rsq = self.q*xx**2 + yy**2/self.q f = np.exp(-0.5*rsq/(self.width**2)**2) f *= self.mass/(2.*np.pi*self.width**2) return f if __name__ == '__main__': import matplotlib.pyplot as plt # Set up cartesian coordinate grid x = np.linspace(-5., 5., 1001) [x, y] = np.meshgrid(x, x[::-1]) # Make a gaussian gaussian = Gaussian() gaussian.q = 0.5 gaussian.theta = 30.*np.pi/180. f = gaussian.evaluate(x, y) print(f.sum()*(x[0, 1] - x[0, 0])**2) plt.imshow(f, interpolation='nearest') plt.show()
import numpy as np class Gaussian: """ An object of this class is a 2D elliptical gaussian """ def __init__(self): """ Constructor sets up a standard gaussian """ self.xc, self.yc, self.mass, self.width, self.q, self.theta =\ 0., 0., 1., 1., 1., 0. self.cos_theta, self.sin_theta = np.cos(self.theta), np.sin(self.theta) def evaluate(self, x, y): """ Evaluate the density. """ xx = (x - self.xc)*self.cos_theta + (y - self.yc)*self.sin_theta yy = -(x - self.xc)*self.sin_theta + (y - self.yc)*self.cos_theta rsq = self.q*xx**2 + yy**2/self.q f = np.exp(-0.5*rsq/(self.width**2)**2) f *= self.mass/(2.*np.pi*self.width**2) return f if __name__ == '__main__': pass
Update social pipeline to social_core
""" A django-socialauth based client for the IX Profile server """ try: # Django 1.7+ from django.apps import AppConfig except ImportError: # Stub for old Django AppConfig = object from django.conf import settings SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'ixprofile_client.pipeline.match_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) class IXProfileClientConfig(AppConfig): """ Application configuration for the IX Profile client. """ name = 'ixprofile_client' def ready(self): """ Configure the social auth pipeline. """ settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE # pylint:disable=invalid-name default_app_config = 'ixprofile_client.IXProfileClientConfig' # pylint:enable=invalid-name
""" A django-socialauth based client for the IX Profile server """ try: # Django 1.7+ from django.apps import AppConfig except ImportError: # Stub for old Django AppConfig = object from django.conf import settings SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.social_user', 'ixprofile_client.pipeline.match_user', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', ) class IXProfileClientConfig(AppConfig): """ Application configuration for the IX Profile client. """ name = 'ixprofile_client' def ready(self): """ Configure the social auth pipeline. """ settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE # pylint:disable=invalid-name default_app_config = 'ixprofile_client.IXProfileClientConfig' # pylint:enable=invalid-name
Set the min version of skosprovider to 0.5.0 Skosprovider 0.5.0 is required because of the ProviderUnavailableException.
import os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() packages = [ 'skosprovider_heritagedata' ] requires = [ 'skosprovider>=0.5.0', 'requests', 'rdflib' ] setup( name='skosprovider_heritagedata', version='0.2.0', description='Skosprovider implementation of the heritagedata.org Vocabularies', long_description=README, packages=packages, include_package_data=True, install_requires=requires, license='MIT', zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], author='Flanders Heritage Agency', author_email='ict@onroerenderfgoed.be', url='https://github.com/OnroerendErfgoed/skosprovider_heritagedata', keywords='heritagedata.org skos skosprovider', test_suite='nose.collector' )
import os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() packages = [ 'skosprovider_heritagedata' ] requires = [ 'skosprovider', 'requests', 'rdflib' ] setup( name='skosprovider_heritagedata', version='0.2.0', description='Skosprovider implementation of the heritagedata.org Vocabularies', long_description=README, packages=packages, include_package_data=True, install_requires=requires, license='MIT', zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], author='Flanders Heritage Agency', author_email='ict@onroerenderfgoed.be', url='https://github.com/OnroerendErfgoed/skosprovider_heritagedata', keywords='heritagedata.org skos skosprovider', test_suite='nose.collector' )
[Security] Fix security.interactive_login event const doc block
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http; final class SecurityEvents { /** * The INTERACTIVE_LOGIN event occurs after a user has actively logged * into your website. It is important to distinguish this action from * non-interactive authentication methods, such as: * - authentication based on your session. * - authentication using a HTTP basic or HTTP digest header. * * The event listener method receives a * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance. * * @Event * * @var string */ const INTERACTIVE_LOGIN = 'security.interactive_login'; /** * The SWITCH_USER event occurs before switch to another user and * before exit from an already switched user. * * The event listener method receives a * Symfony\Component\Security\Http\Event\SwitchUserEvent instance. * * @Event * * @var string */ const SWITCH_USER = 'security.switch_user'; }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http; final class SecurityEvents { /** * The INTERACTIVE_LOGIN event occurs after a user is logged in * interactively for authentication based on http, cookies or X509. * * The event listener method receives a * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance. * * @Event * * @var string */ const INTERACTIVE_LOGIN = 'security.interactive_login'; /** * The SWITCH_USER event occurs before switch to another user and * before exit from an already switched user. * * The event listener method receives a * Symfony\Component\Security\Http\Event\SwitchUserEvent instance. * * @Event * * @var string */ const SWITCH_USER = 'security.switch_user'; }
Add device_key on every call in GPIO client
from rpc import RPCClient class GPIOClient(RPCClient): def __init__(self, rabbit_url): super(GPIOClient, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service') def on(self, device_key, pin_number): return self._call(device_key, {'pin': pin_number, 'action': 'on'}) def off(self, device_key, pin_number): return self._call(device_key, {'pin': pin_number, 'action': 'off'}) def read(self, device_key, pin_number): return self._call(device_key, {'pin': pin_number, 'action': 'read'}) def config(self, device_key, pin_number=None): if pin_number: return self._call(device_key, {'pin': pin_number, 'action': 'get_config'}) return self._call(device_key, {'action': 'get_config'})
from rpc import RPCClient class GPIOClient(RPCClient): def __init__(self, rabbit_url, device_key): super(GPIOClient, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key) def on(self, pin_number): return self._call({'pin': pin_number, 'action': 'on'}) def off(self, pin_number): return self._call({'pin': pin_number, 'action': 'off'}) def read(self, pin_number): return self._call({'pin': pin_number, 'action': 'read'}) def get_config(self, pin_number=None): if pin_number: return self._call({'pin': pin_number, 'action': 'get_config'}) return self._call({'action': 'get_config'})
Remove non gradable questions from the array.
import { getAllSentenceFragmentConceptResults } from './sentenceFragment'; import { getConceptResultsForSentenceCombining } from './sentenceCombining'; import { getConceptResultsForFillInTheBlanks } from './fillInTheBlanks'; export function getConceptResultsForQuestion(question) { if (question.type === 'SF') { return getAllSentenceFragmentConceptResults(question.data); } else if (question.type === 'SC') { return getConceptResultsForSentenceCombining(question.data); } else if (question.type === 'FB') { return getConceptResultsForFillInTheBlanks(question.data); } } export function getNestedConceptResultsForAllQuestions(questions) { return questions.filter(qs => qs.type !== 'TL').map(question => getConceptResultsForQuestion(question)); } export function embedQuestionNumbers(nestedConceptResultArray) { return nestedConceptResultArray.map((conceptResultArray, index) => conceptResultArray.map((conceptResult) => { conceptResult.metadata.questionNumber = index + 1; return conceptResult; })); } export function getConceptResultsForAllQuestions(questions) { const nested = getNestedConceptResultsForAllQuestions(questions); const withKeys = embedQuestionNumbers(nested); return [].concat.apply([], withKeys); }
import { getAllSentenceFragmentConceptResults } from './sentenceFragment'; import { getConceptResultsForSentenceCombining } from './sentenceCombining'; import { getConceptResultsForFillInTheBlanks } from './fillInTheBlanks'; export function getConceptResultsForQuestion(question) { if (question.type === 'SF') { return getAllSentenceFragmentConceptResults(question.data); } else if (question.type === 'SC') { return getConceptResultsForSentenceCombining(question.data); } else if (question.type === 'FB') { return getConceptResultsForFillInTheBlanks(question.data); } } export function getNestedConceptResultsForAllQuestions(questions) { return questions.map(question => getConceptResultsForQuestion(question)); } export function embedQuestionNumbers(nestedConceptResultArray) { return nestedConceptResultArray.map((conceptResultArray, index) => conceptResultArray.map((conceptResult) => { conceptResult.metadata.questionNumber = index + 1; return conceptResult; })); } export function getConceptResultsForAllQuestions(questions) { const nested = getNestedConceptResultsForAllQuestions(questions); const withKeys = embedQuestionNumbers(nested); return [].concat.apply([], withKeys); }
Update help message with watch commands
import issues from './issues' import watch from './watch' import webhooks from './webhooks' const displayHelp = (bot, message) => bot.reply(message, ` Here are some of the things I can do: - **list open tickets** — list open issues assigned to you or someone else. For \ example, to list your own issues, try \`list my open issues\`. To list issues \ for someone else try \`list open issues for George\`. - **create tickets** — I can create a new task, story, or bug for you. You \ must specify the project, type of ticket and summary. For example: \ \`create new TEST task "Add more features"\`. - **ticket status** — I can find the status of an existing ticket. You can \ ask, for example, \`what is the status of TEST-12?\`. - **comment on a ticket** - To comment on an issue, you can tell me which ticket \ and your comment: \`comment on TEST-12 "These features are important"\` - **watch a ticket** - I can notify you of changes to a particular ticket. \ To receive notifications about "TEST-12", for example, you can say \ \`start watching TEST-12\`. To stop receiving notifications, you can tell \ me to stop watching a ticket: \`stop watching TEST-12\`. To see a list of \ tickets I'm watching you can use: \`list watched tickets\`. - **help** — display this message `) export const handleJoin = (bot, message) => bot.reply(message, 'This trusty JIRA bot is here to help.') export default { displayHelp, handleJoin, issues, watch, webhooks }
import issues from './issues' import watch from './watch' import webhooks from './webhooks' const displayHelp = (bot, message) => bot.reply(message, ` Here are some of the things I can do: - **list open tickets** — list open issues assigned to you or someone else. For \ example, to list your own issues, try \`list my open issues\`. To list issues \ for someone else try \`list open issues for George\`. - **create tickets** — I can create a new task, story, or bug for you. You \ must specify the project, type of ticket and summary. For example: \ \`create new TEST task "Add more features"\`. - **ticket status** — I can find the status of an existing ticket. You can \ ask, for example, \`what is the status of TEST-12?\`. - **comment on a ticket** - To comment on an issue, you can tell me which ticket \ and your comment: \`comment on TEST-12 "These features are important"\` - **help** — display this message I'll also post notifications to ${process.env.JIRA_WEBHOOK_ROOM} \ when issues are created, assigned, or their status changes. `) export const handleJoin = (bot, message) => bot.reply(message, 'This trusty JIRA bot is here to help.') export default { displayHelp, handleJoin, issues, watch, webhooks }