text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Use path for group directly
<?php namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } }
<?php namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(function ($router) { require base_path('routes/web.php'); }); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(function ($router) { require base_path('routes/api.php'); }); } }
Fix the missing key-s warning
(function () { 'use strict'; var React = require('react'), clearingItem = function () { return React.DOM.div( {className: 'star-rating-clear-container', key: 0}, React.DOM.a({ className: 'star-rating-clear', title: 'Reset value to no stars', href: '' }, 'Clear') ); }, anchorState = function (value, props) { if (props.prospectiveValue > 0) { return (value <= props.prospectiveValue ? 'suggested' : 'off'); } return (value <= props.currentValue ? 'on' : 'off'); }, starItem = function (value, state) { return React.DOM.div( {className: 'star-rating-star-container', key: value}, React.DOM.a({ className: 'star-rating-star ' + state, title: value, href: '' }, value) ); }, starItems = function (props) { return [1, 2, 3, 4, 5].map(function (value) { return starItem(value, anchorState(value, props)); }); }; module.exports = React.createClass({ render: function () { return React.DOM.div( {className: 'star-rating-input'}, [clearingItem()].concat(starItems(this.props)) ); } }); }());
(function () { 'use strict'; var React = require('react'), clearingItem = function () { return React.DOM.div( {className: 'star-rating-clear-container', key: 's0'}, React.DOM.a({ className: 'star-rating-clear', title: 'Reset value to no stars', href: '' }, 'Clear') ); }, anchorState = function (value, props) { if (props.prospectiveValue > 0) { return (value <= props.prospectiveValue ? 'suggested' : 'off'); } return (value <= props.currentValue ? 'on' : 'off'); }, starItem = function (value, state) { return React.DOM.div( {className: 'star-rating-star-container'}, React.DOM.a({ className: 'star-rating-star ' + state, title: value, href: '', key: 's' + value }, value) ); }, starItems = function (props) { return [1, 2, 3, 4, 5].map(function (value) { return starItem(value, anchorState(value, props)); }); }; module.exports = React.createClass({ render: function () { return React.DOM.div( {className: 'star-rating-input'}, [clearingItem()].concat(starItems(this.props)) ); } }); }());
Update command to use new handle method
<?php namespace SebastiaanLuca\Migrations\Commands; use Illuminate\Database\Console\Migrations\MigrateMakeCommand; use Illuminate\Support\Composer; use SebastiaanLuca\Migrations\ExtendedMigrationCreator; class GenerateMigration extends MigrateMakeCommand { /** * The name and signature of the console command. * * @var string */ protected $signature = 'generate:migration {name : The name of the migration} {--create= : The table to be created} {--table= : The table to migrate} {--path= : The location where the migration file should be created} {--module= : The table to migrate}'; /** * The console command description. * * @var string */ protected $description = 'Generate an unbreakable migration class that uses transactional queries.'; /** * Create a new migration install command instance. * * @param \SebastiaanLuca\Migrations\ExtendedMigrationCreator $creator * @param \Illuminate\Support\Composer $composer */ public function __construct(ExtendedMigrationCreator $creator, Composer $composer) { parent::__construct($creator, $composer); } /** * Execute the console command. * * @return void */ public function handle() : void { if ($module = $this->option('module')) { $this->input->setOption('path', 'modules/' . $module . '/database/migrations'); } parent::handle(); } }
<?php namespace SebastiaanLuca\Migrations\Commands; use Illuminate\Database\Console\Migrations\MigrateMakeCommand; use Illuminate\Support\Composer; use SebastiaanLuca\Migrations\ExtendedMigrationCreator; class GenerateMigration extends MigrateMakeCommand { /** * The name and signature of the console command. * * @var string */ protected $signature = 'generate:migration {name : The name of the migration} {--create= : The table to be created} {--table= : The table to migrate} {--path= : The location where the migration file should be created} {--module= : The table to migrate}'; /** * The console command description. * * @var string */ protected $description = 'Generate an unbreakable migration class that uses transactional queries.'; /** * Create a new migration install command instance. * * @param \SebastiaanLuca\Migrations\ExtendedMigrationCreator $creator * @param \Illuminate\Support\Composer $composer */ public function __construct(ExtendedMigrationCreator $creator, Composer $composer) { parent::__construct($creator, $composer); } /** * Execute the console command. * * @return void */ public function fire() : void { if ($module = $this->option('module')) { $this->input->setOption('path', 'modules/' . $module . '/database/migrations'); } parent::fire(); } }
Change the while loop to a for loop to make the code more concise
package com.example.android.miwok; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; public class NumbersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_numbers); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Create an ArrayList containing the words for the numbers 1-10 ArrayList<String> words = new ArrayList<>(); words.add("one"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten"); // Find the root view of the layout LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView); // Create a new TextView that displays the number word at the index position and adds the // view as a child to the rootView then loops until we get to the end of the ArrayList for (int index = 0; index < words.size(); index++){ TextView wordView = new TextView(this); wordView.setText(words.get(index)); rootView.addView(wordView); } } }
package com.example.android.miwok; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; public class NumbersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_numbers); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Create an ArrayList containing the words for the numbers 1-10 ArrayList<String> words = new ArrayList<>(); words.add("one"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten"); // Find the root view of the layout LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView); // A variable which keeps track of the current index position int index = 0; // Create a new TextView that displays the number word at the index position and adds the // view as a child to the rootView until we get to the end of the ArrayList while (index < words.size()){ TextView wordView = new TextView(this); wordView.setText(words.get(index)); rootView.addView(wordView); index++; } } }
Fix pytables -> tables for pip.
from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='urbansim', version='0.2dev', description='Tool for modeling metropolitan real estate markets', author='Synthicity', author_email='[email protected]', license='AGPL', url='https://github.com/synthicity/urbansim', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', ('License :: OSI Approved :: ' 'GNU Affero General Public License v3')], packages=['synthicity'], package_data={'': ['*.py', 'urbanchoice/*.py', 'urbansim/*.py', 'urbansimd/*.py', 'utils/*.py']}, install_requires=['Django>=1.6.2', 'jinja2>=2.7.2', 'numpy>=1.8.0', 'pandas>=0.13.1', 'patsy>=0.2.1', 'scipy>=0.13.3', 'shapely>=1.3.0', 'simplejson>=3.3.3', 'statsmodels>=0.5.0', 'tables>=3.1.0'] )
from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='urbansim', version='0.2dev', description='Tool for modeling metropolitan real estate markets', author='Synthicity', author_email='[email protected]', license='AGPL', url='https://github.com/synthicity/urbansim', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', ('License :: OSI Approved :: ' 'GNU Affero General Public License v3')], packages=['synthicity'], package_data={'': ['*.py', 'urbanchoice/*.py', 'urbansim/*.py', 'urbansimd/*.py', 'utils/*.py']}, install_requires=['Django>=1.6.2', 'jinja2>=2.7.2', 'numpy>=1.8.0', 'pandas>=0.13.1', 'patsy>=0.2.1', 'pytables>=3.1.0', 'scipy>=0.13.3', 'shapely>=1.3.0', 'simplejson>=3.3.3', 'statsmodels>=0.5.0'] )
Make a test of multiple header values insensitve to their order This test sometimes failed on Python 3 because the values in the header were ordered differently - splitting them and comparing as a set should fix that.
from __future__ import unicode_literals from django_webtest import WebTest from .auth import TestUserMixin from .uk_examples import UK2015ExamplesMixin class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest): def setUp(self): super(TestCaching, self).setUp() def test_unauth_user_cache_headers(self): response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', ) headers = response.headerlist seen_cache = False for header, value in headers: if header == 'Cache-Control': seen_cache = True self.assertTrue(value == 'max-age=1200') self.assertTrue(seen_cache) def test_auth_user_cache_headers(self): response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user ) headers = response.headerlist seen_cache = False for header, value in headers: if header == 'Cache-Control': seen_cache = True values = set(value.split(', ')) self.assertEqual( values, {'no-cache', 'no-store', 'must-revalidate', 'max-age=0'} ) self.assertTrue(seen_cache)
from __future__ import unicode_literals from django_webtest import WebTest from .auth import TestUserMixin from .uk_examples import UK2015ExamplesMixin class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest): def setUp(self): super(TestCaching, self).setUp() def test_unauth_user_cache_headers(self): response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', ) headers = response.headerlist seen_cache = False for header, value in headers: if header == 'Cache-Control': seen_cache = True self.assertTrue(value == 'max-age=1200') self.assertTrue(seen_cache) def test_auth_user_cache_headers(self): response = self.app.get( '/election/2015/post/65808/dulwich-and-west-norwood', user=self.user ) headers = response.headerlist seen_cache = False for header, value in headers: if header == 'Cache-Control': seen_cache = True self.assertTrue( value == 'no-cache, no-store, must-revalidate, max-age=0' ) self.assertTrue(seen_cache)
Stop pinning tomli version for tests-require This was to work around a temporary issue with black. Pinning prevented using the latest black version, which is the first stable version.
import sys import setuptools with open("twarc/version.py") as f: exec(f.read()) with open("docs/README.md") as f: long_description = f.read() with open("requirements.txt") as f: dependencies = f.read().split() if __name__ == "__main__": setuptools.setup( name="twarc", version=version, url="https://github.com/docnow/twarc", author="Ed Summers", author_email="[email protected]", packages=["twarc"], description="Archive tweets from the command line", long_description=long_description, long_description_content_type="text/markdown", python_requires=">=3.3", install_requires=dependencies, setup_requires=["pytest-runner"], tests_require=[ "pytest", "pytest-black", "python-dotenv", "pytz", "tomli", ], entry_points={ "console_scripts": [ "twarc = twarc.command:main", "twarc2 = twarc.command2:twarc2", ] }, )
import sys import setuptools with open("twarc/version.py") as f: exec(f.read()) with open("docs/README.md") as f: long_description = f.read() with open("requirements.txt") as f: dependencies = f.read().split() if __name__ == "__main__": setuptools.setup( name="twarc", version=version, url="https://github.com/docnow/twarc", author="Ed Summers", author_email="[email protected]", packages=["twarc"], description="Archive tweets from the command line", long_description=long_description, long_description_content_type="text/markdown", python_requires=">=3.3", install_requires=dependencies, setup_requires=["pytest-runner"], tests_require=[ "pytest", "pytest-black", "python-dotenv", "pytz", "tomli<2.0.0,>=0.2.6", ], entry_points={ "console_scripts": [ "twarc = twarc.command:main", "twarc2 = twarc.command2:twarc2", ] }, )
Use Request::isMethodSafe() according to standard https://tools.ietf.org/html/rfc7231#section-4.2.1
<?php namespace Bolt\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; /** * Disable browser's XSS detection for given routes. * * These routes should still verify the request data with a CSRF token. * * @author Carson Full <[email protected]> */ class DisableXssProtectionListener implements EventSubscriberInterface { /** @var string[] */ protected $routes; /** * Constructor. * * @param string[] $routes */ public function __construct(array $routes) { $this->routes = $routes; } /** * Add X-XSS-Protection header if route matches, request is unsafe, and response has body. * * @param FilterResponseEvent $event */ public function onResponse(FilterResponseEvent $event) { $request = $event->getRequest(); if ($request->isMethodSafe(false)) { return; } $route = $request->attributes->get('_route'); if (!in_array($route, $this->routes)) { return; } $response = $event->getResponse(); if ($response->isRedirection() || $response->isEmpty() || $response->isInformational()) { return; } $response->headers->set('X-XSS-Protection', 0); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return [ KernelEvents::RESPONSE => 'onResponse', ]; } }
<?php namespace Bolt\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; /** * Disable browser's XSS detection for given routes. * * These routes should still verify the request data with a CSRF token. * * @author Carson Full <[email protected]> */ class DisableXssProtectionListener implements EventSubscriberInterface { /** @var string[] */ protected $routes; /** * Constructor. * * @param string[] $routes */ public function __construct(array $routes) { $this->routes = $routes; } /** * Add X-XSS-Protection header if route matches, request is unsafe, and response has body. * * @param FilterResponseEvent $event */ public function onResponse(FilterResponseEvent $event) { $request = $event->getRequest(); if ($request->isMethodSafe()) { return; } $route = $request->attributes->get('_route'); if (!in_array($route, $this->routes)) { return; } $response = $event->getResponse(); if ($response->isRedirection() || $response->isEmpty() || $response->isInformational()) { return; } $response->headers->set('X-XSS-Protection', 0); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return [ KernelEvents::RESPONSE => 'onResponse', ]; } }
Add more tests for Route53Client::cleanId
<?php namespace Aws\Test\Route53; use Aws\Route53\Route53Client; /** * @covers Aws\Route53\Route53Client */ class Route53ClientTest extends \PHPUnit_Framework_TestCase { public function testCleansIds() { $client = new Route53Client([ 'service' => 'route53', 'region' => 'us-west-2', 'version' => 'latest' ]); $command = $client->getCommand('ChangeResourceRecordSets', [ 'HostedZoneId' => '/hostedzone/foo', 'ChangeBatch' => [ 'Changes' => [ 'bar' => [ 'Action' => 'foo', 'ResourceRecordSet' => [ 'Name' => 'baz', 'Type' => 'abc' ] ] ] ] ]); $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); $this->assertContains('/hostedzone/foo/rrset/', $requestUri); $this->assertNotContains('/hostedzone/hostedzone', $requestUri); $command = $client->getCommand('GetReusableDelegationSet', [ 'Id' => '/delegationset/foo', ]); $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); $this->assertContains('/delegationset/foo', $requestUri); $this->assertNotContains('/delegationset/delegationset', $requestUri); $command = $client->getCommand('CreateHostedZone', [ 'Name' => 'foo', 'CallerReference' => '123', 'DelegationSetId' => '/delegationset/bar', ]); $request = \Aws\serialize($command); $this->assertContains( '<DelegationSetId>bar</DelegationSetId>', $request->getBody()->getContents() ); } }
<?php namespace Aws\Test\Route53; use Aws\Route53\Route53Client; /** * @covers Aws\Route53\Route53Client */ class Route53ClientTest extends \PHPUnit_Framework_TestCase { public function testCleansIds() { $client = new Route53Client([ 'service' => 'route53', 'region' => 'us-west-2', 'version' => 'latest' ]); $command = $client->getCommand('ChangeResourceRecordSets', [ 'HostedZoneId' => '/hostedzone/foo', 'ChangeBatch' => [ 'Changes' => [ 'bar' => [ 'Action' => 'foo', 'ResourceRecordSet' => [ 'Name' => 'baz', 'Type' => 'abc' ] ] ] ] ]); $request = \Aws\serialize($command); $this->assertContains( '/hostedzone/foo/rrset/', (string) $request->getUri() ); } }
Check result of symlink function
<?php namespace Gitonomy\Git; /** * Hooks handler. * * @author Alexandre Salomé <[email protected]> */ class Hooks { /** * @var Gitonomy\Git\Repository */ protected $repository; function __construct(Repository $repository) { $this->repository = $repository; } function has($name) { return file_exists($this->getPath($name)); } function setSymlink($name, $file) { $path = $this->getPath($name); if (file_exists($path)) { throw new \RuntimeException(sprintf('A hook "%s" is already defined', $name)); } if (false === symlink($file, $path)) { throw new \RuntimeException(sprintf('Unable to create hook "%s"', $name, $path)); } } function set($name, $content) { $path = $this->getPath($name); if (file_exists($path)) { throw new \RuntimeException(sprintf('A hook "%s" is already defined', $name)); } file_put_contents($path, $content); chmod($path, 0777); } function remove($name) { $path = $this->getPath($name); if (!file_exists($path)) { throw new \RuntimeException(sprintf('The hook "%s" was not found')); } unlink($path); } protected function getPath($name) { return $this->repository->getPath().'/hooks/'.$name; } }
<?php namespace Gitonomy\Git; /** * Hooks handler. * * @author Alexandre Salomé <[email protected]> */ class Hooks { /** * @var Gitonomy\Git\Repository */ protected $repository; function __construct(Repository $repository) { $this->repository = $repository; } function has($name) { return file_exists($this->getPath($name)); } function setSymlink($name, $file) { $path = $this->getPath($name); if (file_exists($path)) { throw new \RuntimeException(sprintf('A hook "%s" is already defined', $name)); } symlink($file, $path); } function set($name, $content) { $path = $this->getPath($name); if (file_exists($path)) { throw new \RuntimeException(sprintf('A hook "%s" is already defined', $name)); } file_put_contents($path, $content); chmod($path, 0777); } function remove($name) { $path = $this->getPath($name); if (!file_exists($path)) { throw new \RuntimeException(sprintf('The hook "%s" was not found')); } unlink($path); } protected function getPath($name) { return $this->repository->getPath().'/hooks/'.$name; } }
Handle case with empty block
# -*- coding: utf-8 -*- """antimarkdown.handlers -- Element handlers for converting HTML Elements/subtrees to Markdown text. """ from collections import deque from antimarkdown import nodes def render(*domtrees): if not domtrees: return u'' root = nodes.Root() for dom in domtrees: build_render_tree(root, dom) lines = unicode(root).rstrip().splitlines() # Strip leading empty lines while lines and not lines[0].strip(): lines.pop(0) return nodes.normalize(u'\n'.join(lines)) def build_render_tree(root, domtree): """Process an ElementTree domtree and build a render tree. """ opened = set() stack = deque([domtree]) blackboard = {} render_tree = root current_node = render_tree while stack: domtree = stack.pop() if domtree not in opened: # Open the domtree # Build the render node. node_class = getattr(nodes, domtree.tag.upper(), nodes.Node) current_node = node_class(current_node, domtree, blackboard) stack.append(domtree) # Queue children for el in reversed(domtree): stack.append(el) opened.add(domtree) else: # Close the domtree current_node = current_node.parent return root
# -*- coding: utf-8 -*- """antimarkdown.handlers -- Element handlers for converting HTML Elements/subtrees to Markdown text. """ from collections import deque from antimarkdown import nodes def render(*domtrees): if not domtrees: return u'' root = nodes.Root() for dom in domtrees: build_render_tree(root, dom) lines = unicode(root).rstrip().splitlines() # Strip leading empty lines while not lines[0].strip(): lines.pop(0) return nodes.normalize(u'\n'.join(lines)) def build_render_tree(root, domtree): """Process an ElementTree domtree and build a render tree. """ opened = set() stack = deque([domtree]) blackboard = {} render_tree = root current_node = render_tree while stack: domtree = stack.pop() if domtree not in opened: # Open the domtree # Build the render node. node_class = getattr(nodes, domtree.tag.upper(), nodes.Node) current_node = node_class(current_node, domtree, blackboard) stack.append(domtree) # Queue children for el in reversed(domtree): stack.append(el) opened.add(domtree) else: # Close the domtree current_node = current_node.parent return root
Make EntryMarkleLeafStore cater for empty db
package uk.gov.register.db; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import uk.gov.register.core.Entry; import uk.gov.verifiablelog.store.MerkleLeafStore; public class EntryMerkleLeafStore implements MerkleLeafStore { private final EntryQueryDAO entryDAO; private final EntryIteratorDAO entryIteratorDAO; private final boolean hasEntries; public EntryMerkleLeafStore(EntryQueryDAO entryDAO) { this.entryDAO = entryDAO; this.entryIteratorDAO = new EntryIteratorDAO(entryDAO); this.hasEntries = totalLeaves() > 0; } @Override public byte[] getLeafValue(int i) { return hasEntries ? bytesFromEntry(entryIteratorDAO.findByEntryNumber(i + 1)) : new byte[]{0x00}; } @Override public int totalLeaves() { return entryDAO.getTotalEntries(); } private byte[] bytesFromEntry(Entry entry) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false); String value = mapper.writeValueAsString(entry); return value.getBytes(); } catch (JsonProcessingException e) { // FIXME swallow for now and return null byte return new byte[]{0x00}; } } }
package uk.gov.register.db; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import uk.gov.register.core.Entry; import uk.gov.verifiablelog.store.MerkleLeafStore; public class EntryMerkleLeafStore implements MerkleLeafStore { private final EntryQueryDAO entryDAO; private final EntryIteratorDAO entryIteratorDAO; public EntryMerkleLeafStore(EntryQueryDAO entryDAO) { this.entryDAO = entryDAO; this.entryIteratorDAO = new EntryIteratorDAO(entryDAO); } @Override public byte[] getLeafValue(int i) { return bytesFromEntry(entryIteratorDAO.findByEntryNumber(i + 1)); } @Override public int totalLeaves() { return entryDAO.getTotalEntries(); } private byte[] bytesFromEntry(Entry entry) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false); String value = mapper.writeValueAsString(entry); return value.getBytes(); } catch (JsonProcessingException e) { // FIXME swallow for now and return null byte return new byte[]{0x00}; } } }
BAP-775: Create datagrid and pager for all results from indexer - updated datagrid interface
<?php namespace Oro\Bundle\GridBundle\Datagrid; use Sonata\AdminBundle\Datagrid\DatagridInterface as BaseDatagridInterface; use Oro\Bundle\GridBundle\Property\PropertyInterface; use Oro\Bundle\GridBundle\Sorter\SorterInterface; use Oro\Bundle\GridBundle\Route\RouteGeneratorInterface; use Oro\Bundle\GridBundle\Action\ActionInterface; interface DatagridInterface extends BaseDatagridInterface { /** * @param PropertyInterface $property * @return void */ public function addProperty(PropertyInterface $property); /** * @param SorterInterface $sorter * @return void */ public function addSorter(SorterInterface $sorter); /** * @param ActionInterface $action * @return void */ public function addRowAction(ActionInterface $action); /** * @return SorterInterface[] */ public function getSorters(); /** * @return ActionInterface[] */ public function getRowActions(); /** * @param string $name * @return null|SorterInterface */ public function getSorter($name); /** * @return RouteGeneratorInterface */ public function getRouteGenerator(); /** * @return string */ public function getName(); /** * @return string */ public function getEntityHint(); /** * @return DatagridView */ public function createView(); /** * @return array */ public function getParameters(); }
<?php namespace Oro\Bundle\GridBundle\Datagrid; use Sonata\AdminBundle\Datagrid\DatagridInterface as BaseDatagridInterface; use Oro\Bundle\GridBundle\Property\PropertyInterface; use Oro\Bundle\GridBundle\Sorter\SorterInterface; use Oro\Bundle\GridBundle\Route\RouteGeneratorInterface; use Oro\Bundle\GridBundle\Action\ActionInterface; interface DatagridInterface extends BaseDatagridInterface { /** * @param PropertyInterface $property * @return void */ public function addProperty(PropertyInterface $property); /** * @param SorterInterface $sorter * @return void */ public function addSorter(SorterInterface $sorter); /** * @param ActionInterface $action * @return void */ public function addRowAction(ActionInterface $action); /** * @return SorterInterface[] */ public function getSorters(); /** * @return ActionInterface[] */ public function getRowActions(); /** * @param string $name * @return null|SorterInterface */ public function getSorter($name); /** * @return RouteGeneratorInterface */ public function getRouteGenerator(); /** * @return string */ public function getName(); /** * @return string */ public function getEntityHint(); /** * @return DatagridView */ public function createView(); }
chore(test): Fix styleguide specs now that tabs changed
require('./spec_helper'); import StyleguideNav from '../../src/styleguide-nav'; describe('StyleguideNav', () => { beforeEach(() => { const navTree = { CSS: { eggplants: "purple.html", apples: "red.html" }, React: { carrots: "orange.html", apples: "red.html" } }; ReactDOM.render( <StyleguideNav navTree={navTree} defaultLanguage={'react'} />, root ); }); afterEach(() => { ReactDOM.unmountComponentAtNode(root); }); it('creates top-level language tabs with React first', () => { expect('.nav-tabs li:eq(0)').toContainText('React'); expect('.nav-tabs li:eq(1)').toContainText('CSS'); }); it('selects language provided as default', () => { expect('.nav-tabs li.active').toContainText('React'); }); it('creates second-level links', () => { expect(".tab-pane:eq(0)").toContainText('apples'); expect(".tab-pane:eq(0)").toContainText('carrots'); }); it('creates component links', () => { expect(".tab-pane:eq(0) a:eq(0)") .toHaveAttr('href', 'red.html'); }); });
require('./spec_helper'); import StyleguideNav from '../../src/styleguide-nav'; describe('StyleguideNav', () => { beforeEach(() => { const navTree = { CSS: { eggplants: "purple.html", apples: "red.html" }, React: { carrots: "orange.html", apples: "red.html" } }; ReactDOM.render( <StyleguideNav navTree={navTree} defaultLanguage={'react'} />, root ); }); afterEach(() => { ReactDOM.unmountComponentAtNode(root); }); it('creates top-level language tabs with React first', () => { expect('.nav-tabs li:eq(0)').toContainText('React'); expect('.nav-tabs li:eq(1)').toContainText('CSS'); }); it('selects language provided as default', () => { expect('.nav-tabs li.active').toContainText('React'); }); it('creates second-level links', () => { expect(".tab-pane:eq(0)").toContainText('apples'); expect(".tab-pane:eq(0)").toContainText('carrots'); expect(".tab-pane:eq(1)").toContainText('eggplants'); expect(".tab-pane:eq(1)").toContainText('apples'); }); it('creates component links', () => { expect(".tab-pane:eq(0) a:eq(0)") .toHaveAttr('href', 'red.html'); expect(".tab-pane:eq(1) a:eq(1)") .toHaveAttr('href', 'purple.html'); }); });
Throw AccessDeniedHttpException instead of a NotFoundHttpException.
<?php namespace Oneup\Bundle\ContaoSecurityCheckerBundle\Controller; use Oneup\Bundle\ContaoSecurityCheckerBundle\DependencyInjection\Configuration; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ApiController extends Controller { public function apiAction(Request $request) { $apiEnabled = $this->getParameter('oneup_contao_security_checker.enable_api'); $apiToken = $this->getParameter('oneup_contao_security_checker.api_key'); $composerFile = sprintf('%s/../composer.lock', $this->getParameter('kernel.root_dir')); if (!$apiEnabled) { throw new NotFoundHttpException('API is not enabled'); } if ($request->headers->get('authorization-token') === $apiToken) { if(file_exists($composerFile)) { $response = ['locks' => []]; $response['locks'][] = json_encode(file_get_contents($composerFile)); return new JsonResponse($response); } else { throw new NotFoundHttpException('No composer.lock file found on server.'); } } else { throw new AccessDeniedHttpException('API token mismatch.'); } } }
<?php namespace Oneup\Bundle\ContaoSecurityCheckerBundle\Controller; use Oneup\Bundle\ContaoSecurityCheckerBundle\DependencyInjection\Configuration; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ApiController extends Controller { public function apiAction(Request $request) { $apiEnabled = $this->getParameter('oneup_contao_security_checker.enable_api'); $apiToken = $this->getParameter('oneup_contao_security_checker.api_key'); $composerFile = sprintf('%s/../composer.lock', $this->getParameter('kernel.root_dir')); if (!$apiEnabled) { throw new NotFoundHttpException('Api is not enabled'); } if ($request->headers->get('authorization-token') === $apiToken) { if(file_exists($composerFile)) { $response = ['locks' => []]; $response['locks'][] = json_encode(file_get_contents($composerFile)); return new JsonResponse($response); } else { throw new NotFoundHttpException('No composer.lock file found on server.'); } } else { throw new NotFoundHttpException('None/incorrect API token provided.'); } } }
Set term category when fetching definition
function fetchDefinition() { var term = document.getElementById('id_term-text').value; var language = document.getElementById('id_term-language').value; var url = '/api/define.json?term=' + term + '&language=' + language; fetch(url) .then(function(response) { return response.json(); }) .then(function(data) { var definitionInput = document.getElementById('id_term-definition'); var highlightsInput = document.getElementById('id_term-highlights'); definitionInput.value = data.definition; highlightsInput.value = data.highlights; var linkButton = document.getElementById('link_button'); var occurrencesCount = document.getElementById('occurrences_count'); // If the term already exists, disable the definition and highlights // textareas and add a link to the page for viewing it. if (data.view_link) { linkButton.className = 'ui blue button'; linkButton.href = data.view_link; occurrencesCount.innerText = '(' + data.num_occurrences + ' occurrences)'; // Also set the category to 'notable'. document.getElementById('id_occurrence-category').value = '1'; } else { definitionInput.disabled = false; highlightsInput.disabled = false; linkButton.className = 'ui disabled button'; occurrencesCount.innerText = ''; } }); } $('.editable-rating').rating({ maxRating: 5, interactive: true, onRate: function(value) { $('#section_rating').val(value); } }); $('.display-rating').rating({ maxRating: 5, interactive: false, });
function fetchDefinition() { var term = document.getElementById('id_term-text').value; var language = document.getElementById('id_term-language').value; var url = '/api/define.json?term=' + term + '&language=' + language; fetch(url) .then(function(response) { return response.json(); }) .then(function(data) { var definitionInput = document.getElementById('id_term-definition'); var highlightsInput = document.getElementById('id_term-highlights'); definitionInput.value = data.definition; highlightsInput.value = data.highlights; var linkButton = document.getElementById('link_button'); var occurrencesCount = document.getElementById('occurrences_count'); // If the term already exists, disable the definition and highlights // textareas and add a link to the page for viewing it. if (data.view_link) { linkButton.className = 'ui blue button'; linkButton.href = data.view_link; occurrencesCount.innerText = '(' + data.num_occurrences + ' occurrences)'; } else { definitionInput.disabled = false; highlightsInput.disabled = false; linkButton.className = 'ui disabled button'; occurrencesCount.innerText = ''; } }); } $('.editable-rating').rating({ maxRating: 5, interactive: true, onRate: function(value) { $('#section_rating').val(value); } }); $('.display-rating').rating({ maxRating: 5, interactive: false, });
Set Guzzle 6 as Http Client And Http Message Factory.
<?php /** * Linkedin API for Laravel Framework * * @author Mauri de Souza Nunes <[email protected]> * @license https://opensource.org/licenses/MIT MIT License */ namespace Artesaos\LinkedIn; use Illuminate\Support\ServiceProvider; use Http\Adapter\Guzzle6\Client as HttpClient; use Http\Message\MessageFactory\GuzzleMessageFactory as HttpGuzzleMessageFactory; class LinkedinServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { //Publish config file if(function_exists('config_path')){ //If is not a Lumen App... $this->publishes([ __DIR__ . '/config/linkedin.php' => config_path('linkedin.php'), ]); $this->mergeConfigFrom( __DIR__ . '/config/linkedin.php','linkedin' ); } } /** * Register bindings in the container. * * @return void */ public function register() { //Bind the facade and pass api construct parameters $this->app->bind('LinkedIn', function(){ $api_key = config('linkedin.api_key'); $api_secret = config('linkedin.api_secret'); $linkedIn = new LinkedInLaravel($api_key, $api_secret); $linkedIn->setHttpClient(new HttpClient()); $linkedIn->setHttpMessageFactory(new HttpGuzzleMessageFactory()); return $linkedIn; }); } }
<?php /** * Linkedin API for Laravel Framework * * @author Mauri de Souza Nunes <[email protected]> * @license https://opensource.org/licenses/MIT MIT License */ namespace Artesaos\LinkedIn; use Illuminate\Support\ServiceProvider; class LinkedinServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { //Publish config file if(function_exists('config_path')){ //If is not a Lumen App... $this->publishes([ __DIR__ . '/config/linkedin.php' => config_path('linkedin.php'), ]); $this->mergeConfigFrom( __DIR__ . '/config/linkedin.php','linkedin' ); } } /** * Register bindings in the container. * * @return void */ public function register() { //Bind the facade and pass api construct parameters $this->app->bind('LinkedIn', function(){ $api_key = config('linkedin.api_key'); $api_secret = config('linkedin.api_secret'); return new LinkedInLaravel($api_key, $api_secret); }); } }
Fix bug in getPrefFast (first time use)
/* global sauce */ /* Just add some client side caching to the proxy calls. */ sauce.ns('storage', ns => { 'use strict'; let _prefs; let _prefsCache = new Map(); let _fastPrefsReadyInvoked; // catch API misuse with this. const _fastPrefInit = (async () => { if (!sauce.proxy.isConnected) { await sauce.proxy.connected; } _prefs = await sauce.storage.get('preferences'); })(); async function fastPrefsReady() { if (_prefs === undefined) { await _fastPrefInit; } return (_fastPrefsReadyInvoked = true); } function getPrefFast(path) { if (_fastPrefsReadyInvoked !== true) { throw new TypeError('initFastPrefs() call is requried'); } if (!_prefsCache.has(path)) { let ref = _prefs || {}; for (const key of path.split('.')) { ref = ref[key]; if (ref == null) { break; } } _prefsCache.set(path, ref); } return _prefsCache.get(path); } async function setPref(path, value) { _prefsCache.set(path, value); return await ns._setPref(path, value); } return { fastPrefsReady, getPrefFast, setPref, }; });
/* global sauce */ /* Just add some client side caching to the proxy calls. */ sauce.ns('storage', ns => { 'use strict'; let _prefs; let _prefsCache = new Map(); let _fastPrefsReadyInvoked; // catch API misuse with this. const _fastPrefInit = (async () => { if (!sauce.proxy.isConnected) { await sauce.proxy.connected; } _prefs = await sauce.storage.get('preferences'); })(); async function fastPrefsReady() { if (_prefs === undefined) { await _fastPrefInit; } return (_fastPrefsReadyInvoked = true); } function getPrefFast(path) { if (_fastPrefsReadyInvoked !== true) { throw new TypeError('initFastPrefs() call is requried'); } if (!_prefsCache.has(path)) { let ref = _prefs || {}; for (const key of path.split('.')) { ref = ref[key]; if (ref[key] == null) { break; } } _prefsCache.set(path, ref); } return _prefsCache.get(path); } async function setPref(path, value) { _prefsCache.set(path, value); return await ns._setPref(path, value); } return { fastPrefsReady, getPrefFast, setPref, }; });
Set publish and trashed state
(function () { 'use strict'; function RelatedLinksAppController($scope) { var vm = this; vm.relations = $scope.model.viewModel; var currentVariant = _.find($scope.content.variants, function (v) { return v.active }); if (currentVariant.language) { vm.culture = currentVariant.language.culture; vm.cultureRelations = _.filter(vm.relations, function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() }); } else { vm.cultureRelations = vm.relations; } vm.ungrouped = []; for (var i = 0; i < vm.cultureRelations.length; i++) { var relation = vm.cultureRelations[i]; for (var j = 0; j < relation.Properties.length; j++) { vm.ungrouped.push({ id: relation.Id, name: relation.Name, propertyname: relation.Properties[j].PropertyName, tabname: relation.Properties[j].TabName, published: relation.IsPublished, trashed: relation.IsTrashed }); } } } angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController', [ '$scope', 'editorState', 'localizationService', RelatedLinksAppController ]); })();
(function () { 'use strict'; function RelatedLinksAppController($scope) { var vm = this; vm.relations = $scope.model.viewModel; var currentVariant = _.find($scope.content.variants, function (v) { return v.active }); if (currentVariant.language) { vm.culture = currentVariant.language.culture; vm.cultureRelations = _.filter(vm.relations, function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() }); } else { vm.cultureRelations = vm.relations; } vm.ungrouped = []; for (var i = 0; i < vm.cultureRelations.length; i++) { var relation = vm.cultureRelations[i]; for (var j = 0; j < relation.Properties.length; j++) { vm.ungrouped.push({ id: relation.Id, name: relation.Name, propertyname: relation.Properties[j].PropertyName, tabname: relation.Properties[j].TabName }); } } } angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController', [ '$scope', 'editorState', 'localizationService', RelatedLinksAppController ]); })();
[QUEUE] Add tags list on queues
<?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->arrayNode('tags') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
<?php namespace WorkerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('worker'); $rootNode ->children() ->arrayNode('providers') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('class')->isRequired()->end() ->arrayNode('arguments') ->defaultValue(array()) ->performNoDeepMerging() ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('queues') ->useAttributeAsKey('key') ->prototype('array') ->children() ->scalarNode('name')->isRequired()->end() ->scalarNode('provider')->isRequired()->end() ->end() ->end() ->end() ; return $treeBuilder; } }
Use new services for retreiving the Project and Entry
var trexControllers = angular.module('trexControllers', []); trexControllers.controller('ProjectListCtrl', ['$scope', 'Project', function($scope, Project) { $scope.projects = Project.query(); $scope.order = "name"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]); trexControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', 'Project', function($scope, $routeParams, Project) { $scope.project = Project.get({projectId: $routeParams.id}); $scope.entries = Project.entries({projectId: $routeParams.id}); // $http.get('/api/1/projects/' + $routeParams.id + "/entries").success( // function(data) { // }); $scope.order = "id"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]);
var trexControllers = angular.module('trexControllers', []); trexControllers.controller('ProjectListCtrl', ['$scope', '$http', function($scope, $http) { $http.get('/api/1/projects/').success(function(data) { $scope.projects = data; }); $scope.order = "name"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]); trexControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { $http.get('/api/1/projects/' + $routeParams.id).success(function(data) { $scope.project = data; }); $http.get('/api/1/projects/' + $routeParams.id + "/entries").success( function(data) { $scope.entries = data; }); $scope.order = "name"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]);
Make sure LOG is defined before using it.
"""A virtual serial port data source.""" from __future__ import absolute_import import logging from .base import BytestreamDataSource, DataSourceError LOG = logging.getLogger(__name__) try: import serial except ImportError: LOG.debug("serial library not installed, can't use serial interface") class SerialDataSource(BytestreamDataSource): """A data source reading from a serial port, which could be implemented with a USB to Serial or Bluetooth adapter. """ DEFAULT_PORT = "/dev/ttyUSB0" DEFAULT_BAUDRATE = 115200 def __init__(self, callback=None, port=None, baudrate=None): """Initialize a connection to the serial device. Kwargs: port - optionally override the default virtual COM port baudrate - optionally override the default baudrate Raises: DataSourceError if the serial device cannot be opened. """ super(SerialDataSource, self).__init__(callback) port = port or self.DEFAULT_PORT baudrate = baudrate or self.DEFAULT_BAUDRATE try: self.device = serial.Serial(port, baudrate, rtscts=True) except serial.SerialException as e: raise DataSourceError("Unable to open serial device at port " "%s: %s" % (port, e)) else: LOG.debug("Opened serial device at %s", port) def _read(self): return self.device.readline()
"""A virtual serial port data source.""" from __future__ import absolute_import import logging try: import serial except ImportError: LOG.debug("serial library not installed, can't use serial interface") from .base import BytestreamDataSource, DataSourceError LOG = logging.getLogger(__name__) class SerialDataSource(BytestreamDataSource): """A data source reading from a serial port, which could be implemented with a USB to Serial or Bluetooth adapter. """ DEFAULT_PORT = "/dev/ttyUSB0" DEFAULT_BAUDRATE = 115200 def __init__(self, callback=None, port=None, baudrate=None): """Initialize a connection to the serial device. Kwargs: port - optionally override the default virtual COM port baudrate - optionally override the default baudrate Raises: DataSourceError if the serial device cannot be opened. """ super(SerialDataSource, self).__init__(callback) port = port or self.DEFAULT_PORT baudrate = baudrate or self.DEFAULT_BAUDRATE try: self.device = serial.Serial(port, baudrate, rtscts=True) except serial.SerialException as e: raise DataSourceError("Unable to open serial device at port " "%s: %s" % (port, e)) else: LOG.debug("Opened serial device at %s", port) def _read(self): return self.device.readline()
Add snippet fetching to HEAD
/* jshint node: true */ 'use strict'; var fs = require('fs'); var path = require('path'); function readSnippet() { try { // NOTE: expecting addon as a node_module on parent addon or in an Ember CLI application. return fs.readFileSync(path.join(process.cwd(), 'node_modules/ember-segmentio/vendor/snippet-core.min.js'), { encoding: 'UTF-8' }); } catch(error) { if (error.code === 'ENOENT') { return ''; } else { throw error; } } } module.exports = { name: 'ember-segmentio', contentFor: function(type, config) { var content = ''; var coreSnippet = readSnippet(); var enabled = config.SEGMENTIO_KEY && coreSnippet; if (!config.SEGMENTIO_KEY) { console.warn('ember-segmentio: Not enabled missing key "SEGMENTIO_KEY" in parent application/addon.'); } if (!coreSnippet) { console.warn('ember-segmentio: Error while reading snippet.'); } if (enabled && type === 'head') { content = [ '<script type="text/javascript">', '(function(){', coreSnippet, 'analytics.load("', config.SEGMENTIO_KEY, '");', 'analytics.page()', '})();', '</script>' ].join(''); } return content; } };
/* jshint node: true */ 'use strict'; var fs = require('fs'); var path = require('path'); function readSnippet() { try { // NOTE: expecting addon as a node_module on parent addon or in an Ember CLI application. return fs.readFileSync(path.join(process.cwd(), 'node_modules/ember-segmentio/vendor/snippet-core.min.js'), { encoding: 'UTF-8' }); } catch(error) { if (error.code === 'ENOENT') { return ''; } else { throw error; } } } module.exports = { name: 'ember-segmentio', contentFor: function(type, config) { var content = ''; var coreSnippet = readSnippet(); var enabled = config.SEGMENTIO_KEY && coreSnippet; if (!config.SEGMENTIO_KEY) { console.warn('ember-segmentio: Not enabled missing key "SEGMENTIO_KEY" in parent application/addon.'); } if (!coreSnippet) { console.warn('ember-segmentio: Error while reading snippet.'); } if (enabled && type === 'head') { content = [ '<script type="text/javascript">', '!function(){', coreSnippet, 'analytics.load("', config.SEGMENTIO_KEY, '");', 'analytics.page()', '}();', '</script>' ].join(''); } return content; } };
Split into own method for clariy and "return" support
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save()
Rename the date field related to the project status
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
[page] Add mixin for the cartridge
var isFunction = require('lodash/lang/isFunction'); var dispatcher = require('focus').dispatcher; module.exports = { /** * Register the cartridge. */ _registerCartridge: function registerCartridge(){ this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration; if(!isFunction(this.cartridgeConfiguration)){ this.cartridgeConfiguration = function cartridgeConfiguration(){ return {}; }; console.warn(` Your detail page does not have any cartrige configuration, this is not mandarory but recommended. It should be a component attribute return by a function. function cartridgeConfiguration(){ var cartridgeConfiguration = { summary: {component: "A React Component", props: {id: this.props.id}}, cartridge: {component: "A React Component"}, actions: {components: "react actions"} }; return cartridgeConfiguration; } `); } var cartridgeConf = this.cartridgeConfiguration(); dispatcher.handleViewAction({ data: { cartridgeComponent: cartridgeConf.cartridge, summaryComponent: cartridgeConf.summary, actions: cartridgeConf.actions }, type: 'update' }); }, componentWillMount: function pageMixinWillMount(){ this._registerCartridge(); } };
var isFunction = require('lodash/lang/isFunction'); var dispatcher = require('focus').dispatcher; module.exports = { /** * Register the cartridge. */ _registerCartridge: function registerCartridge(){ if(!isFunction(this.cartridgeConfiguration)){ this.cartridgeConfiguration = function cartridgeConfiguration(){ return {}; }; console.warn(` Your detail page does not have any cartrige configuration, this is not mandarory but recommended. It should be a component attribute return by a function. function cartridgeConfiguration(){ var cartridgeConfiguration = { summary: {component: "A React Component", props: {id: this.props.id}}, cartridge: {component: "A React Component"}, actions: {components: "react actions"} }; return cartridgeConfiguration; } `); } var cartridgeConf = this.cartridgeConfiguration(); dispatcher.handleViewAction({ data: { cartridgeComponent: cartridgeConf.cartridge, summaryComponent: cartridgeConf.summary, actions: cartridgeConf.actions }, type: 'update' }); }, componentWillMount: function pageMixinWillMount(){ this._registerCartridge(); } };
Use identity operator when comparing with None
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from libthumbor import CryptoURL class ThumborService(object): def __init__(self, baseurl='http://localhost:8888/', secretkey='MY_SECURE_KEY'): self.baseurl = baseurl.rstrip('/') self._urlgen = CryptoURL(key=secretkey) def generate_url(self, options): return self.baseurl + self._urlgen.generate(**options) class ThumborUrlGenerator(object): def __init__(self, service, key='content_url', destkey='thumbnail', options=None, optionskey=None): self.service = service self.key = key self.destkey = destkey self.options = options self.optionskey = optionskey if not (self.options is None) ^ (self.optionskey is None): raise ValueError('Either options or optionskey is required') def __call__(self, item, send): for oid in item['inserts']: if self.options: options = self.options.copy() else: options = item['data'][oid][self.optionskey].copy() options['image_url'] = item['data'][oid][self.key] item['data'][oid][self.destkey] = self.service.generate_url(options) send(item, self) @property def dependencies(self): yield (self, self.service)
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from libthumbor import CryptoURL class ThumborService(object): def __init__(self, baseurl='http://localhost:8888/', secretkey='MY_SECURE_KEY'): self.baseurl = baseurl.rstrip('/') self._urlgen = CryptoURL(key=secretkey) def generate_url(self, options): return self.baseurl + self._urlgen.generate(**options) class ThumborUrlGenerator(object): def __init__(self, service, key='content_url', destkey='thumbnail', options=None, optionskey=None): self.service = service self.key = key self.destkey = destkey self.options = options self.optionskey = optionskey if not (self.options == None) ^ (self.optionskey == None): raise ValueError('Either options or optionskey is required') def __call__(self, item, send): for oid in item['inserts']: if self.options: options = self.options.copy() else: options = item['data'][oid][self.optionskey].copy() options['image_url'] = item['data'][oid][self.key] item['data'][oid][self.destkey] = self.service.generate_url(options) send(item, self) @property def dependencies(self): yield (self, self.service)
Fix in how the contents is determined.
define(function (require, exports, module) { 'use strict'; var Mode = require("../../mode").Mode; var util = require("../../util"); var oop = require("../../oop"); var GenericDecorator = require("./generic_decorator").GenericDecorator; var tr = require("./generic_tr").tr; function GenericMode () { Mode.call(this); this._resolver = new util.NameResolver(); } oop.inherit(GenericMode, Mode); (function () { // Modes must override this. this.getAbsoluteResolver = function () { return this._resolver; }; this.makeDecorator = function () { var obj = Object.create(GenericDecorator.prototype); // Make arg an array and add our extra argument(s). var args = Array.prototype.slice.call(arguments); args.unshift(this); GenericDecorator.apply(obj, args); return obj; }; this.getTransformationRegistry = function () { return tr; }; this.getContextualMenuItems = function () { return []; }; this.nodesAroundEditableContents = function (parent) { var ret = [null, null]; var start = parent.childNodes[0]; if ($(start).is("._gui._start_button")) ret[0] = start; var end = parent.childNodes[parent.childNodes.length - 1]; if ($(end).is("._gui._end_button")) ret[1] = end; return ret; }; }).call(GenericMode.prototype); exports.Mode = GenericMode; });
define(function (require, exports, module) { 'use strict'; var Mode = require("../../mode").Mode; var util = require("../../util"); var oop = require("../../oop"); var GenericDecorator = require("./generic_decorator").GenericDecorator; var tr = require("./generic_tr").tr; function GenericMode () { Mode.call(this); this._resolver = new util.NameResolver(); } oop.inherit(GenericMode, Mode); (function () { // Modes must override this. this.getAbsoluteResolver = function () { return this._resolver; }; this.makeDecorator = function () { var obj = Object.create(GenericDecorator.prototype); // Make arg an array and add our extra argument(s). var args = Array.prototype.slice.call(arguments); args.unshift(this); GenericDecorator.apply(obj, args); return obj; }; this.getTransformationRegistry = function () { return tr; }; this.getContextualMenuItems = function () { return []; }; this.nodesAroundEditableContents = function (parent) { var ret = [null, null]; var start = parent.childNodes[0]; if ($(start).is("._gui._start_button")) ret[0] = start; var end = parent.childNodes[parent.childNodes.length - 1]; if ($(end).is("_gui.start_button")) ret[1] = end; return ret; }; }).call(GenericMode.prototype); exports.Mode = GenericMode; });
Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
Fix issue with not using upgraded history object
import React from 'react' import { merge } from 'lodash' import { Router as ReactRouter, RouterContext, browserHistory, createMemoryHistory, match } from 'react-router' import { syncHistoryWithStore, routerReducer } from 'react-router-redux' export { Route, IndexRoute, Redirect, IndexRedirect, Link, IndexLink, } from 'react-router' export renderer from './renderer' export default Router export class Router { static defaults = { routes: [] }; constructor(opts) { this.options = merge({}, Router.defaults, opts) this.routes = this.options.routes } registerStore(store) { this.history = syncHistoryWithStore(this.history, store) } getReducer() { return routerReducer } getComponent(renderProps, client = false) { return client ? <ReactRouter {...renderProps} /> : <RouterContext {...renderProps} /> } match(req, callback) { if (arguments.length === 1 && typeof req === 'function') { callback = req req = null } return match(this.createMatchOptions(req), callback) } createMatchOptions(req) { const opts = { routes: this.routes } if (req) { opts.history = createMemoryHistory() opts.location = req.url } else { opts.history = browserHistory } this.history = opts.history return opts } }
import React from 'react' import { merge } from 'lodash' import { Router as ReactRouter, RouterContext, browserHistory, createMemoryHistory, match } from 'react-router' import { syncHistoryWithStore, routerReducer } from 'react-router-redux' export { Route, IndexRoute, Redirect, IndexRedirect, Link, IndexLink, } from 'react-router' export renderer from './renderer' export default Router export class Router { static defaults = { routes: [] }; constructor(opts) { this.options = merge({}, Router.defaults, opts) this.routes = this.options.routes } registerStore(store) { syncHistoryWithStore(this.history, store) } getReducer() { return routerReducer } getComponent(renderProps, client = false) { return client ? <ReactRouter {...renderProps} /> : <RouterContext {...renderProps} /> } match(req, callback) { if (arguments.length === 1 && typeof req === 'function') { callback = req req = null } return match(this.createMatchOptions(req), callback) } createMatchOptions(req) { const opts = { routes: this.routes } if (req) { opts.history = createMemoryHistory() opts.location = req.url } else { opts.history = browserHistory } this.history = opts.history return opts } }
Use require for views instead of require_once
<?php class DbconfigController extends ControllerBase { protected function dbInit() {} public function create( $user, $pass, $dbname ) { $entries = compact( 'user', 'pass', 'dbname' ); $entries = [ 'db' => $entries ]; try { updateConfig( $entries, $this->environment ); go(); } catch ( FileNotWritableException $e ) { $content = $e->content; require 'views/database/notwritable.php'; } } public function createView( $error, $dbSaid ) { global $config; $oldConfig = [ 'db' => [ 'user' => '', 'pass' => '', 'dbname' => '' ] ]; $oldConfig = array_replace_recursive( $oldConfig, $config ); require 'views/database/create.php'; } } ?>
<?php class DbconfigController extends ControllerBase { protected function dbInit() {} public function create( $user, $pass, $dbname ) { $entries = compact( 'user', 'pass', 'dbname' ); $entries = [ 'db' => $entries ]; try { updateConfig( $entries, $this->environment ); go(); } catch ( FileNotWritableException $e ) { $content = $e->content; require_once 'views/database/notwritable.php'; } } public function createView( $error, $dbSaid ) { global $config; $oldConfig = [ 'db' => [ 'user' => '', 'pass' => '', 'dbname' => '' ] ]; $oldConfig = array_replace_recursive( $oldConfig, $config ); require_once 'views/database/create.php'; } } ?>
Select the only suggestion when hit enter key
var Tutu = Tutu || (function() { function removeSuggestionMenu() { var cmdSegs = $('#mesage-input').val().split(); var suggestions = $('div.tt-menu div.tt-suggestion>strong'); if(suggestions.length == 1) { var lastCmdSeg = cmdSegs[cmdSegs.length - 1]; var suggestion = lastCmdSeg == suggestions.text(); // TODO: select it } } function initHotkeyBindings() { var msg_box = $('#message-input')[0]; Mousetrap(msg_box).bind('enter', function(e) { var suggestion_menu_visible = $('div.tt-menu').is(":visible"); removeSuggestionMenu(); if (suggestion_menu_visible) { console.log("menu is visible, ignore logic here"); return false; } console.log('# TODO: submit the command'); }); } function initTypeahead() { var commands = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '/api/commands' }); $('.typeahead').typeahead({ hint: true, highlight: true, minLength: 1, menuConfig: { position: 'top' } }, { name: 'commands', display: 'name', source: commands, templates: { header: '<h3 class="suggestion-menu">Commands</h3>' } } ); } function initFocus() { $('#message-input').focus(); } $(function() { initHotkeyBindings(); initTypeahead(); initFocus(); }); // API return {}; })();
var Tutu = Tutu || (function() { function initHotkeyBindings() { var msg_box = $('#message-input')[0]; Mousetrap(msg_box).bind('enter', function(e) { var suggestion_menu_visible = $('div.tt-menu').is(":visible"); if (suggestion_menu_visible) { console.log("menu is visible, ignore logic here"); return false; } console.log('# TODO: submit the command'); }); } function initTypeahead() { var commands = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '/api/commands' }); $('.typeahead').typeahead({ hint: true, highlight: true, minLength: 1, menuConfig: { position: 'top' } }, { name: 'commands', display: 'name', source: commands, templates: { header: '<h3 class="suggestion-menu">Commands</h3>' } } ); } function initFocus() { $('#message-input').focus(); } $(function() { initHotkeyBindings(); initTypeahead(); initFocus(); }); // API return {}; })();
Remove reference to butter since butter is deprecated
''' Return data to a mongodb server Required python modules: pymongo ''' import logging try: import pymongo has_pymongo = True except ImportError: has_pymongo = False log = logging.getLogger(__name__) __opts__ = {'mongo.db': 'salt', 'mongo.host': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': ''} def __virtual__(): if not has_pymongo: return False return 'mongo_return' def returner(ret): ''' Return data to a mongodb server ''' conn = pymongo.Connection(__opts__['mongo.host'], __opts__['mongo.port']) db = conn[__opts__['mongo.db']] user = __opts__.get('mongo.user') password = __opts__.get('mongo.password') if user and password: db.authenticate(user, password) col = db[ret['id']] back = {} if isinstance(ret['return'], dict): for key in ret['return']: back[key.replace('.', '-')] = ret['return'][key] else: back = ret['return'] log.debug(back) col.insert({ret['jid']: back})
''' Return data to a mongodb server This is the default interface for returning data for the butter statd subsytem Required python modules: pymongo ''' import logging try: import pymongo has_pymongo = True except ImportError: has_pymongo = False log = logging.getLogger(__name__) __opts__ = {'mongo.db': 'salt', 'mongo.host': 'salt', 'mongo.password': '', 'mongo.port': 27017, 'mongo.user': ''} def __virtual__(): if not has_pymongo: return False return 'mongo_return' def returner(ret): ''' Return data to a mongodb server ''' conn = pymongo.Connection(__opts__['mongo.host'], __opts__['mongo.port']) db = conn[__opts__['mongo.db']] user = __opts__.get('mongo.user') password = __opts__.get('mongo.password') if user and password: db.authenticate(user, password) col = db[ret['id']] back = {} if isinstance(ret['return'], dict): for key in ret['return']: back[key.replace('.', '-')] = ret['return'][key] else: back = ret['return'] log.debug(back) col.insert({ret['jid']: back})
Add the "Production" trove classifier.
import sys from setuptools import setup, find_packages extra_setup = {} if sys.version_info >= (3,): extra_setup['use_2to3'] = True setup( name='blessings', version='1.2', description='A thin, practical wrapper around terminal formatting, positioning, and more', long_description=open('README.rst').read(), author='Erik Rose', author_email='[email protected]', license='MIT', packages=find_packages(exclude=['ez_setup']), tests_require=['Nose'], url='https://github.com/erikrose/blessings', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: User Interfaces', 'Topic :: Terminals' ], keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'color', 'console'], **extra_setup )
import sys from setuptools import setup, find_packages extra_setup = {} if sys.version_info >= (3,): extra_setup['use_2to3'] = True setup( name='blessings', version='1.2', description='A thin, practical wrapper around terminal formatting, positioning, and more', long_description=open('README.rst').read(), author='Erik Rose', author_email='[email protected]', license='MIT', packages=find_packages(exclude=['ez_setup']), tests_require=['Nose'], url='https://github.com/erikrose/blessings', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: User Interfaces', 'Topic :: Terminals' ], keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'color', 'console'], **extra_setup )
Add year to miner table to make it sort properly.
@extends('layouts.master') @section('title', 'Miners') @section('content') <div class="row"> <div class="col-12"> <table id="miners"> <thead> <th>Miner</th> <th>Corporation</th> <th class="numeric">Amount owed</th> <th class="numeric">Total payments</th> <th>Last payment</th> </thead> <tbody> @foreach ($miners as $miner) <tr> <td><a href="/miners/{{ $miner->eve_id }}">{{ $miner->name }}</a></td> <td>{{ $miner->corporation->name }}</td> <td class="numeric">{{ number_format($miner->amount_owed, 0) }}</td> <td class="numeric">{{ number_format($miner->total_payments, 0) }}</td> <td> @if (isset($miner->latest_payment)) {{ date('M j, Y', strtotime($miner->latest_payment)) }} @endif </td> </tr> @endforeach </tbody> </table> </div> </div> <script> window.addEventListener('load', function () { $('#miners').tablesorter(); $('#miners tr').on('click', function () { $(this).find('a')[0].click(); }); }); </script> @endsection
@extends('layouts.master') @section('title', 'Miners') @section('content') <div class="row"> <div class="col-12"> <table id="miners"> <thead> <th>Miner</th> <th>Corporation</th> <th class="numeric">Amount owed</th> <th class="numeric">Total payments</th> <th>Last payment</th> </thead> <tbody> @foreach ($miners as $miner) <tr> <td><a href="/miners/{{ $miner->eve_id }}">{{ $miner->name }}</a></td> <td>{{ $miner->corporation->name }}</td> <td class="numeric">{{ number_format($miner->amount_owed, 0) }}</td> <td class="numeric">{{ number_format($miner->total_payments, 0) }}</td> <td> @if (isset($miner->latest_payment)) {{ date('M j', strtotime($miner->latest_payment)) }} @endif </td> </tr> @endforeach </tbody> </table> </div> </div> <script> window.addEventListener('load', function () { $('#miners').tablesorter(); $('#miners tr').on('click', function () { $(this).find('a')[0].click(); }); }); </script> @endsection
Add changes requested in PR.
/* * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.tools.codestyle; import java.nio.file.Path; /** * Class that represent java file extension. * * @author Alexander Aleksandrov */ public final class JavaSources { private static final String JAVA_FILE_EXTENSION = ".java"; private JavaSources() { // Prevent initialization of this utility class } /** * Returns the java file extension string constant. * * @return ".java" string */ public static String javaExt() { return JAVA_FILE_EXTENSION; } public static boolean isJavaFile(Path path) { return path.toString() .endsWith(javaExt()); } }
/* * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.tools.codestyle; import java.nio.file.Path; /** * This is a string constants keeper class. * * @author Alexander Aleksandrov */ public final class JavaSources { private static final String JAVA_FILE_EXTENSION = ".java"; private JavaSources() { // Prevent initialization of this utility class } /** * Returns the java file extension string constant. * * @return ".java" string */ public static String javaExt() { return JAVA_FILE_EXTENSION; } public static boolean isJavaFile(Path path) { return path.toString() .endsWith(javaExt()); } }
Use the DObjectFactory to move DObjects over the wire. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@7 542714f4-19e9-0310-aa3c-eee0fc999fb1
// // $Id: ObjectResponse.java,v 1.3 2001/05/29 03:28:50 mdb Exp $ package com.samskivert.cocktail.cher.net; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import com.samskivert.cocktail.cher.dobj.DObject; import com.samskivert.cocktail.cher.dobj.DObjectFactory; public class ObjectResponse extends DownstreamMessage { /** The code for an event notification. */ public static final short TYPE = TYPE_BASE + 2; /** * Zero argument constructor used when unserializing an instance. */ public ObjectResponse () { super(); } /** * Constructs an object response with supplied distributed object that * is associated with the specified upstream message id. */ public ObjectResponse (short messageId, DObject dobj) { this.messageId = messageId; _dobj = dobj; } public short getType () { return TYPE; } public void writeTo (DataOutputStream out) throws IOException { super.writeTo(out); out.writeShort(messageId); DObjectFactory.writeTo(out, _dobj); } public void readFrom (DataInputStream in) throws IOException { super.readFrom(in); messageId = in.readShort(); _dobj = (DObject)DObjectFactory.readFrom(in); } /** The object which is associated with this response. */ protected DObject _dobj; }
// // $Id: ObjectResponse.java,v 1.2 2001/05/23 04:03:40 mdb Exp $ package com.samskivert.cocktail.cher.net; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import com.samskivert.cocktail.cher.dobj.DObject; import com.samskivert.cocktail.cher.io.TypedObjectFactory; public class ObjectResponse extends DownstreamMessage { /** The code for an event notification. */ public static final short TYPE = TYPE_BASE + 2; /** * Zero argument constructor used when unserializing an instance. */ public ObjectResponse () { super(); } /** * Constructs an object response with supplied distributed object that * is associated with the specified upstream message id. */ public ObjectResponse (short messageId, DObject dobj) { this.messageId = messageId; _dobj = dobj; } public short getType () { return TYPE; } public void writeTo (DataOutputStream out) throws IOException { super.writeTo(out); out.writeShort(messageId); TypedObjectFactory.writeTo(out, _dobj); } public void readFrom (DataInputStream in) throws IOException { super.readFrom(in); messageId = in.readShort(); _dobj = (DObject)TypedObjectFactory.readFrom(in); } /** The object which is associated with this response. */ protected DObject _dobj; }
Fix CORS when running the api server with Docker
"""This module contains basic functions to instantiate the BigchainDB API. The application is implemented in Flask and runs using Gunicorn. """ import os from flask import Flask from flask.ext.cors import CORS from server.lib.api.views import api_views def create_app(debug): """Return an instance of the Flask application. Args: debug (bool): a flag to activate the debug mode for the app (default: False). """ app = Flask(__name__) CORS(app, origins=("^(https?://)?(www\.)?(" + os.environ.get('DOCKER_MACHINE_IP', 'localhost') + "|0|0.0.0.0|dimi-bat.local|localhost|127.0.0.1)(\.com)?:\d{1,5}$"), headers=( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken', 'withcredentials', 'cache-control', 'cookie', 'session-id', ), supports_credentials=True, ) app.debug = debug app.register_blueprint(api_views, url_prefix='/api') return app if __name__ == '__main__': app = create_app(debug=True) app.run(host=os.environ.get('FLASK_HOST', '127.0.0.1'), port=os.environ.get('FLASK_PORT', 8000)) app.run()
"""This module contains basic functions to instantiate the BigchainDB API. The application is implemented in Flask and runs using Gunicorn. """ import os from flask import Flask from flask.ext.cors import CORS from server.lib.api.views import api_views def create_app(debug): """Return an instance of the Flask application. Args: debug (bool): a flag to activate the debug mode for the app (default: False). """ app = Flask(__name__) CORS(app, origins=("^(https?://)?(www\.)?(" + os.environ.get('DOCKER_MACHINE_IP', 'localhost') + "0|0.0.0.0|dimi-bat.local|localhost|127.0.0.1)(\.com)?:\d{1,5}$"), headers=( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken', 'withcredentials', 'cache-control', 'cookie', 'session-id', ), supports_credentials=True, ) app.debug = debug app.register_blueprint(api_views, url_prefix='/api') return app if __name__ == '__main__': app = create_app(debug=True) app.run(host=os.environ.get('FLASK_HOST', '127.0.0.1'), port=os.environ.get('FLASK_PORT', 8000)) app.run()
Hide documentation commands in non-python scope
# -*- coding: utf-8 -*- import sublime import sublime_plugin from .utils import ask_daemon, PythonCommandMixin class HelpMessageCommand(sublime_plugin.TextCommand): def run(self, edit, docstring): self.view.close() self.view.insert(edit, self.view.size(), docstring) class SublimeJediDocstring(PythonCommandMixin, sublime_plugin.TextCommand): """ Show doctring in output panel """ def run(self, edit): ask_daemon(self.view, self.show_docstring, 'docstring') def show_docstring(self, view, docstring): window = sublime.active_window() if docstring: output = window.get_output_panel('help_panel') output.set_read_only(False) output.run_command('help_message', {'docstring': docstring}) output.set_read_only(True) window.run_command("show_panel", {"panel": "output.help_panel"}) else: window.run_command("hide_panel", {"panel": "output.help_panel"}) sublime.status_message('Jedi: No results!') class SublimeJediSignature(PythonCommandMixin, sublime_plugin.TextCommand): """ Show signature in statusbar """ def run(self, edit): ask_daemon(self.view, self.show_signature, 'signature') def show_signature(self, view, signature): if signature: sublime.status_message('Jedi: {0}'.format(signature))
# -*- coding: utf-8 -*- import sublime import sublime_plugin from .utils import ask_daemon class HelpMessageCommand(sublime_plugin.TextCommand): def run(self, edit, docstring): self.view.close() self.view.insert(edit, self.view.size(), docstring) class SublimeJediDocstring(sublime_plugin.TextCommand): """ Show doctring in output panel """ def run(self, edit): ask_daemon(self.view, self.show_docstring, 'docstring') def show_docstring(self, view, docstring): window = sublime.active_window() if docstring: output = window.get_output_panel('help_panel') output.set_read_only(False) output.run_command('help_message', {'docstring': docstring}) output.set_read_only(True) window.run_command("show_panel", {"panel": "output.help_panel"}) else: window.run_command("hide_panel", {"panel": "output.help_panel"}) sublime.status_message('Jedi: No results!') class SublimeJediSignature(sublime_plugin.TextCommand): """ Show signature in statusbar """ def run(self, edit): ask_daemon(self.view, self.show_signature, 'signature') def show_signature(self, view, signature): if signature: sublime.status_message('Jedi: {0}'.format(signature))
Fix compat for python 2.6
try: from collections import OrderedDict except ImportError: from django.utils.datastructures import SortedDict as OrderedDict from sequere.query import QuerySetTransformer from sequere import utils class RedisQuerySetTransformer(QuerySetTransformer): def __init__(self, client, count, key, prefix, manager): super(RedisQuerySetTransformer, self).__init__(client, count) self.keys = [key, ] self.order_by(False) self.prefix = prefix self.manager = manager def order_by(self, desc): self.desc = desc if desc: self.method = getattr(self.qs, 'zrevrangebyscore') self.pieces = self.keys + ['+inf', '-inf'] else: self.method = getattr(self.qs, 'zrangebyscore') self.pieces = self.keys + ['-inf', '+inf'] return self def transform(self, qs): scores = self.method(*self.pieces, start=self.start, num=self.stop - self.start, withscores=True) scores = OrderedDict(scores) objects = self.manager.get_from_uid_list(scores.keys()) return [(objects[i], utils.from_timestamp(value[1])) for i, value in enumerate(scores.items())]
from collections import OrderedDict from sequere.query import QuerySetTransformer from sequere import utils class RedisQuerySetTransformer(QuerySetTransformer): def __init__(self, client, count, key, prefix, manager): super(RedisQuerySetTransformer, self).__init__(client, count) self.keys = [key, ] self.order_by(False) self.prefix = prefix self.manager = manager def order_by(self, desc): self.desc = desc if desc: self.method = getattr(self.qs, 'zrevrangebyscore') self.pieces = self.keys + ['+inf', '-inf'] else: self.method = getattr(self.qs, 'zrangebyscore') self.pieces = self.keys + ['-inf', '+inf'] return self def transform(self, qs): scores = self.method(*self.pieces, start=self.start, num=self.stop - self.start, withscores=True) scores = OrderedDict(scores) objects = self.manager.get_from_uid_list(scores.keys()) return [(objects[i], utils.from_timestamp(value[1])) for i, value in enumerate(scores.items())]
Add comments to example module
/** * Example WebSocket module. */ class EchoChat { constructor( ws ) { this.ws = ws; } /** * Default message routing function for this object. * The routing server assumes all modules will have a * doAction() function. */ doAction( messageObj ) { console.log( "do action", messageObj ); switch( messageObj.data.action ) { case 'echo_message': this.echoMessage( messageObj ); break; case 'send_response': this.sendResponse( messageObj ); break; } } /** * Simple function to echo the user message back to them. */ echoMessage( messageObj ) { this.ws.send( JSON.stringify( { isSuccess: true, call_id: messageObj.call_id, data: { message: messageObj.data.message, user: 'dan', } } ) ); } /** * Send the user a generic response message */ sendResponse( messageObj ) { this.ws.send( JSON.stringify( { isSuccess: true, call_id: messageObj.call_id, data: { message: 'Response Message', user: 'brian', } } ) ); } } module.exports.EchoChat = EchoChat;
/** * Example WebSocket module. */ class EchoChat { constructor( ws ) { this.ws = ws; } doAction( messageObj ) { console.log( "do action", messageObj ); switch( messageObj.data.action ) { case 'echo_message': this.echoMessage( messageObj ); break; case 'send_response': this.sendResponse( messageObj ); break; } } echoMessage( messageObj ) { this.ws.send( JSON.stringify( { isSuccess: true, call_id: messageObj.call_id, data: { message: messageObj.data.message, user: 'dan', } } ) ); } sendResponse( messageObj ) { this.ws.send( JSON.stringify( { isSuccess: true, call_id: messageObj.call_id, data: { message: 'Response Message', user: 'brian', } } ) ); } } module.exports.EchoChat = EchoChat;
Change to gridboard to add column picker
Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', launch: function() { var self = this; Ext.create('Rally.data.wsapi.Store', { model: 'TypeDefinition', autoLoad:true, filters: [{ property: "TypePath", operator: "contains", value: "PortfolioItem/" }], listeners: { load: function(store, data, success) { self.loadPortfolioItems(data[0].data.TypePath); } } }); }, loadPortfolioItems: function(typePath) { console.log('loading ' + typePath); Ext.create('Rally.data.wsapi.TreeStoreBuilder').build({ models: [typePath], autoLoad: true, enableHierarchy: true, context: null, filters: [ { property: 'Milestones.ObjectID', value: null } ] }).then({ success: this._onStoreBuilt.bind(this, typePath), scope: this }); }, _onStoreBuilt: function(modelName, store) { var modelNames = [modelName], context = this.getContext(); this.add({ xtype: 'rallygridboard', context: context, modelNames: modelNames, toggleState: 'grid', stateful: false, plugins: [ 'rallygridboardaddnew', { ptype: 'rallygridboardfieldpicker', headerPosition: 'left', modelNames: modelNames, stateful: true, stateId: context.getScopedStateId('milestone-app') } ], gridConfig: { store: store, columnCfgs: [ 'Name', 'Project', 'Parent', 'Owner', 'Milestones' ] }, height: this.getHeight() }); } });
Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', launch: function() { var self = this; Ext.create('Rally.data.wsapi.Store', { model: 'TypeDefinition', autoLoad:true, filters: [{ property: "TypePath", operator: "contains", value: "PortfolioItem/" }], listeners: { load: function(store, data, success) { self.loadPortfolioItems(data[0].data.TypePath); } } }); }, loadPortfolioItems: function(typePath) { console.log('loading ' + typePath); Ext.create('Rally.data.wsapi.TreeStoreBuilder').build({ models: [typePath], autoLoad: true, enableHierarchy: true, context: null, filters: [ { property: 'Milestones.ObjectID', value: null } ] }).then({ success: this._onStoreBuilt, scope: this }); }, _onStoreBuilt: function(store) { this.add({ xtype: 'rallytreegrid', store: store, columnCfgs: [ 'Name', 'Project', 'Parent', 'Owner', 'Milestones' ] }); } });
Add get in progress content mehtod Former-commit-id: 1f63a939185c91b73ba9bdc71ade5bdba59143fe Former-commit-id: 1e66b188666eb2cfe2167caae5769551fe51cabd Former-commit-id: 24fe274d42f336154cf8395c622f460da093deb9
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } static getInProgressContent(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response.inProgress; }) } }
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } }
Fix Python 3 issue with long()
from __future__ import unicode_literals import sys import json from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, HttpResponse from django.views.generic.detail import BaseDetailView from .models import Marker if sys.version_info[0] >= 3: long = int class MarkerDetailView(BaseDetailView): """ Simple view for fetching marker details. """ # TODO: support different object types. Perhaps through django-polymorphic? model = Marker pk_url_kwarg = 'id' def get_object(self, queryset=None): """ Returns the object the view is displaying. """ if queryset is None: queryset = self.get_queryset() # Take a GET parameter instead of URLConf variable. try: pk = long(self.request.GET[self.pk_url_kwarg]) except (KeyError, ValueError): raise Http404("Invalid Parameters") queryset = queryset.filter(pk=pk) try: # Get the single item from the filtered queryset obj = queryset.get() except ObjectDoesNotExist as e: raise Http404(e) return obj def render_to_response(self, context): return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8') def get_json_data(self, context): """ Generate the JSON data to send back to the client. :rtype: dict """ return self.object.to_dict(detailed=True)
from __future__ import unicode_literals import json from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, HttpResponse from django.views.generic.detail import BaseDetailView from .models import Marker class MarkerDetailView(BaseDetailView): """ Simple view for fetching marker details. """ # TODO: support different object types. Perhaps through django-polymorphic? model = Marker pk_url_kwarg = 'id' def get_object(self, queryset=None): """ Returns the object the view is displaying. """ if queryset is None: queryset = self.get_queryset() # Take a GET parameter instead of URLConf variable. try: pk = long(self.request.GET[self.pk_url_kwarg]) except (KeyError, ValueError): raise Http404("Invalid Parameters") queryset = queryset.filter(pk=pk) try: # Get the single item from the filtered queryset obj = queryset.get() except ObjectDoesNotExist as e: raise Http404(e) return obj def render_to_response(self, context): return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8') def get_json_data(self, context): """ Generate the JSON data to send back to the client. :rtype: dict """ return self.object.to_dict(detailed=True)
Update pypi classifier to Alpha status
from setuptools import setup, find_packages setup(name='pyramid_es', version='0.3.2.dev', description='Elasticsearch integration for Pyramid.', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', ], keywords='pyramid search elasticsearch', url='http://github.com/cartlogic/pyramid_es', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'pyramid>=1.4', 'pyramid_tm', 'transaction', 'sqlalchemy>=0.8', 'six>=1.5.2', 'elasticsearch>=1.0.0,<2.0.0', ], license='MIT', packages=find_packages(), test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
from setuptools import setup, find_packages setup(name='pyramid_es', version='0.3.2.dev', description='Elasticsearch integration for Pyramid.', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', ], keywords='pyramid search elasticsearch', url='http://github.com/cartlogic/pyramid_es', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'pyramid>=1.4', 'pyramid_tm', 'transaction', 'sqlalchemy>=0.8', 'six>=1.5.2', 'elasticsearch>=1.0.0,<2.0.0', ], license='MIT', packages=find_packages(), test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
Fix typo selectedSting to selectedString
(function () { function CreateNotifyController( $scope, contentResource, navigationService, angularHelper) { var vm = this; var currentForm; vm.notifyOptions = []; vm.save = save; vm.cancel = cancel; vm.message = { name: $scope.currentNode.name };; function onInit() { vm.loading = true; contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) { currentForm = angularHelper.getCurrentForm($scope); vm.loading = false; vm.notifyOptions = options; }); } function cancel() { navigationService.hideMenu(); }; function save(notifyOptions) { vm.saveState = "busy"; vm.saveError = false; vm.saveSuccces = false; var selectedString = ""; angular.forEach(notifyOptions, function (option) { if (option.checked === true && option.notifyCode) { selectedString += option.notifyCode; } }) contentResource.setNotifySettingsById($scope.currentNode.id, selectedString).then(function () { vm.saveState = "success"; vm.saveSuccces = true; }, function (error) { vm.saveState = "error"; vm.saveError = error; }); } onInit(); } angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController); }());
(function () { function CreateNotifyController( $scope, contentResource, navigationService, angularHelper) { var vm = this; var currentForm; vm.notifyOptions = []; vm.save = save; vm.cancel = cancel; vm.message = { name: $scope.currentNode.name };; function onInit() { vm.loading = true; contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) { currentForm = angularHelper.getCurrentForm($scope); vm.loading = false; vm.notifyOptions = options; }); } function cancel() { navigationService.hideMenu(); }; function save(notifyOptions) { vm.saveState = "busy"; vm.saveError = false; vm.saveSuccces = false; var selectedSting = ""; angular.forEach(notifyOptions, function (option) { if (option.checked === true && option.notifyCode) { selectedSting += option.notifyCode; } }) contentResource.setNotifySettingsById($scope.currentNode.id, selectedSting).then(function () { vm.saveState = "success"; vm.saveSuccces = true; }, function (error) { vm.saveState = "error"; vm.saveError = error; }); } onInit(); } angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController); }());
Add dbversion parameter to call of webservice via ajax
$(document).ready(function(){ //autocomplete for organism search $("#search_organism").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Organisms"), data: {term: request.term, limit: 500, search: search, dbversion: DbVersion}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_organism").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/organism/details/byId/"+item.organism_id+"' class='fancybox' data-fancybox-type='ajax'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.scientific_name + "</span><span style='color: #338C8C'>" + item.rank + "</span></a>") .appendTo(ul); return li; }; $("#btn_search_organism").click(function(){ var searchTerm = $("#search_organism").val(); var resultPage = WebRoot+"/organism/results/"+searchTerm; window.location.href = resultPage; }); });
$(document).ready(function(){ //autocomplete for organism search $("#search_organism").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Organisms"), data: {term: request.term, limit: 500, search: search}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_organism").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/organism/details/byId/"+item.organism_id+"' class='fancybox' data-fancybox-type='ajax'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.scientific_name + "</span><span style='color: #338C8C'>" + item.rank + "</span></a>") .appendTo(ul); return li; }; $("#btn_search_organism").click(function(){ var searchTerm = $("#search_organism").val(); var resultPage = WebRoot+"/organism/results/"+searchTerm; window.location.href = resultPage; }); });
Use "clientInstance" instead of just "forager"
package forager.client; import java.io.IOException; import java.util.logging.Logger; /** * Monitors currently running tasks and decides when new tasks should be * requested based on current processing directives. * * @author malensek */ public class StatusMonitor implements Runnable { private static final Logger logger = Logger.getLogger("forager"); /** Maximum number of concurrent tasks */ int maxActive = 4; boolean online; private Forager clientInstance; public StatusMonitor(Forager clientInstance) { this.clientInstance = clientInstance; this.maxActive = clientInstance.getMaxTasks(); } public void run() { online = true; while (online) { int active = clientInstance.getNumActive() + clientInstance.getNumPending(); if (active < maxActive) { int numTasks = maxActive - active; try { clientInstance.submitTaskRequest(numTasks); } catch (IOException e) { System.out.println("Failed to submit task request!"); e.printStackTrace(); } } try { Thread.sleep(30000); } catch (InterruptedException e) { logger.fine("Waking up StatusMonitor thread"); } } } }
package forager.client; import java.io.IOException; import java.util.logging.Logger; /** * Monitors currently running tasks and decides when new tasks should be * requested based on current processing directives. * * @author malensek */ public class StatusMonitor implements Runnable { private static final Logger logger = Logger.getLogger("forager"); /** Maximum number of concurrent tasks */ int maxActive = 4; boolean online; private Forager forager; public StatusMonitor(Forager forager) { this.forager = forager; this.maxActive = forager.getMaxTasks(); } public void run() { online = true; while (online) { int active = forager.getNumActive() + forager.getNumPending(); if (active < maxActive) { int numTasks = maxActive - active; try { forager.submitTaskRequest(numTasks); } catch (IOException e) { System.out.println("Failed to submit task request!"); e.printStackTrace(); } } try { Thread.sleep(30000); } catch (InterruptedException e) { logger.fine("Waking up StatusMonitor thread"); } } } }
Update gen-publish script to update 'next' tag for main releases
#!/usr/bin/env node const path = require("path"); const fs = require("fs-extra"); const should = require("should"); const LATEST = "2"; function generateScript() { return new Promise((resolve, reject) => { const packages = [ "@node-red/util", "@node-red/runtime", "@node-red/registry", "@node-red/nodes", "@node-red/editor-client", "@node-red/editor-api", "node-red" ]; const rootPackage = require(path.join(__dirname,"..","package.json")); const version = rootPackage.version; const versionParts = version.split("."); let updateNextToLatest = false; let tagArg = ""; if (versionParts[0] !== LATEST) { tagArg = `--tag v${versionParts[0]}-maintenance` } else if (/-/.test(version)) { tagArg = "--tag next" } else { updateNextToLatest = true; } const lines = []; packages.forEach(name => { const tarName = name.replace(/@/,"").replace(/\//,"-") lines.push(`npm publish ${tarName}-${version}.tgz ${tagArg}\n`); if (updateNextToLatest) { lines.push(`npm dist-tag add ${name}@${version} next\n`); } }) resolve(lines.join("")) }); } if (require.main === module) { generateScript().then(output => { console.log(output); }); } else { module.exports = generateScript; }
#!/usr/bin/env node const path = require("path"); const fs = require("fs-extra"); const should = require("should"); const LATEST = "2"; function generateScript() { return new Promise((resolve, reject) => { const packages = [ "node-red-util", "node-red-runtime", "node-red-registry", "node-red-nodes", "node-red-editor-client", "node-red-editor-api", "node-red" ]; const rootPackage = require(path.join(__dirname,"..","package.json")); const version = rootPackage.version; const versionParts = version.split("."); let tagArg = ""; if (versionParts[0] !== LATEST) { tagArg = `--tag v${versionParts[0]}-maintenance` } else if (/-/.test(version)) { tagArg = "--tag next" } const lines = []; packages.forEach(name => { lines.push(`npm publish ${name}-${version}.tgz ${tagArg}\n`); }) resolve(lines.join("")) }); } if (require.main === module) { generateScript().then(output => { console.log(output); }); } else { module.exports = generateScript; }
Extend the status exposing duration
'use strict'; import { StatsCollector } from './lib/stats'; export default function(RED) { class DeviceStatsNode { constructor(n) { RED.nodes.createNode(this, n); this.name = n.name; this.mem = n.mem; this.nw = n.nw; this.load = n.load; this.hostname = n.hostname; this.useString = n.useString; this.collector = new StatsCollector(this); this.status({}); this.on('input', msg => { clearTimeout(this.timeout); this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' }); let opts = msg ? msg.payload : null; this.collector.collect(opts).then(stats => { if (this.useString || opts && opts.useString) { stats = JSON.stringify(stats); } this.send({ payload: stats }); this.timeout = setTimeout(() => { this.status({}); }, 750); }).catch(err => { RED.log.warn(RED._('device-stats.errors.unknown', { error: err })); this.status({}); }); }); } } RED.nodes.registerType('DeviceStats', DeviceStatsNode); }
'use strict'; import { StatsCollector } from './lib/stats'; export default function(RED) { class DeviceStatsNode { constructor(n) { RED.nodes.createNode(this, n); this.name = n.name; this.mem = n.mem; this.nw = n.nw; this.load = n.load; this.hostname = n.hostname; this.useString = n.useString; this.collector = new StatsCollector(this); this.status({}); this.on('input', msg => { clearTimeout(this.timeout); this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' }); let opts = msg ? msg.payload : null; this.collector.collect(opts).then(stats => { if (this.useString || opts && opts.useString) { stats = JSON.stringify(stats); } this.send({ payload: stats }); this.timeout = setTimeout(() => { this.status({}); }, 500); }).catch(err => { RED.log.warn(RED._('device-stats.errors.unknown', { error: err })); this.status({}); }); }); } } RED.nodes.registerType('DeviceStats', DeviceStatsNode); }
Handle non-existent files in the database.
#!/usr/bin/env python import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) if datafile is None: continue df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
#!/usr/bin/env python import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
Disable the assigned list when changing to the next status
$(function() { var $nextStatus = $('.next-status-choice'); var $assigned = $('.assigned-choice'); var workflowId = $('.workflow-hidden').val(); var currentStateId = $('.current-state').data('value'); var UpdateAssignedList = function() { var status = $('input:checked', $nextStatus).val(); if (status == undefined) { status = currentStateId; } $assigned.attr('disabled','disabled'); $.ajax({ url: Routing.generate('integrated_workflow_assigned', { 'workflow':workflowId, 'state':status, '_format':'json' }), dataType: 'json', success: function(response) { var selected = $('option:selected', $assigned).val(); var $firstOption = $('option:first', $assigned); var $option = $firstOption.clone(); $firstOption.siblings().remove(); $.each(response.users, function(id, name) { var $tmp = $option.clone().val(id).text(name); if (id==selected) { $tmp.attr('selected','selected'); } $tmp.appendTo($assigned); }); $assigned.removeAttr('disabled'); } }); }; $('input', $nextStatus).change(UpdateAssignedList); UpdateAssignedList(); });
$(function() { var $nextStatus = $('.next-status-choice'); var $assigned = $('.assigned-choice'); var workflowId = $('.workflow-hidden').val(); var currentStateId = $('.current-state').data('value'); var UpdateAssignedList = function() { var status = $('input:checked', $nextStatus).val(); if (status == undefined) { status = currentStateId; } $.ajax({ url: Routing.generate('integrated_workflow_assigned', { 'workflow':workflowId, 'state':status, '_format':'json' }), dataType: 'json', success: function(response) { var selected = $('option:selected', $assigned).val(); var $firstOption = $('option:first', $assigned); var $option = $firstOption.clone(); $firstOption.siblings().remove(); $.each(response.users, function(id, name) { var $tmp = $option.clone().val(id).text(name); if (id==selected) { $tmp.attr('selected','selected'); } $tmp.appendTo($assigned); }); } }); }; $('input', $nextStatus).change(UpdateAssignedList); UpdateAssignedList(); });
Use first visible background layer as active background layer
angular.module('anol.layerswitcher', []) .directive('anolLayerswitcher', ['LayersService', function(LayersService) { return { restrict: 'A', transclude: true, templateUrl: 'anol/modules/layerswitcher/templates/layerswitcher.html', scope: {}, link: function(scope, element, attrs) { scope.$watch('backgroundLayer', function(newVal, oldVal) { oldVal.setVisible(false); newVal.setVisible(true); }); }, controller: function($scope, $element, $attrs) { $scope.backgroundLayers = LayersService.backgroundLayers; angular.forEach($scope.backgroundLayers, function(layer) { if(layer.getVisible() === true && $scope.backgroundLayer === undefined) { $scope.backgroundLayer = layer; $scope.backgroundLayer.setVisible(false); } else { layer.setVisible(false); } }); $scope.overlayLayers = LayersService.overlayLayers; } }; }]);
angular.module('anol.layerswitcher', []) .directive('anolLayerswitcher', ['LayersService', function(LayersService) { return { restrict: 'A', transclude: true, templateUrl: 'anol/modules/layerswitcher/templates/layerswitcher.html', scope: {}, link: function(scope, element, attrs) { scope.$watch('backgroundLayer', function(newVal, oldVal) { oldVal.setVisible(false); newVal.setVisible(true); }); }, controller: function($scope, $element, $attrs) { $scope.backgroundLayers = LayersService.backgroundLayers; angular.forEach($scope.backgroundLayers, function(layer) { if(layer.getVisible() === true) { if($scope.backgroundLayer !== undefined) { $scope.backgroundLayer.setVisible(false); } $scope.backgroundLayer = layer; } }); $scope.overlayLayers = LayersService.overlayLayers; } }; }]);
Return the proper error message if there is one
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { response.json().then((data) => { if (response.ok && data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { let e = new Error('Malformed response'); e.response = response; reject(e); }) }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { if (response.ok) { response.json().then((data) => { if (data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { let e = new Error('Malformed response'); e.response = response; reject(e); }) } else { let e = new Error(response.statusText); e.response = response; reject(e); } }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
Use JSON.stringify instead and fix linter
define([ '/bower_components/jquery/dist/jquery.min.js', '/common/cryptpad-common.js', ], function (jQuery, Cryptpad) { var $ = window.jQuery; var $body = $('body'); var pre = function (text, opt) { return $('<pre>', opt).text(text); }; var todo = function (missing) { var str = ""; var need = 1; if (missing.length) { $body.append(pre(missing.map(function (msg) { var res = ""; var code = msg[0]; var key = msg[1]; var needed = msg[2]; if (str !== code) { if (str !== "") { res += '\n'; } str = code; res += '/*\n *\n * ' + code + '\n *\n */\n\n'; } if (need !== needed) { need = needed; if (need === 0) { res += '\n// TODO: These keys are not needed anymore and should be removed ('+ code + ')\n\n'; } } res += (need ? '' : '// ') + 'out.' + key + ' = "";'; if (need) { res += ' // ' + JSON.stringify(Cryptpad.Messages._getKey(key, [])); } return res; }).join('\n'))); } else { $body.text('// All keys are present in all translations'); } }; Cryptpad.Messages._checkTranslationState(todo); });
define([ '/bower_components/jquery/dist/jquery.min.js', '/common/cryptpad-common.js', ], function (jQuery, Cryptpad) { var $ = window.jQuery; var $body = $('body'); var pre = function (text, opt) { return $('<pre>', opt).text(text); }; var addSlashes = function (text) { return (text + '').replace(/[\\']/g, '\\\''); } var todo = function (missing) { var str = "";; var need = 1; if (missing.length) { $body.append(pre(missing.map(function (msg) { var res = ""; var code = msg[0]; var key = msg[1]; var needed = msg[2]; if (str !== code) { if (str !== "") res += '\n'; str = code; res += '/*\n *\n * ' + code + '\n *\n */\n\n'; } if (need !== needed) { need = needed; if (need === 0) res += '\n// TODO: These keys are not needed anymore and should be removed ('+ code + ')\n\n'; } res += (need ? '' : '// ') + 'out.' + key + ' = \'\';'; if (need) res += ' // \'' + addSlashes(Cryptpad.Messages._getKey(key, [])) + '\''; return res; }).join('\n'))); } else { $body.text('// All keys are present in all translations'); } }; Cryptpad.Messages._checkTranslationState(todo); });
Add pyzmq. Note: this package doesn't need it but IPython notebook does
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() requires = ['pyrax==1.4.7', 'ipython==0.13.2', 'tornado==3.1', 'pyzmq==13.1.0' ] setup(name='ipynb_swiftstore', version='0.0.0', description='IPython notebook storage for OpenStack Swift', author='Kyle Kelley', author_email='[email protected]', url='http://github.com/rgbkrk/ipynb-swiftstore', py_modules=['ipynb_swiftstore'], package_data={'': ['LICENSE']}, include_package_data=False, install_requires=requires, license=open('LICENSE').read(), zip_safe=True, classifiers=( 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Environment :: OpenStack', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Distributed Computing', ), )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() requires = ['pyrax==1.4.7', 'ipython==0.13.2', 'tornado==3.1', ] setup(name='ipynb_swiftstore', version='0.0.0', description='IPython notebook storage for OpenStack Swift', author='Kyle Kelley', author_email='[email protected]', url='http://github.com/rgbkrk/ipynb-swiftstore', py_modules=['ipynb_swiftstore'], package_data={'': ['LICENSE']}, include_package_data=False, install_requires=requires, license=open('LICENSE').read(), zip_safe=True, classifiers=( 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Environment :: OpenStack', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Distributed Computing', ), )
Fix server error when login with u2f
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from u2flib_server.u2f import (begin_registration, begin_authentication, complete_registration, complete_authentication) from components.eternity import config facet = config.rss['link'] async def enroll(user): enroll = begin_registration(facet, user.get('_u2f_devices_', [])) user['_u2f_enroll_'] = enroll.json return user, json.dumps(enroll.data_for_client) async def bind(user, data): response = data['tokenResponse'] enroll = user.pop('_u2f_enroll_') device, cert = complete_registration(enroll, response, [facet]) patch = device patch['deviceName'] = data['deviceName'] patch['registerDate'] = data['date'] user.setdefault('_u2f_devices_', []).append(json.dumps(patch)) # cert = x509.load_der_x509_certificate(cert, default_backend()) return user, True async def sign(user): challenge = begin_authentication(facet, user.get('_u2f_devices_', [])) user['_u2f_challenge_'] = challenge.json return user, json.dumps(challenge.data_for_client) async def verify(user, data): print(user) challenge = user.pop('_u2f_challenge_') try: complete_authentication(challenge, data, [facet]) except AttributeError: return user, False return user, True
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from u2flib_server.u2f import (begin_registration, begin_authentication, complete_registration, complete_authentication) from components.eternity import config facet = config.rss['link'] async def enroll(user): enroll = begin_registration(facet, user.get('_u2f_devices_', [])) user['_u2f_enroll_'] = enroll.json return user, json.dumps(enroll.data_for_client) async def bind(user, data): response = data['tokenResponse'] enroll = user.pop('_u2f_enroll_') device, cert = complete_registration(enroll, response, [facet]) patch = device patch['deviceName'] = data['deviceName'] patch['registerDate'] = data['date'] user.setdefault('_u2f_devices_', []).append(json.dumps(patch)) # cert = x509.load_der_x509_certificate(cert, default_backend()) return user, True async def sign(user): challenge = begin_authentication(facet, user.get('_u2f_devices_', [])) user['_u2f_challenge_'] = challenge.json return user, json.dumps(challenge.data_for_client) async def verify(user, data): challenge = user.pop('_u2f_challenge_') try: complete_authentication(challenge, data, [facet]) except AttributeError: return user, False return user, True
Add price per layer in order view
<?php class Magebay_Productbuilderpro_Block_Adminhtml_Additional_Product_Info extends Mage_Core_Block_Abstract { protected function _toHtml() { $item = $this->getParentBlock()->getItem(); //Zend_Debug::dump($item->getData()); $additionalOptions = serialize($item->getProductOptionByCode("additional_options")); if($additionalOptions) { $customizeInfo = Mage::helper("productbuilderpro")->getCustomizeInfo($additionalOptions); if($customizeInfo) { $html = "<div class='view-customize-design' id='customize-". $item->getData("item_id") ."'>"; $html .= '<dt><span style="font-weight: bold">' . Mage::helper("productbuilderpro")->__("Customize Information:") . '</span></dt>'; $html .= '<dl class="item-options pdp_cart_item">'; foreach ($customizeInfo['selected_layer'] as $layer) { $price = Mage::helper('core')->currency($layer['price'], true, false); $html .= '<dt>' . $layer['root_title'] . '<dt>'; $html .= '<dd>' . $layer['title'] . ': <strong class="price">' . $price . '</strong><dd>'; } $html .= "<dt>". Mage::helper("productbuilderpro")->__("Design Preview") ."</dt>"; $html .= "<dd><img src='". $customizeInfo['thumbnail_image'] ."' width='200px'/></dd>"; $html .= '</dl>'; $html .= "</div>"; return $html; } } } }
<?php class Magebay_Productbuilderpro_Block_Adminhtml_Additional_Product_Info extends Mage_Core_Block_Abstract { protected function _toHtml() { $item = $this->getParentBlock()->getItem(); //Zend_Debug::dump($item->getData()); $additionalOptions = serialize($item->getProductOptionByCode("additional_options")); if($additionalOptions) { $customizeInfo = Mage::helper("productbuilderpro")->getCustomizeInfo($additionalOptions); if($customizeInfo) { $html = "<div class='view-customize-design' id='customize-". $item->getData("item_id") ."'>"; $html .= '<dt><span style="font-weight: bold">' . Mage::helper("productbuilderpro")->__("Customize Information:") . '</span></dt>'; $html .= '<dl class="item-options pdp_cart_item">'; foreach ($customizeInfo['selected_layer'] as $layer) { $html .= '<dt>' . $layer['root_title'] . '<dt>'; $html .= '<dd>' . $layer['title'] . '<dd>'; } $html .= "<dt>". Mage::helper("productbuilderpro")->__("Design Preview") ."</dt>"; $html .= "<dd><img src='". $customizeInfo['thumbnail_image'] ."' width='200px'/></dd>"; $html .= '</dl>'; $html .= "</div>"; return $html; } } } }
Add logging for state_code error
'use strict'; const Queries = require('../../helpers/queries'); const Parser = require('../../helpers/paydroid_parser'); const Boom = require('boom'); const D3 = require('d3'); exports.getData = { auth: { mode: 'try', strategy: 'standard' }, plugins: { 'hapi-auth-cookie': { redirectTo: false } }, handler: function(request, reply) { if (!request.auth.isAuthenticated) { return reply(Boom.forbidden('You are not logged in')); } var sequelize = request.server.plugins.sequelize.db.sequelize; var userId = request.auth.credentials.id; var role = request.auth.credentials.role; var version = request.pre.apiVersion; var name = request.auth.credentials.firstname + ' ' + request.auth.credentials.lastname; var queryString = Queries.paydroid(userId, role, version); // API CODE sequelize .query(queryString, { type: sequelize.QueryTypes.SELECT }) .then(function(rows) { var data; if (version === 1) { data = Parser.v1(rows, userId, name); } else if (version === 2) { if (role==='block' && D3.values(rows[4])[0]===undefined) { console.log("Couldn't find state code in db for request:\n" + request); return reply(Boom.badRequest('Bad request')); } data = Parser.v2(rows, role, userId, name); } reply(data); }); } };
'use strict'; const Queries = require('../../helpers/queries'); const Parser = require('../../helpers/paydroid_parser'); const Boom = require('boom'); exports.getData = { auth: { mode: 'try', strategy: 'standard' }, plugins: { 'hapi-auth-cookie': { redirectTo: false } }, handler: function(request, reply) { if (!request.auth.isAuthenticated) { return reply(Boom.forbidden('You are not logged in')); } var sequelize = request.server.plugins.sequelize.db.sequelize; var userId = request.auth.credentials.id; var role = request.auth.credentials.role; var version = request.pre.apiVersion; var name = request.auth.credentials.firstname + ' ' + request.auth.credentials.lastname; var queryString = Queries.paydroid(userId, role, version); // API CODE sequelize .query(queryString, { type: sequelize.QueryTypes.SELECT }) .then(function(rows) { var data; if (version === 1) { data = Parser.v1(rows, userId, name); } else if (version === 2) { data = Parser.v2(rows, role, userId, name); } reply(data); }); } };
Fix "clear completed" button to actually work As it stands, the "clear completed" button fails to work as intended. This is because the array is mutated during the traversal. An item which immediately follows a completed item will not be checked. The fix is to traverse the array backwards.
var app = app || {}; (function () { 'use strict'; app.controller = function() { this.list = new app.TodoList(); // Todo collection this.title = m.prop(''); // Temp title placeholder this.filter = m.prop(m.route.param('filter') || ''); // TodoList filter // Add a Todo this.add = function(title) { if(this.title()) { this.list.push(new app.Todo({title: title()})); this.title(''); } }; //check whether a todo is visible this.isVisible = function(todo) { if(this.filter() == '') return true; if (this.filter() == 'active') return !todo.completed(); if (this.filter() == 'completed') return todo.completed(); } this.clearTitle = function() { this.title('') } // Removing a Todo from the list this.remove = function(key) { this.list.splice(key, 1) } // Remove all Todos where Completed == true this.clearCompleted = function() { for(var i = this.list.length - 1; i >= 0; i--) { if (this.list[i].completed()) { this.list.splice(i, 1); } } } // Total amount of Todos completed this.amountCompleted = function() { var amount = 0; for(var i = 0; i < this.list.length; i++) if(this.list[i].completed()) amount++; return amount; } }; })();
var app = app || {}; (function () { 'use strict'; app.controller = function() { this.list = new app.TodoList(); // Todo collection this.title = m.prop(''); // Temp title placeholder this.filter = m.prop(m.route.param('filter') || ''); // TodoList filter // Add a Todo this.add = function(title) { if(this.title()) { this.list.push(new app.Todo({title: title()})); this.title(''); } }; //check whether a todo is visible this.isVisible = function(todo) { if(this.filter() == '') return true; if (this.filter() == 'active') return !todo.completed(); if (this.filter() == 'completed') return todo.completed(); } this.clearTitle = function() { this.title('') } // Removing a Todo from the list this.remove = function(key) { this.list.splice(key, 1) } // Remove all Todos where Completed == true this.clearCompleted = function() { for(var i = 0; i < this.list.length; i++) { if(this.list[i].completed()) this.list.splice(i, 1) } } // Total amount of Todos completed this.amountCompleted = function() { var amount = 0; for(var i = 0; i < this.list.length; i++) if(this.list[i].completed()) amount++; return amount; } }; })();
Increase max listeners to prevent nodes warn.
'use strict'; var retry = require('retry'); var deepExtend = require('deep-extend'); var errorCodes = [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET' ]; function requestReplay(request, options) { var originalEmit = request.emit; var operation; var attempts = 0; // Default options options = deepExtend({ errorCodes: errorCodes, retries: 5, factor: 3, minTimeout: 2000, maxTimeout: 35000, randomize: true }, options || {}); // Init retry operation = retry.operation(options); operation.attempt(function () { if (attempts) { request.start(); } attempts++; }); // Increase maxListeners because start() adds a new listener each time request._maxListeners += options.retries + 1; // Monkey patch emit to catch errors and retry request.emit = function (name, error) { // If not an error, pass-through if (name !== 'error') { return originalEmit.apply(this, arguments); } // If not a retry error code, pass-through if (options.errorCodes.indexOf(error.code) === -1) { return originalEmit.call(this, name, error); } // Retry if (operation.retry(error)) { this.emit('replay', attempts - 1, error); return 0; } // No more retries available, error out error.replays = attempts - 1; return originalEmit.call(this, name, error); }; return request; } module.exports = requestReplay;
'use strict'; var retry = require('retry'); var deepExtend = require('deep-extend'); var errorCodes = [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET' ]; function requestReplay(request, options) { var originalEmit = request.emit; var operation; var attempts = 0; options = deepExtend({ errorCodes: errorCodes, retries: 5, factor: 3, minTimeout: 2000, maxTimeout: 35000, randomize: true }, options || {}); options.errorCodes = options.errorCodes || errorCodes; operation = retry.operation(options); operation.attempt(function () { if (attempts) { request.start(); } attempts++; }); request.emit = function (name, error) { // If not an error, pass-through if (name !== 'error') { return originalEmit.apply(this, arguments); } // If not a retry error code, pass-through if (options.errorCodes.indexOf(error.code) === -1) { return originalEmit.call(this, name, error); } // Retry if (operation.retry(error)) { this.emit('replay', attempts - 1, error); return 0; } // No more retries available, error out error.replays = attempts - 1; return originalEmit.call(this, name, error); }; return request; } module.exports = requestReplay;
Add plugins to the domains which handle temp files
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): path = urlquote(request.get_full_path()) if not request.session.get("project"): return HttpResponseRedirect("/projects/list/?next=%s" % path) return func(request, *args, **kwargs) return wrapper def saves_files(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): temp = request.path.startswith(("/ocr/", "/plugins/")) project = request.session.get("project") output_path = None if project is None: temp = True if temp: output_path = os.path.join( settings.MEDIA_ROOT, settings.TEMP_PATH, request.user.username, datetime.now().strftime("%Y%m%d%H%M%S") ) else: output_path = os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH, project.slug ) request.__class__.output_path = output_path return func(request, *args, **kwargs) return wrapper
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): path = urlquote(request.get_full_path()) if not request.session.get("project"): return HttpResponseRedirect("/projects/list/?next=%s" % path) return func(request, *args, **kwargs) return wrapper def saves_files(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): temp = request.path.startswith("/ocr/") project = request.session.get("project") output_path = None if project is None: temp = True if temp: output_path = os.path.join( settings.MEDIA_ROOT, settings.TEMP_PATH, request.user.username, datetime.now().strftime("%Y%m%d%H%M%S") ) else: output_path = os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH, project.slug ) request.__class__.output_path = output_path return func(request, *args, **kwargs) return wrapper
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
# Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) try: key = int(input()) except ValueError: continue if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
# Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) key = int(input()) if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
Change boolean-based options to real booleans
(function() { // Creates an iframe with an embedded HipChat conversation window. // // Options: // url - The url to the room to embed; required // el - The container in which to insert the HipChat panel; required // timezone - The timezone to use in the embedded room; required // width - The width of the iframe; defaults to 100% // height - The height of the iframe; defaults to 400px var parametize = function(params) { var key, toks = []; for (key in params) { toks.push(key + '=' + params[key]); } return toks.join('&'); }; return this.HipChat = function(options) { if (options && options.url && options.el && options.timezone) { var el = document.querySelector(options.el); if (!el) return; var params = { anonymous: false, timezone: options.timezone, minimal: true }; var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + parametize(params); if (url.indexOf('https://') !== 0) { url = 'https://' + url; } var w = options.width || '100%'; var h = options.height || 600; el.innerHTML = '<iframe src="' + url + '" frameborder="' + 0 + '" width="' + w + '" height="' + h + '"></iframe>'; } }; })();
(function() { // Creates an iframe with an embedded HipChat conversation window. // // Options: // url - The url to the room to embed; required // el - The container in which to insert the HipChat panel; required // timezone - The timezone to use in the embedded room; required // width - The width of the iframe; defaults to 100% // height - The height of the iframe; defaults to 400px var parametize = function(params) { var key, toks = []; for (key in params) { toks.push(key + '=' + params[key]); } return toks.join('&'); }; return this.HipChat = function(options) { if (options && options.url && options.el && options.timezone) { var el = document.querySelector(options.el); if (!el) return; var params = { anonymous: 0, timezone: options.timezone, minimal: 1 }; var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + parametize(params); if (url.indexOf('https://') !== 0) { url = 'https://' + url; } var w = options.width || '100%'; var h = options.height || 600; el.innerHTML = '<iframe src="' + url + '" frameborder="' + 0 + '" width="' + w + '" height="' + h + '"></iframe>'; } }; })();
Move choices outside of model class
from django.db import models from django.utils.translation import pgettext_lazy from django.utils.encoding import python_2_unicode_compatible INTEGER = 'i' STRING = 's' BOOLEAN = 'b' @python_2_unicode_compatible class Setting(models.Model): VALUE_TYPE_CHOICES = ( (INTEGER, pgettext_lazy('Settings', 'Integer')), (STRING, pgettext_lazy('Settings', 'String')), (BOOLEAN, pgettext_lazy('Settings', 'Boolean')), ) name = models.CharField( pgettext_lazy('Settings field', 'name'), max_length=128) value_type = models.CharField(pgettext_lazy('Settings field', 'value type'), max_length=1, choices=VALUE_TYPE_CHOICES) value = models.CharField( pgettext_lazy('Settings field', 'value'), max_length=256) def convert_value(self): if self.value_type == self.INTEGER: return int(self.value) elif self.value_type == self.BOOLEAN: return self._to_bool() elif self.value_type == self.STRING: return self.value else: raise ValueError('Incorrect value') def _to_bool(self): values_dict = {'true': True, 'false': False} try: return values_dict[self.value.lower()] except KeyError: raise ValueError('Cannot convert to boolean') def __str__(self): return '%s: %s' % (self.name, self.value)
from django.db import models from django.utils.translation import pgettext_lazy from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Setting(models.Model): INTEGER = 'i' STRING = 's' BOOLEAN = 'b' VALUE_TYPE_CHOICES = ( (INTEGER, pgettext_lazy('Settings', 'Integer')), (STRING, pgettext_lazy('Settings', 'String')), (BOOLEAN, pgettext_lazy('Settings', 'Boolean')), ) name = models.CharField( pgettext_lazy('Settings field', 'name'), max_length=128) value_type = models.CharField(pgettext_lazy('Settings field', 'value type'), max_length=1, choices=VALUE_TYPE_CHOICES) value = models.CharField( pgettext_lazy('Settings field', 'value'), max_length=256) def convert_value(self): if self.value_type == self.INTEGER: return int(self.value) elif self.value_type == self.BOOLEAN: return self._to_bool() elif self.value_type == self.STRING: return self.value else: raise ValueError('Incorrect value') def _to_bool(self): values_dict = {'true': True, 'false': False} try: return values_dict[self.value.lower()] except KeyError: raise ValueError('Cannot convert to boolean') def __str__(self): return '%s: %s' % (self.name, self.value)
Fix IDE warnings in the agent
package com.github.sulir.runtimesearch.runtime; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Check { public static final int PORT = 4321; public static String searchValue; public static void initialize() { try { throw new BreakpointError(); } catch (BreakpointError e) { // exception thrown to trigger a breakpoint in the IDE } } public static void runServer() { try { ServerSocket server = new ServerSocket(PORT, 0, InetAddress.getLoopbackAddress()); Thread thread = new Thread(() -> { while (true) { try { Socket client = server.accept(); ObjectInputStream input = new ObjectInputStream(client.getInputStream()); searchValue = (String) input.readObject(); client.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }); thread.setDaemon(true); thread.start(); } catch (IOException e) { e.printStackTrace(); } } public static void perform(Object object) { if (searchValue == null) return; if (object instanceof String) { String string = (String) object; if (string.contains(searchValue)) { try { searchValue = null; throw new BreakpointError(); } catch (BreakpointError e) { // exception thrown to trigger a breakpoint in the IDE } } } } }
package com.github.sulir.runtimesearch.runtime; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Check { public static final int PORT = 4321; public static String searchValue; public static void initialize() { try { throw new BreakpointError(); } catch (BreakpointError e) { } } public static void runServer() { try { ServerSocket server = new ServerSocket(PORT, 0, InetAddress.getLoopbackAddress()); Thread thread = new Thread(() -> { while (true) { try { Socket client = server.accept(); ObjectInputStream input = new ObjectInputStream(client.getInputStream()); searchValue = (String) input.readObject(); client.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }); thread.setDaemon(true); thread.start(); } catch (IOException e) { e.printStackTrace(); } } public static void perform(Object object) { if (searchValue == null) return; if (object instanceof String) { String string = (String) object; if (string.contains(searchValue)) { try { searchValue = null; throw new BreakpointError(); } catch (BreakpointError e) { } } } } }
Fix portolio tab loading when loaded by pjax
const State = require('../../binary/base/storage').State; const Client = require('../../binary/base/client').Client; const PortfolioWS = require('../../binary/websocket_pages/user/account/portfolio/portfolio.init').PortfolioWS; const JapanPortfolio = (function() { let $portfolio, isPortfolioActive = false; function init() { if (isActive()) { $('#tab_portfolio').removeClass('invisible'); } const $container = $('#tab_portfolio-content'); $portfolio = $portfolio || $('#portfolio'); if ($portfolio && (!$portfolio.parent().length || $portfolio.parent().get(0).id !== 'tab_portfolio-content')) { $portfolio.detach(); $container.append($portfolio); } } function show() { if (isTradePage() && !isPortfolioActive) { PortfolioWS.onLoad(); isPortfolioActive = true; } } function isActive() { return !!(Client.is_logged_in() && isTradePage()); } function hide() { if (isTradePage() && isPortfolioActive) { PortfolioWS.onUnload(); isPortfolioActive = false; $portfolio = undefined; } } function isTradePage() { return State.get('is_mb_trading'); } return { init : init, show : show, hide : hide, isActive: isActive, }; })(); module.exports = { JapanPortfolio: JapanPortfolio, };
const State = require('../../binary/base/storage').State; const Client = require('../../binary/base/client').Client; const PortfolioWS = require('../../binary/websocket_pages/user/account/portfolio/portfolio.init').PortfolioWS; const JapanPortfolio = (function() { let $portfolio, isPortfolioActive = false; function init() { if (isActive()) { $('#tab_portfolio').removeClass('invisible'); } const $container = $('#tab_portfolio-content'); $portfolio = $portfolio || $('#portfolio'); if ($portfolio && (!$portfolio.parent().length || $portfolio.parent().get(0).id !== 'tab_portfolio-content')) { $portfolio.detach(); $container.append($portfolio); } } function show() { if (isTradePage() && !isPortfolioActive) { PortfolioWS.onLoad(); isPortfolioActive = true; } } function isActive() { return !!(Client.is_logged_in() && isTradePage()); } function hide() { if (isTradePage() && isPortfolioActive) { PortfolioWS.onUnload(); isPortfolioActive = false; } } function isTradePage() { return State.get('is_mb_trading'); } return { init : init, show : show, hide : hide, isActive: isActive, }; })(); module.exports = { JapanPortfolio: JapanPortfolio, };
Allow Handlebars to be a global
define(["handlebars"], function(Handlebars) { var buildMap = {}, templateExtension = ".hbs"; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { // Get the template extension. var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension); if (config.isBuild) { // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ext; buildMap[name] = fs.readFileSync(fsPath).toString(); onload(); } else { // In browsers use the text-plugin to the load template. This way we // don't have to deal with ajax stuff parentRequire(["text!" + name + ext], function(raw) { // Just return the compiled template onload(Handlebars.compile(raw)); }); } }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "Handlebars = Handlebars || window.Handlebars;\n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
define(["handlebars"], function(Handlebars) { var buildMap = {}, templateExtension = ".hbs"; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { // Get the template extension. var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension); if (config.isBuild) { // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ext; buildMap[name] = fs.readFileSync(fsPath).toString(); onload(); } else { // In browsers use the text-plugin to the load template. This way we // don't have to deal with ajax stuff parentRequire(["text!" + name + ext], function(raw) { // Just return the compiled template onload(Handlebars.compile(raw)); }); } }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
Remove outdated imports, oops sorry.
import time from . import config # expects Cozify devices type json data def getMultisensorData(data): out = [] for device in data: state=data[device]['state'] devtype = state['type'] if devtype == 'STATE_MULTI_SENSOR': name=data[device]['name'] if 'lastSeen' in state: timestamp=state['lastSeen'] else: # if no time of measurement is known we must make a reasonable assumption # Stored here in milliseconds to match accuracy of what the hub will give you timestamp = time.time() * 1000 if 'temperature' in state: temperature=state['temperature'] else: temperature=None if 'humidity' in state: humidity=state['humidity'] else: humidity=None out.append({ 'name': name, 'time': timestamp, 'temperature': temperature, 'humidity': humidity }) return out
import time from influxdb import InfluxDBClient from influxdb import SeriesHelper from . import config # expects Cozify devices type json data def getMultisensorData(data): out = [] for device in data: state=data[device]['state'] devtype = state['type'] if devtype == 'STATE_MULTI_SENSOR': name=data[device]['name'] if 'lastSeen' in state: timestamp=state['lastSeen'] else: # if no time of measurement is known we must make a reasonable assumption # Stored here in milliseconds to match accuracy of what the hub will give you timestamp = time.time() * 1000 if 'temperature' in state: temperature=state['temperature'] else: temperature=None if 'humidity' in state: humidity=state['humidity'] else: humidity=None out.append({ 'name': name, 'time': timestamp, 'temperature': temperature, 'humidity': humidity }) return out
Rewrite listener to use async/await
const newtaburlEX = { async idleCaptive(newtab) { browser.tabs.onUpdated.addListener(newtaburlEX.forward); }, async forward(tabId, changeInfo, tab) { console.log("wewled"); if (changeInfo.title === '@NewTab') { let ntu = await newtaburlEX.getForwardUrl(); let makeactive = await browser.storage.local.get('active'); if (makeactive.active) { browser.tabs.create({ 'url': ntu }); await browser.tabs.remove(tabId) let closed = await browser.sessions.getRecentlyClosed(); if (Object.prototype.hasOwnProperty.call(closed[0],'tab') && closed[0].tab.title === '@NewTab') { browser.sessions.forgetClosedTab( closed[0].tab.windowId, closed[0].tab.sessionId.toString() ); } } else { await browser.tabs.update(tabId, { 'url': ntu }); } } browser.tabs.onUpdated.removeListener(newtaburlEX.forward); }, async getForwardUrl() { let ntu = await browser.storage.local.get('newtaburl'); if (ntu.newtaburl == null) { return 'about:blank'; } else { return ntu.newtaburl; } } } browser.tabs.onCreated.addListener(newtaburlEX.idleCaptive);
function nt (newtab) { function waitForURL(tabId, changeInfo, tab) { if (changeInfo.title === '@NewTab') { browser.storage.local.get('newtaburl').then((ntu) => { browser.tabs.onUpdated.removeListener(waitForURL); if (ntu.newtaburl == null) { browser.storage.local.set({ newtaburl: 'about:blank' }); ntu.newtaburl = 'about:blank'; } browser.storage.local.get('active').then((act) => { if (act.active) { browser.tabs.create({ 'url': ntu.newtaburl }); browser.tabs.remove(newtab.id).then(() => { browser.sessions.getRecentlyClosed().then((l) => { if (Object.prototype.hasOwnProperty.call(l[0],'tab') && l[0].tab.title === '@NewTab') { browser.sessions.forgetClosedTab( l[0].tab.windowId, l[0].tab.sessionId.toString() ); } }); }); } else { browser.tabs.update(tabId, { 'url': ntu.newtaburl }); } }); }); } browser.tabs.onUpdated.removeListener(waitForURL); } browser.tabs.onUpdated.addListener(waitForURL); } browser.tabs.onCreated.addListener(nt);
Fix error if passing a list of args to tenancy_reverse
from django.conf import settings from django.core.urlresolvers import reverse from django.db.models import Q def multitenancy_enabled(): return "decisiontree.multitenancy" in settings.INSTALLED_APPS def get_tenants_for_user(user): """Return all tenants that the user can manage.""" from multitenancy.models import Tenant tenants = Tenant.objects.all() if not user.is_superuser: user_is_manager = Q(tenantrole__user=user) | Q(group__tenantrole__user=user) tenants = tenants.filter(user_is_manager) return tenants def get_link_class_from_model(model): """Get the tenant link model associated with the model class.""" model_class = model if isinstance(model, type) else type(model) if not hasattr(model_class, 'tenantlink'): raise TypeError("This method should only be used on tenant-enabled models.") return model_class.tenantlink.related.model def tenancy_reverse(request, url_name, *args, **kwargs): """Add tenancy information to the URL reversal if multitenancy is enabled.""" if multitenancy_enabled(): # reverse disallows mixing *args and **kwargs. if args: args = (request.group_slug, request.tenant_slug) + tuple(args) else: kwargs.setdefault('group_slug', request.group_slug) kwargs.setdefault('tenant_slug', request.tenant_slug) return reverse(url_name, args=args, kwargs=kwargs)
from django.conf import settings from django.core.urlresolvers import reverse from django.db.models import Q def multitenancy_enabled(): return "decisiontree.multitenancy" in settings.INSTALLED_APPS def get_tenants_for_user(user): """Return all tenants that the user can manage.""" from multitenancy.models import Tenant tenants = Tenant.objects.all() if not user.is_superuser: user_is_manager = Q(tenantrole__user=user) | Q(group__tenantrole__user=user) tenants = tenants.filter(user_is_manager) return tenants def get_link_class_from_model(model): """Get the tenant link model associated with the model class.""" model_class = model if isinstance(model, type) else type(model) if not hasattr(model_class, 'tenantlink'): raise TypeError("This method should only be used on tenant-enabled models.") return model_class.tenantlink.related.model def tenancy_reverse(request, url_name, *args, **kwargs): """Add tenancy information to the URL reversal if multitenancy is enabled.""" if multitenancy_enabled(): # reverse disallows mixing *args and **kwargs. if args: args = (request.group_slug, request.tenant_slug) + args else: kwargs.setdefault('group_slug', request.group_slug) kwargs.setdefault('tenant_slug', request.tenant_slug) return reverse(url_name, args=args, kwargs=kwargs)
Use is_readable instead of file_exists
<?php namespace Ochenta; /** @throws InvalidArgumentException */ function resource_of($resource) { if (is_null($resource)) { return null; } if (is_scalar($resource)) { $stream = fopen('php://temp', 'r+'); if (!empty($resource)) { fwrite($stream, $resource); fseek($stream, 0); } return $stream; } if (is_resource($resource)) { return $resource; } throw new \InvalidArgumentException('Invalid resource'); } /** @throws RuntimeException */ function mimetype_of($resource, $filename=null) { $finfo = finfo_open(FILEINFO_MIME_TYPE); if ($finfo === false) { throw new \RuntimeException('Fileinfo database is not available'); } $mimetype = false; if (is_file($filename) && is_readable($filename)) { $mimetype = finfo_file($finfo, $filename); } if ($mimetype === false) { $contents = false; if (is_string($resource)) { $contents = $resource; } elseif (is_resource($resource)) { $contents = stream_get_contents($resource, -1, 0); } if ($contents !== false) { $mimetype = finfo_buffer($finfo, $contents); } } finfo_close($finfo); if ($mimetype === false) { throw new \RuntimeException('Couldn\'t detect mime type from resource'); } return $mimetype; }
<?php namespace Ochenta; /** @throws InvalidArgumentException */ function resource_of($resource) { if (is_null($resource)) { return null; } if (is_scalar($resource)) { $stream = fopen('php://temp', 'r+'); if (!empty($resource)) { fwrite($stream, $resource); fseek($stream, 0); } return $stream; } if (is_resource($resource)) { return $resource; } throw new \InvalidArgumentException('Invalid resource'); } /** @throws RuntimeException */ function mimetype_of($resource, $filename=null) { $finfo = finfo_open(FILEINFO_MIME_TYPE); if ($finfo === false) { throw new \RuntimeException('Fileinfo database is not available'); } $mimetype = false; if (is_file($filename) && file_exists($filename)) { $mimetype = finfo_file($finfo, $filename); } if ($mimetype === false) { $contents = false; if (is_string($resource)) { $contents = $resource; } elseif (is_resource($resource)) { $contents = stream_get_contents($resource, -1, 0); } if ($contents !== false) { $mimetype = finfo_buffer($finfo, $contents); } } finfo_close($finfo); if ($mimetype === false) { throw new \RuntimeException('Couldn\'t detect mime type from resource'); } return $mimetype; }
Enhance mock of idol user for integration tests (ISO-6) [rev. matthew.gordon]
package com.hp.autonomy.searchcomponents.idol.test; import com.hp.autonomy.frontend.configuration.authentication.CommunityPrincipal; import com.hpe.bigdata.frontend.spring.authentication.AuthenticationInformationRetriever; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Configuration @ConditionalOnProperty(value = "mock.configuration", matchIfMissing = true) public class IdolTestAuthenticationConfiguration { @Bean @Primary @ConditionalOnProperty(value = "mock.authenticationRetriever", matchIfMissing = true) public AuthenticationInformationRetriever<?, CommunityPrincipal> authenticationInformationRetriever() { final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.isAuthenticated()).thenReturn(true); final CommunityPrincipal communityPrincipal = mock(CommunityPrincipal.class); when(communityPrincipal.getId()).thenReturn(1L); when(communityPrincipal.getUsername()).thenReturn("user"); when(communityPrincipal.getName()).thenReturn("user"); when(authentication.getPrincipal()).thenReturn(communityPrincipal); @SuppressWarnings("unchecked") final AuthenticationInformationRetriever<UsernamePasswordAuthenticationToken, CommunityPrincipal> authenticationInformationRetriever = mock(AuthenticationInformationRetriever.class); when(authenticationInformationRetriever.getAuthentication()).thenReturn(authentication); when(authenticationInformationRetriever.getPrincipal()).thenReturn(communityPrincipal); return authenticationInformationRetriever; } }
package com.hp.autonomy.searchcomponents.idol.test; import com.hp.autonomy.frontend.configuration.authentication.CommunityPrincipal; import com.hpe.bigdata.frontend.spring.authentication.AuthenticationInformationRetriever; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Configuration @ConditionalOnProperty(value = "mock.configuration", matchIfMissing = true) public class IdolTestAuthenticationConfiguration { @Bean @Primary @ConditionalOnProperty(value = "mock.authenticationRetriever", matchIfMissing = true) public AuthenticationInformationRetriever<?, CommunityPrincipal> authenticationInformationRetriever() { final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.isAuthenticated()).thenReturn(true); final CommunityPrincipal communityPrincipal = mock(CommunityPrincipal.class); when(communityPrincipal.getId()).thenReturn(1L); when(communityPrincipal.getUsername()).thenReturn("user"); when(authentication.getPrincipal()).thenReturn(communityPrincipal); @SuppressWarnings("unchecked") final AuthenticationInformationRetriever<?, CommunityPrincipal> authenticationInformationRetriever = mock(AuthenticationInformationRetriever.class); when(authenticationInformationRetriever.getAuthentication()).thenReturn(authentication); when(authenticationInformationRetriever.getPrincipal()).thenReturn(communityPrincipal); return authenticationInformationRetriever; } }
Add angular-moment dependency to karma
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../../', frameworks: ['jasmine'], files : [ 'bower_components/underscore/underscore.js', 'bower_components/angular/angular.js', 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-moment/angular-moment.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-toastr/dist/angular-toastr.min.js', 'bower_components/moment/min/moment.min.js', 'bower_components/highlightjs/highlight.pack.js', 'js/**/*.js', 'test/karma/**/*.js' ], reporters: ['junit', 'coverage', 'dots'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/karma/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../../', frameworks: ['jasmine'], files : [ 'bower_components/underscore/underscore.js', 'bower_components/angular/angular.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-toastr/dist/angular-toastr.min.js', 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'bower_components/moment/min/moment.min.js', 'bower_components/highlightjs/highlight.pack.js', 'js/**/*.js', 'test/karma/**/*.js' ], reporters: ['junit', 'coverage', 'dots'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/karma/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
Remove the .only from the generative test
"use strict"; const apiRequest = require( "../../src/token/api-request" ); const storeToken = require( "../../src/token/store-token" ); const Promise = require( "bluebird" ); const expect = require( "expect.js" ); const sinonSandbox = require( "sinon" ).sandbox.create(); describe( "Generative testing", function() { ["SOME", "RANDOM", "STRINGS"].forEach(function( randomString ) { describe( `Given the token '${randomString}'`, function() { let fakeToken; beforeEach(function() { fakeToken = randomString }); describe( `When storing the token '${randomString}'`, function() { let promiseToStoreToken; let mockedApiRequest; beforeEach(function() { mockedApiRequest = sinonSandbox .mock( apiRequest ) .expects( "post" ) .withExactArgs( "/store-token", fakeToken ); promiseToStoreToken = storeToken( fakeToken, apiRequest ); }); afterEach(function() { sinonSandbox.restore(); }); it( "persists", function() { return Promise.try(function() { return promiseToStoreToken; }).then(function() { mockedApiRequest.verify(); }); }); }); }); }); });
"use strict"; const apiRequest = require( "../../src/token/api-request" ); const storeToken = require( "../../src/token/store-token" ); const Promise = require( "bluebird" ); const expect = require( "expect.js" ); const sinonSandbox = require( "sinon" ).sandbox.create(); describe.only( "Generative testing", function() { ["SOME", "RANDOM", "STRINGS"].forEach(function( randomString ) { describe( `Given the token '${randomString}'`, function() { let fakeToken; beforeEach(function() { fakeToken = randomString }); describe( `When storing the token '${randomString}'`, function() { let promiseToStoreToken; let mockedApiRequest; beforeEach(function() { mockedApiRequest = sinonSandbox .mock( apiRequest ) .expects( "post" ) .withExactArgs( "/store-token", fakeToken ); promiseToStoreToken = storeToken( fakeToken, apiRequest ); }); afterEach(function() { sinonSandbox.restore(); }); it( "persists", function() { return Promise.try(function() { return promiseToStoreToken; }).then(function() { mockedApiRequest.verify(); }); }); }); }); }); });
Fix cleaning for Node 5
/* * grunt-google-site-verification * https://github.com/sbstnmsch/grunt-google-site-verification * * Copyright (c) 2016 Sebastian Misch * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ eslint: { default: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ] }, clean: { tests: ['tmp'] }, 'google-site-verification': { default: { }, missingDestination: { options: { code: '123' } }, missingCode: { options: { }, dest: 'tmp' }, withCodeAndDestination: { options: { code: '123' }, dest: 'tmp/' } }, nodeunit: { tests: ['test/*-spec.js'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('test', ['clean', 'eslint', 'google-site-verification', 'nodeunit']); grunt.registerTask('default', ['test']); };
/* * grunt-google-site-verification * https://github.com/sbstnmsch/grunt-google-site-verification * * Copyright (c) 2016 Sebastian Misch * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ eslint: { default: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ] }, clean: { tests: ['tmp'] }, 'google-site-verification': { default: { }, missingDestination: { options: { code: '123' } }, missingCode: { options: { }, dest: 'tmp' }, withCodeAndDestination: { options: { code: '123' }, dest: 'tmp/' } }, nodeunit: { tests: ['test/*-spec.js'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('test', ['clean', 'eslint', 'google-site-verification', 'nodeunit', 'clean']); grunt.registerTask('default', ['test']); };
CRM-2136: Convert Marketing List connection from workflow to controllers
<?php namespace Oro\Bundle\FormBundle\Form\Handler; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\Request; class ApiFormHandler { /** * @var FormInterface */ protected $form; /** * @var Request */ protected $request; /** * @var ObjectManager */ protected $manager; /** * @param Request $request * @param ObjectManager $manager */ public function __construct(Request $request, ObjectManager $manager) { $this->request = $request; $this->manager = $manager; } /** * @param FormInterface $form */ public function setForm(FormInterface $form) { $this->form = $form; } /** * Process form * * @param object $entity * * @return bool True on successful processing, false otherwise */ public function process($entity) { $this->form->setData($entity); if (in_array($this->request->getMethod(), ['POST', 'PUT'])) { $this->form->submit($this->request); if ($this->form->isValid()) { $this->onSuccess($entity); return true; } } return false; } /** * "Success" form handler * * @param object $entity */ protected function onSuccess($entity) { $this->manager->persist($entity); $this->manager->flush(); } }
<?php namespace Oro\Bundle\FormBundle\Form\Handler; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\Request; use OroCRM\Bundle\TaskBundle\Entity\Task; class ApiFormHandler { /** * @var FormInterface */ protected $form; /** * @var Request */ protected $request; /** * @var ObjectManager */ protected $manager; /** * @param Request $request * @param ObjectManager $manager */ public function __construct(Request $request, ObjectManager $manager) { $this->request = $request; $this->manager = $manager; } /** * @param FormInterface $form */ public function setForm(FormInterface $form) { $this->form = $form; } /** * Process form * * @param object $entity * * @return bool True on successful processing, false otherwise */ public function process($entity) { $this->form->setData($entity); if (in_array($this->request->getMethod(), ['POST', 'PUT'])) { $this->form->submit($this->request); if ($this->form->isValid()) { $this->onSuccess($entity); return true; } } return false; } /** * "Success" form handler * * @param object $entity */ protected function onSuccess($entity) { $this->manager->persist($entity); $this->manager->flush(); } }
Fix the name for the installerDb field to match our conventions.
package org.opennms.netmgt.dao.db; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class PopulatedTemporaryDatabaseTestCase extends TemporaryDatabaseTestCase { private InstallerDb m_installerDb; private ByteArrayOutputStream m_outputStream; protected void setUp() throws Exception { super.setUp(); initializeDatabase(); } protected void initializeDatabase() throws Exception { if (!isEnabled()) { return; } m_installerDb = new InstallerDb(); // Create a ByteArrayOutputSteam to effectively throw away output. resetOutputStream(); m_installerDb.setDatabaseName(getTestDatabase()); m_installerDb.setDataSource(getDataSource()); m_installerDb.setCreateSqlLocation( "../opennms-daemon/src/main/filtered/etc/create.sql"); m_installerDb.setStoredProcedureDirectory( "../opennms-daemon/src/main/filtered/etc"); //installerDb.setDebug(true); m_installerDb.readTables(); m_installerDb.createSequences(); m_installerDb.updatePlPgsql(); m_installerDb.addStoredProcedures(); m_installerDb.createTables(); m_installerDb.closeConnection(); } public ByteArrayOutputStream getOutputStream() { return m_outputStream; } public void resetOutputStream() { m_outputStream = new ByteArrayOutputStream(); m_installerDb.setOutputStream(new PrintStream(m_outputStream)); } }
package org.opennms.netmgt.dao.db; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class PopulatedTemporaryDatabaseTestCase extends TemporaryDatabaseTestCase { private InstallerDb installerDb; private ByteArrayOutputStream m_outputStream; protected void setUp() throws Exception { super.setUp(); initializeDatabase(); } protected void initializeDatabase() throws Exception { if (!isEnabled()) { return; } installerDb = new InstallerDb(); // Create a ByteArrayOutputSteam to effectively throw away output. resetOutputStream(); installerDb.setDatabaseName(getTestDatabase()); installerDb.setDataSource(getDataSource()); installerDb.setCreateSqlLocation( "../opennms-daemon/src/main/filtered/etc/create.sql"); installerDb.setStoredProcedureDirectory( "../opennms-daemon/src/main/filtered/etc"); //installerDb.setDebug(true); installerDb.readTables(); installerDb.createSequences(); installerDb.updatePlPgsql(); installerDb.addStoredProcedures(); installerDb.createTables(); installerDb.closeConnection(); } public ByteArrayOutputStream getOutputStream() { return m_outputStream; } public void resetOutputStream() { m_outputStream = new ByteArrayOutputStream(); installerDb.setOutputStream(new PrintStream(m_outputStream)); } }
Add current_month_score and last_month_score to EmployeeListSerializer
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'score', 'last_month_score', 'current_month_score') class EmployeeAvatarSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'avatar') class EmployeeAuthenticationResponse(serializers.Serializer): token = serializers.CharField(max_length=40) user_id = serializers.IntegerField()
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'role', 'skype_id', 'last_month_score', 'current_month_score', 'level', 'score', 'is_active', 'last_login') class EmployeeListSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'level', 'avatar', 'score') class EmployeeAvatarSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'avatar') class EmployeeAuthenticationResponse(serializers.Serializer): token = serializers.CharField(max_length=40) user_id = serializers.IntegerField()
Change GPG password encryption to AES256
from glob import glob import os import shutil from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_bin, path, passphrase) return Database(path, gpg) @classmethod def from_path(cls, path, gpg_bin="gpg"): gpg = load_gpg(binary=gpg_bin, database_path=path) return Database(path, gpg) @property def gpg_key(self): return self.gpg.list_keys(secret=True)[0]["fingerprint"] @property def credentials(self): return [self.credential(os.path.basename(c)) for c in glob(self.path + "/**")] def add(self, credential): encrypted_password = self.gpg.encrypt( credential.password, self.gpg_key, cipher_algo="AES256" ) credential.password = str(encrypted_password) credential.save(database_path=self.path) def delete(self, name): credential_path = os.path.join(self.path, name) shutil.rmtree(credential_path) def credential(self, name): credential_path = os.path.join(self.path, name) credential = Credential.from_path(credential_path) return credential def search(self, query): return [c for c in self.credentials if query in str(c)]
from glob import glob import os import shutil from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_bin, path, passphrase) return Database(path, gpg) @classmethod def from_path(cls, path, gpg_bin="gpg"): gpg = load_gpg(binary=gpg_bin, database_path=path) return Database(path, gpg) @property def gpg_key(self): return self.gpg.list_keys(secret=True)[0]["fingerprint"] @property def credentials(self): return [self.credential(os.path.basename(c)) for c in glob(self.path + "/**")] def add(self, credential): encrypted_password = self.gpg.encrypt( credential.password, self.gpg_key ) credential.password = str(encrypted_password) credential.save(database_path=self.path) def delete(self, name): credential_path = os.path.join(self.path, name) shutil.rmtree(credential_path) def credential(self, name): credential_path = os.path.join(self.path, name) credential = Credential.from_path(credential_path) return credential def search(self, query): return [c for c in self.credentials if query in str(c)]
Remove stuff that doesn't work
<?php namespace MathieuImbert\Slack\Logger; class SlackRequest { private $webhookUrl; /** * SlackRequest constructor. * @param string $webhookUrl */ public function __construct($webhookUrl) { $this->webhookUrl = $webhookUrl; } public function post($text) { /* switch ($level) { case 'success': case 'good': $color = 'good'; break; case 'warning': $color = 'warning'; break; case 'error': case 'danger': case 'critical': $color = 'danger'; break; case 'info': $color = '#3aa3e3'; break; default: $color = "#cccccc"; } */ $payload = [ "username" => "Flow Bot", "icon_emoji" => ":robot_face:", "text" => $text ]; $client = new \GuzzleHttp\Client(); $client->post($this->webhookUrl, ['json' => $payload]); } }
<?php namespace MathieuImbert\Slack\Logger; class SlackRequest { private $webhookUrl; /** * SlackRequest constructor. * @param string $webhookUrl */ public function __construct($webhookUrl) { $this->webhookUrl = $webhookUrl; } public function post($text) { switch ($level) { case 'success': case 'good': $color = 'good'; break; case 'warning': $color = 'warning'; break; case 'error': case 'danger': case 'critical': $color = 'danger'; break; case 'info': $color = '#3aa3e3'; break; default: $color = "#cccccc"; } $payload = [ "username" => "Flow Bot", "icon_emoji" => ":robot_face:", "text" => $text ]; $client = new \GuzzleHttp\Client(); $client->post($this->webhookUrl, ['json' => $payload]); } }
Sort packs newest to oldest.
<?php namespace AppBundle\Repository; use AppBundle\Entity\Cycle; use AppBundle\Entity\Pack; use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Query\ResultSetMappingBuilder; class PackRepository extends EntityRepository { public function __construct(EntityManager $entityManager) { parent::__construct($entityManager, $entityManager->getClassMetadata('AppBundle\Entity\Pack')); } /** * @param Cycle $cycle * @return Pack[] */ public function findByCycleWithCardCount(Cycle $cycle): array { $rsm = new ResultSetMappingBuilder($this->getEntityManager()); $rsm->addRootEntityFromClassMetadata(Pack::class, 'p'); $rsm->addScalarResult('cards', 'count', 'integer'); $selectClause = $rsm->generateSelectClause([ 'p' => 'p', ]); $sql = 'SELECT ' . $selectClause . ', count(c.id) as cards from pack p left join card c on c.pack_id=p.id where p.cycle_id = ? group by p.id order by p.position DESC'; $query = $this->getEntityManager()->createNativeQuery($sql, $rsm); $query->setParameter(1, $cycle->getId()); return array_map(function ($item) { /** @var Pack $pack */ $pack = $item[0]; $pack->setCardCount($item['count']); return $pack; }, $query->getResult()); } }
<?php namespace AppBundle\Repository; use AppBundle\Entity\Cycle; use AppBundle\Entity\Pack; use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Query\ResultSetMappingBuilder; class PackRepository extends EntityRepository { public function __construct(EntityManager $entityManager) { parent::__construct($entityManager, $entityManager->getClassMetadata('AppBundle\Entity\Pack')); } /** * @param Cycle $cycle * @return Pack[] */ public function findByCycleWithCardCount(Cycle $cycle): array { $rsm = new ResultSetMappingBuilder($this->getEntityManager()); $rsm->addRootEntityFromClassMetadata(Pack::class, 'p'); $rsm->addScalarResult('cards', 'count', 'integer'); $selectClause = $rsm->generateSelectClause([ 'p' => 'p', ]); $sql = 'SELECT ' . $selectClause . ', count(c.id) as cards from pack p left join card c on c.pack_id=p.id where p.cycle_id = ? group by p.id order by p.position'; $query = $this->getEntityManager()->createNativeQuery($sql, $rsm); $query->setParameter(1, $cycle->getId()); return array_map(function ($item) { /** @var Pack $pack */ $pack = $item[0]; $pack->setCardCount($item['count']); return $pack; }, $query->getResult()); } }
feat: Add abit of visual jazz to the gulp output
var fs = require('fs'); var path = require('path'); var chalk = require('chalk'); var viewsPath = path.join(process.cwd(), 'views') var partialsPath = path.join(viewsPath, '_partials'); var componentPath; var hbsFileName; var scssFileName; module.exports = function(gulp, argv) { gulp.task('new-component', function (cb) { if(!argv.name) { console.log(''); console.log('A component must have a name'); console.log(''); console.log('Example usage:') console.log('gulp component --name header'); console.log(''); } else { hbsFileName = argv.name + '.hbs'; scssFileName = argv.name + '.scss'; componentPath = path.join(partialsPath, argv.name); fs.mkdirSync(componentPath); console.log(''); console.log(chalk.green('✓ Folder "%s" created'), argv.name); fs.writeFileSync(path.join(componentPath, hbsFileName), '<h1>' + argv.name +'</h1>', 'utf8'); console.log(chalk.green('✓ Handlebars file "%s" created'), hbsFileName); fs.writeFileSync(path.join(componentPath, scssFileName), '//' + argv.name + ' styles', 'utf8'); console.log(chalk.green('✓ Sass file "%s" created'), scssFileName); console.log('') console.log(chalk.bold('Component files created in "%s"'), componentPath); console.log('') } cb(); }); }
var fs = require('fs'); var path = require('path'); var chalk = require('chalk'); var viewsPath = path.join(process.cwd(), 'views') var partialsPath = path.join(viewsPath, '_partials'); var componentPath; var hbsFileName; var scssFileName; module.exports = function(gulp, argv) { gulp.task('new-component', function (cb) { if(!argv.name) { console.log(''); console.log('A component must have a name'); console.log(''); console.log('Example usage:') console.log('gulp component --name header'); console.log(''); } else { hbsFileName = argv.name + '.hbs'; scssFileName = argv.name + '.scss'; componentPath = path.join(partialsPath, argv.name); fs.mkdirSync(componentPath); console.log(chalk.green('Folder "%s" created'), argv.name); fs.writeFileSync(path.join(componentPath, hbsFileName), '<h1>' + argv.name +'</h1>', 'utf8'); console.log(chalk.green('Handlebars file "%s" created'), hbsFileName); fs.writeFileSync(path.join(componentPath, scssFileName), '//' + argv.name + ' styles', 'utf8'); console.log(chalk.green('Sass file "%s" created'), scssFileName); console.log(chalk.green('Component files created in "%s"'), componentPath); } cb(); }); }
Use correct UserDTO parameter when searching
<?php namespace App\Service; use App\Classes\ElasticSearchBase; use App\Entity\DTO\UserDTO; class Search extends ElasticSearchBase { /** * @param array $params * @return array * @throws \Exception when the search service isn't setup */ protected function search(array $params) : array { if (!$this->enabled) { throw new \Exception("Search is not configured, isEnabled() should be called before calling this method"); } return $this->client->search($params); } /** * @param string $query * @return array * @throws \Exception when search is not configured */ public function userIdsQuery(string $query) { if (!$this->enabled) { throw new \Exception("Search is not configured, isEnabled() should be called before calling this method"); } $params = [ 'type' => UserDTO::class, 'index' => self::PRIVATE_INDEX, 'body' => [ 'query' => [ 'query_string' => [ 'query' => "*${query}*", ] ], "_source" => [ '_id' ] ] ]; $results = $this->search($params); return array_map(function (array $arr) { return $arr['_id']; }, $results['hits']['hits']); } }
<?php namespace App\Service; use App\Classes\ElasticSearchBase; use App\Entity\User; class Search extends ElasticSearchBase { /** * @param array $params * @return array * @throws \Exception when the search service isn't setup */ protected function search(array $params) : array { if (!$this->enabled) { throw new \Exception("Search is not configured, isEnabled() should be called before calling this method"); } return $this->client->search($params); } /** * @param string $query * @return array * @throws \Exception when search is not configured */ public function userIdsQuery(string $query) { if (!$this->enabled) { throw new \Exception("Search is not configured, isEnabled() should be called before calling this method"); } $params = [ 'type' => User::class, 'index' => self::PRIVATE_INDEX, 'body' => [ 'query' => [ 'query_string' => [ 'query' => "*${query}*", ] ], "_source" => [ '_id' ] ] ]; $results = $this->search($params); return array_map(function (array $arr) { return $arr['_id']; }, $results['hits']['hits']); } }
Use os.path.join to join paths. Use relative paths.
''' Created on 03.02.2016. @author: Lazar ''' import os from textx.metamodel import metamodel_from_file from concepts.layout import Layout from concepts.object import Object from concepts.property import Property from concepts.selector_object import SelectorObject, selector_object_processor from concepts.selector_view import SelectorView from concepts.view import View from concepts.page import page_processor if __name__ == "__main__": builtins = {x : View(None,x, []) for x in View.basic_type_names} layouts = { 'border' : Layout('border', ['top','bottom','center', 'left','right'], None), 'grid' : Layout('grid', [], None) } builtins.update(layouts) obj_processors = { 'SelectorObject' : selector_object_processor, 'Page' : page_processor } this_dir = os.path.dirname(__file__) my_mm = metamodel_from_file(os.path.join(this_dir, '..', 'grammar', 'grammar.tx'), classes = [ View, Object, Property, SelectorObject, SelectorView ], builtins = builtins, debug = False) my_mm.register_obj_processors(obj_processors) # Create model my_model = my_mm.model_from_file(os.path.join(this_dir, '..', '..', 'test', 'test.gn')) print(my_model.entity)
''' Created on 03.02.2016. @author: Lazar ''' from textx.metamodel import metamodel_from_file from concepts.layout import Layout from concepts.object import Object from concepts.property import Property from concepts.selector_object import SelectorObject, selector_object_processor from concepts.selector_view import SelectorView from concepts.view import View from concepts.page import page_processor if __name__ == "__main__": builtins = {x : View(None,x, []) for x in View.basic_type_names} layouts = { 'border' : Layout('border', ['top','bottom','center','left','right'], None), 'grid' : Layout('grid', [], None) } builtins.update(layouts) obj_processors = { 'SelectorObject' : selector_object_processor, 'Page' : page_processor } my_mm = metamodel_from_file('../grammar/grammar.tx', classes = [ View, Object, Property, SelectorObject, SelectorView ], builtins = builtins, debug = False) my_mm.register_obj_processors(obj_processors) # Create model my_model = my_mm.model_from_file('../../test/test.gn') my_model
BUmp patch to include new README fix The previous README version was incorrect. Bumping the version to correct the display on PyPi.
"""Setuptools configuration for rpmvenv.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='rpmvenv', version='0.13.1', url='https://github.com/kevinconway/rpmvenv', description='RPM packager for Python virtualenv.', author="Kevin Conway", author_email="[email protected]", long_description=README, license='MIT', packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), install_requires=[ 'jinja2', 'venvctrl', 'argparse', 'confpy', 'ordereddict', 'semver', ], entry_points={ 'console_scripts': [ 'rpmvenv = rpmvenv.cli:main', ], 'rpmvenv.extensions': [ 'core = rpmvenv.extensions.core:Extension', 'file_permissions = rpmvenv.extensions.files.permissions:Extension', 'file_extras = rpmvenv.extensions.files.extras:Extension', 'python_venv = rpmvenv.extensions.python.venv:Extension', 'blocks = rpmvenv.extensions.blocks.generic:Extension', ] }, package_data={ "rpmvenv": ["templates/*"], }, )
"""Setuptools configuration for rpmvenv.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='rpmvenv', version='0.13.0', url='https://github.com/kevinconway/rpmvenv', description='RPM packager for Python virtualenv.', author="Kevin Conway", author_email="[email protected]", long_description=README, license='MIT', packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']), install_requires=[ 'jinja2', 'venvctrl', 'argparse', 'confpy', 'ordereddict', 'semver', ], entry_points={ 'console_scripts': [ 'rpmvenv = rpmvenv.cli:main', ], 'rpmvenv.extensions': [ 'core = rpmvenv.extensions.core:Extension', 'file_permissions = rpmvenv.extensions.files.permissions:Extension', 'file_extras = rpmvenv.extensions.files.extras:Extension', 'python_venv = rpmvenv.extensions.python.venv:Extension', 'blocks = rpmvenv.extensions.blocks.generic:Extension', ] }, package_data={ "rpmvenv": ["templates/*"], }, )
Fix Authenticatable mixing using wrong protocol value
'use strict'; var request = require('../request') ; var token = {}; var Authenticatable = { token: { get: function () { return token; } }, authenticate: { value: function (user, password) { if (!user) { throw { name: 'ArgumentError', message: user + ' is not a valid username' }; } if (!password) { throw { name: 'ArgumentError', message: password + ' is not a valid password' }; } return request({ method: 'post', protocol: this.auth.protocol && this.auth.protocol + ':', host: this.auth.host || this.host, port: this.auth.port || 9100, path: this.path, withCredentials: false, headers: { 'content-type': 'application/json' }, rejectUnauthorized: this.rejectUnauthorized, auth: [user, password].join(':') }).then(function (res) { if (res.statusCode !== 201) { throw { name: 'APIError', status: res.statusCode, message: res.body.faultstring || res.body }; } token = res.body; return res.body; }); } } }; module.exports = Authenticatable;
'use strict'; var request = require('../request') ; var token = {}; var Authenticatable = { token: { get: function () { return token; } }, authenticate: { value: function (user, password) { if (!user) { throw { name: 'ArgumentError', message: user + ' is not a valid username' }; } if (!password) { throw { name: 'ArgumentError', message: password + ' is not a valid password' }; } return request({ method: 'post', protocol: this.protocol && this.protocol + ':', host: this.auth.host || this.host, port: this.auth.port || 9100, path: this.path, withCredentials: false, headers: { 'content-type': 'application/json' }, rejectUnauthorized: this.rejectUnauthorized, auth: [user, password].join(':') }).then(function (res) { if (res.statusCode !== 201) { throw { name: 'APIError', status: res.statusCode, message: res.body.faultstring || res.body }; } token = res.body; return res.body; }); } } }; module.exports = Authenticatable;
Use README in long description.
from setuptools import setup, find_packages version = '1.0a1' import sys, functools if sys.version_info[0] >= 3: open = functools.partial(open, encoding='utf-8') setup(name='pystunnel', version=version, description='Python interface to stunnel', long_description=open('README.rst').read() + '\n' + open('CHANGES.rst').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='stunnel ssl tunnel tls', author='Stefan H. Holek', author_email='[email protected]', url='https://pypi.python.org/pypi/pystunnel', license='AGPLv3', packages=find_packages(), include_package_data=True, zip_safe=False, #test_suite='pystunnel.tests', install_requires=[ 'setuptools', 'six', ], entry_points={ 'console_scripts': 'pystunnel=pystunnel.pystunnel:main', }, )
from setuptools import setup, find_packages version = '1.0a1' setup(name='pystunnel', version=version, description='Python interface to stunnel', #long_description=open('README.rst').read() + '\n' + # open('CHANGES.rst').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='stunnel ssl tunnel tls', author='Stefan H. Holek', author_email='[email protected]', url='https://pypi.python.org/pypi/pystunnel', license='AGPLv3', packages=find_packages(), include_package_data=True, zip_safe=False, #test_suite='pystunnel.tests', install_requires=[ 'setuptools', 'six', ], entry_points={ 'console_scripts': 'pystunnel=pystunnel.pystunnel:main', }, )
Update blog model with a more descriptive name
''' Blog App This module determines how to display the Blog app in Django's admin and lists other model functions. ''' from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from tunobase.core import models as core_models class Blog(core_models.ContentModel): ''' Blogs the Site has ''' class Meta: verbose_name = 'Blog Category' verbose_name_plural = 'Blog Categories' class BlogEntry(core_models.ContentModel): ''' Entries per Blog ''' blog = models.ForeignKey(Blog, related_name='entries') author_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='blog_entries_authored', null=True, blank=True ) authors_alternate = models.CharField( max_length=512, blank=True, null=True ) class Meta: verbose_name_plural = 'Blog entries' def get_absolute_url(self): return reverse('blog_entry_detail', args=(self.slug,)) @property def authors(self): ''' Return a list of authors selected as users on the system and a list of alternate authors as not users on the system if either exist ''' authors_dict = {} auth_users = self.author_users.all() if auth_users: authors_dict.update({ 'users': auth_users }) if self.authors_alternate: authors_dict.update({ 'alternate': self.authors_alternate.split(',') }) return authors_dict
''' Blog App This module determines how to display the Blog app in Django's admin and lists other model functions. ''' from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from tunobase.core import models as core_models class Blog(core_models.ContentModel): ''' Blogs the Site has ''' class BlogEntry(core_models.ContentModel): ''' Entries per Blog ''' blog = models.ForeignKey(Blog, related_name='entries') author_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='blog_entries_authored', null=True, blank=True ) authors_alternate = models.CharField( max_length=512, blank=True, null=True ) class Meta: verbose_name_plural = 'Blog entries' def get_absolute_url(self): return reverse('blog_entry_detail', args=(self.slug,)) @property def authors(self): ''' Return a list of authors selected as users on the system and a list of alternate authors as not users on the system if either exist ''' authors_dict = {} auth_users = self.author_users.all() if auth_users: authors_dict.update({ 'users': auth_users }) if self.authors_alternate: authors_dict.update({ 'alternate': self.authors_alternate.split(',') }) return authors_dict
BAP-10985: Update the rules displaying autocomplete result for business unit owner field
<?php namespace Oro\Bundle\OrganizationBundle\Form\Transformer; use Doctrine\Common\Collections\Collection; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager; use Symfony\Component\Form\DataTransformerInterface; class BusinessUnitTreeTransformer implements DataTransformerInterface { /** @var BusinessUnitManager */ protected $manager; /** @var BusinessUnit */ protected $entity; public function __construct($manager) { $this->manager = $manager; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (null == $value) { return 0; } elseif (is_array($value)) { foreach($value as &$val) { if ($val === "") { $val =0; } } return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]); } return $this->manager->getBusinessUnitRepo()->find($value); } /** * {@inheritdoc} */ public function transform($value) { if (null == $value) { return 0; } if (is_array($value) || (is_object($value) && ($value instanceof Collection))) { $result = []; foreach ($value as $object) { $result[] = $object->getId(); } } elseif (is_object($value)) { $result = $value->getId(); } else { $result = $value; } return $result; } }
<?php namespace Oro\Bundle\OrganizationBundle\Form\Transformer; use Doctrine\Common\Collections\Collection; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager; use Symfony\Component\Form\DataTransformerInterface; class BusinessUnitTreeTransformer implements DataTransformerInterface { /** @var BusinessUnitManager */ protected $manager; /** @var BusinessUnit */ protected $entity; public function __construct($manager) { $this->manager = $manager; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (null === $value) { return null; } elseif (is_array($value)) { return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]); } return $this->manager->getBusinessUnitRepo()->find($value); } /** * {@inheritdoc} */ public function transform($value) { if (null === $value) { return null; } if (is_array($value) || (is_object($value) && ($value instanceof Collection))) { $result = []; foreach ($value as $object) { $result[] = $object->getId(); } } elseif (is_object($value)) { $result = $value->getId(); } else { $result = $value; } return $result; } }
Exclude examples from the package installation PiperOrigin-RevId: 398741057 Change-Id: I7fd7921b8275b9f8b8994b0f20f0d40e814c3a23 GitOrigin-RevId: 4ca481ae4f7c6cf62e38a970f13a14716f9661fc
# Copyright 2021 DeepMind Technologies Limited # # 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. """Setup configuration specifying XManager dependencies.""" from setuptools import find_namespace_packages from setuptools import setup setup( name='xmanager', version='0.1.0', description='A framework for managing experiments', author='DeepMind Technologies Limited', packages=find_namespace_packages(exclude=['examples.*']), include_package_data=True, package_data={'': ['*.sh', '*.sql']}, python_requires='>=3.7', install_requires=[ 'absl-py', 'async_generator', 'attrs', 'docker', 'google-api-core', 'google-api-python-client', 'google-auth', 'google-cloud-aiplatform>=1.4.0', 'google-cloud-storage', 'humanize', 'immutabledict', 'kubernetes', 'sqlalchemy==1.2', 'termcolor', ], entry_points={ 'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',], }, )
# Copyright 2021 DeepMind Technologies Limited # # 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. """Setup configuration specifying XManager dependencies.""" from setuptools import find_namespace_packages from setuptools import setup setup( name='xmanager', version='0.1.0', description='A framework for managing experiments', author='DeepMind Technologies Limited', packages=find_namespace_packages(), include_package_data=True, package_data={'': ['*.sh', '*.sql']}, python_requires='>=3.7', install_requires=[ 'absl-py', 'async_generator', 'attrs', 'docker', 'google-api-core', 'google-api-python-client', 'google-cloud-aiplatform>=1.4.0', 'google-auth', 'google-cloud-storage', 'humanize', 'immutabledict', 'kubernetes', 'sqlalchemy==1.2', 'termcolor', ], entry_points={ 'console_scripts': ['xmanager = xmanager.cli.cli:entrypoint',], }, )
Make Contact details change when selecting different ones
angular.module("yds").controller("TrafficCountsController", ["$scope", "$timeout", "DashboardService", function ($scope, $timeout, DashboardService) { var scope = $scope; scope.galwayProjectId = "http://linkedeconomy.org/resource/Contract/AwardNotice/2013208591/5795646"; scope.lang = "en"; scope.showGrid = true; scope.showProjectInfo = false; // Create the object for the clicked traffic point scope.selectedPoint = { "point": null }; /** * Get the selected contract from the DashboardService, and show or hide the Contract details */ var gridSelectionHandler = function () { var selectedContract = _.first(DashboardService.getGridSelection("galway_contract")); DashboardService.setSelectedProject(selectedContract, null); scope.showProjectInfo = false; $timeout(function () { scope.showProjectInfo = !_.isUndefined(selectedContract); }); }; // Watch changes in the selected point, and set it as selected in the DashboardService scope.$watch("selectedPoint.point", function (newPoint) { // Force a refresh of the related contracts grid scope.showGrid = false; scope.showProjectInfo = false; $timeout(function () { scope.showGrid = true; DashboardService.setGridSelection("galway_traffic_point", newPoint); }); }); // Watch for changes in the selected contract, to show the Contract details page DashboardService.subscribeGridSelectionChanges(scope, gridSelectionHandler); } ]);
angular.module("yds").controller("TrafficCountsController", ["$scope", "$timeout", "DashboardService", function ($scope, $timeout, DashboardService) { var scope = $scope; scope.galwayProjectId = "http://linkedeconomy.org/resource/Contract/AwardNotice/2013208591/5795646"; scope.lang = "en"; scope.showGrid = true; scope.showProjectInfo = false; // Create the object for the clicked traffic point scope.selectedPoint = { "point": null }; // Watch changes in the selected point, and set it as selected in the DashboardService scope.$watch("selectedPoint.point", function (newPoint) { // Force a refresh of the related contracts grid scope.showGrid = false; $timeout(function () { scope.showGrid = true; DashboardService.setGridSelection("galway_traffic_point", newPoint); }); }); // Watch for changes in the selected contract, to show the Contract details page DashboardService.subscribeGridSelectionChanges(scope, function () { var selectedContract = _.first(DashboardService.getGridSelection("galway_contract")); DashboardService.setSelectedProject(selectedContract, null); scope.showProjectInfo = !_.isUndefined(selectedContract); }); } ]);
Fix to install extension 'cycgkit.boundingbox'.
from setuptools import Extension, setup from Cython.Build import cythonize from sys import platform from distutils.sysconfig import get_config_vars import os (opt,) = get_config_vars('OPT') if opt: os.environ['OPT'] = " ".join(flag for flag in opt.split() if flag != '-Wstrict-prototypes') incl = ['./include'] extrac = [] if platform == 'win32': rldirs = [] extrac.append('/EHsc') elif platform == 'darwin': rldirs = [] else: rldirs = ["$ORIGIN"] extrac.extend(["-w", "-O3"]) setup( name="cycgkit", packages=["cycgkit", 'cycgkit.cgtypes'], ext_modules=cythonize([ Extension('cycgkit.cgtypes.*', ["cycgkit/cgtypes/*.pyx", './src/vec3.cpp'], include_dirs=incl, runtime_library_dirs=rldirs, extra_compile_args=extrac, language="c++"), Extension('cycgkit.boundingbox', ["cycgkit/boundingbox.pyx", './src/boundingbox.cpp', './src/vec3.cpp'], include_dirs=incl, runtime_library_dirs=rldirs, extra_compile_args=extrac, language="c++") ]), )
from setuptools import Extension, setup from Cython.Build import cythonize from sys import platform from distutils.sysconfig import get_config_vars import os (opt,) = get_config_vars('OPT') if opt: os.environ['OPT'] = " ".join(flag for flag in opt.split() if flag != '-Wstrict-prototypes') incl = ['./include'] extrac = [] if platform == 'win32': rldirs = [] extrac.append('/EHsc') elif platform == 'darwin': rldirs = [] else: rldirs = ["$ORIGIN"] extrac.extend(["-w", "-O3"]) setup( name="cycgkit", packages=["cycgkit", 'cycgkit.cgtypes', 'cycgkit.boundingbox'], ext_modules=cythonize([ Extension('cycgkit.cgtypes.*', ["cycgkit/cgtypes/*.pyx", './src/vec3.cpp'], include_dirs=incl, runtime_library_dirs=rldirs, extra_compile_args=extrac, language="c++"), Extension('cycgkit.boundingbox', ["cycgkit/boundingbox.pyx", './src/boundingbox.cpp', './src/vec3.cpp'], include_dirs=incl, runtime_library_dirs=rldirs, extra_compile_args=extrac, language="c++") ]), )
Remove exception messages and add equality test
<?php /** * UsernameTest.php * * @copyright 2013 George D. Cooksey, III * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace VeritasTest\Identity; use PHPUnit_Framework_TestCase as TestCase; use Veritas\Identity\Username; class UsernameTest extends TestCase { public function testClassExists() { $this->assertTrue(class_exists('Veritas\Identity\Username')); } public function testClassImplementsCredential() { $this->assertInstanceOf('Veritas\Identity\Credential', new Username('username')); } public function testConstructSetsValue() { $subject = new Username('username'); $this->assertTrue($subject->verify('username')); } public function testConstructChecksMinimumLength() { $this->setExpectedException('Veritas\Identity\Exception\UsernameLengthException'); new Username('bad'); } public function testConstructChecksMaximumLength() { $this->setExpectedException('Veritas\Identity\Exception\UsernameLengthException'); new Username( 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf' . 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf' ); } public function testToStringReturnsValue() { $subject = new Username('username'); $this->assertEquals('username', (string) $subject); } public function testEqualsReturnsBool() { $subject = new Username('username'); $this->assertFalse($subject->equals(new Username('test failure'))); } }
<?php /** * UsernameTest.php * * @copyright 2013 George D. Cooksey, III * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace VeritasTest\Identity; use PHPUnit_Framework_TestCase as TestCase; use Veritas\Identity\Username; class UsernameTest extends TestCase { public function testClassExists() { $this->assertTrue(class_exists('Veritas\Identity\Username')); } public function testClassImplementsCredential() { $this->assertInstanceOf('Veritas\Identity\Credential', new Username('username')); } public function testConstructSetsValue() { $subject = new Username('username'); $this->assertTrue($subject->verify('username')); } public function testConstructChecksMinimumLength() { $this->setExpectedException( 'Veritas\Identity\Exception\UsernameLengthException', 'Value must be a minimum of 8 characters' ); new Username('bad'); } public function testConstructChecksMaximumLength() { $this->setExpectedException( 'Veritas\Identity\Exception\UsernameLengthException', 'Value must be a maximum of 125 characters' ); new Username( 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf' . 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf' ); } public function testToStringReturnsValue() { $subject = new Username('username'); $this->assertEquals('username', (string) $subject); } }
Use the unexpected-dev project on browserstack for Travis "PR" builds https://github.com/travis-ci/travis-ci/issues/6652
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], browserDisconnectTimeout: '60000', browserNoActivityTimeout: '60000', client: { mocha: { reporter: 'html', timeout: 60000 } }, browserStack: { video: false, project: process.env.TRAVIS_BRANCH === 'master' && !process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds ? 'unexpected' : 'unexpected-dev' }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7' } }, reporters: ['dots', 'BrowserStack'] }); };
module.exports = function(config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/es5-shim.js', 'vendor/es5-sham.js', 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js' ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], browserDisconnectTimeout: '60000', browserNoActivityTimeout: '60000', client: { mocha: { reporter: 'html', timeout: 60000 } }, browserStack: { video: false, project: process.env.TRAVIS_BRANCH === 'master' ? 'unexpected' : 'unexpected-dev' }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7' } }, reporters: ['dots', 'BrowserStack'] }); };
Set output target as UMD
'use strict'; var path = require('path'); var webpack = require('webpack'); var prod = process.env.NODE_ENV === 'production'; var config = { devtool: prod ? null : 'eval', entry: [ path.join(__dirname, 'demo', 'src', 'demo.js') ], output: { path: path.join(__dirname, 'demo', 'dist', 'js'), filename: 'demo.js', publicPath: '/demo/dist', libraryTarget: 'umd' }, externals: { 'react': { root: 'React', commonjs: 'react', commonjs2: 'react', amd: 'react' }, 'react-dom': { root: 'ReactDOM', commonjs: 'react-dom', commonjs2: 'react-dom', amd: 'react-dom' } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, presets: ['react'] } }, { test: /\.json$/, loader: 'json' }] }, plugins: [ new webpack.NoErrorsPlugin() ] }; if (prod) { config.plugins.push(new webpack.optimize.DedupePlugin()); config.plugins.push(new webpack.optimize.OccurenceOrderPlugin(true)); config.plugins.push(new webpack.optimize.UglifyJsPlugin()); } module.exports = config;
'use strict'; var path = require('path'); var webpack = require('webpack'); var prod = process.env.NODE_ENV === 'production'; var config = { devtool: prod ? null : 'eval', entry: [ path.join(__dirname, 'demo', 'src', 'demo.js') ], output: { path: path.join(__dirname, 'demo', 'dist', 'js'), filename: 'demo.js', publicPath: '/demo/dist' }, externals: { 'react': { root: 'React', commonjs: 'react', commonjs2: 'react', amd: 'react' }, 'react-dom': { root: 'ReactDOM', commonjs: 'react-dom', commonjs2: 'react-dom', amd: 'react-dom' } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, presets: ['react'] } }, { test: /\.json$/, loader: 'json' }] }, plugins: [ new webpack.NoErrorsPlugin() ] }; if (prod) { config.plugins.push(new webpack.optimize.DedupePlugin()); config.plugins.push(new webpack.optimize.OccurenceOrderPlugin(true)); config.plugins.push(new webpack.optimize.UglifyJsPlugin()); } module.exports = config;
Fix in parser test for instances
var vows = require('vows'), expect = require('expect.js'), types = require('../lib/types'), AST = require('../lib/ast'), parseAndWalk = require('./helper').parseAndWalk describe('Parser', function () { describe('given a var declaration', function () { it('should parse an implicit type', function () { var topic = 'var foo = 1', tree = parseAndWalk(topic) expect(tree.statements.length).to.eql(1) var decl = tree.statements[0] // Check that it parsed as a var-assignment with a type of Number expect(decl).to.be.an(AST.Assignment) expect(decl.type).to.eql('var') expect(decl.lvalue.type).to.be.a(types.Instance) expect(decl.lvalue.type.type).to.be.a(types.Number) }) it('should parse an explicit type', function () { var topic = 'var foo: Integer = 1' parseAndWalk(topic) }) it('should fail on an invalid explicit type', function () { var topic = 'var foo: Integer = func () -> Integer { return 1 }', tree = false try { tree = parseAndWalk(topic) // tree.print() } catch (err) { // Caught an error successfully expect(err.name).to.eql('TypeError') expect(err.message).to.contain('Unequal types in declaration') return } expect(tree).to.be(false) }) }) })
var vows = require('vows'), expect = require('expect.js'), types = require('../lib/types'), AST = require('../lib/ast'), parseAndWalk = require('./helper').parseAndWalk describe('Parser', function () { describe('given a var declaration', function () { it('should parse an implicit type', function () { var topic = 'var foo = 1', tree = parseAndWalk(topic) expect(tree.statements.length).to.eql(1) var decl = tree.statements[0] // Check that it parsed as a var-assignment with a type of Number expect(decl).to.be.an(AST.Assignment) expect(decl.type).to.eql('var') expect(decl.lvalue.type).to.be.a(types.Number) }) it('should parse an explicit type', function () { var topic = 'var foo: Integer = 1' parseAndWalk(topic) }) it('should fail on an invalid explicit type', function () { var topic = 'var foo: Integer = func () -> Integer { return 1 }', tree = false try { tree = parseAndWalk(topic) // tree.print() } catch (err) { // Caught an error successfully expect(err.name).to.eql('TypeError') expect(err.message).to.contain('Unequal types in declaration') return } expect(tree).to.be(false) }) }) })
Use var for compatibility with Android 4.x
var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation === 'keys') { var keys = []; var key = localStorage.key(0); if(!key) { return success(keys); } var i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle;
var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if(operation === 'keys') { const keys = []; let key = localStorage.key(0); if(!key) { return success(keys); } let i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle;
Make the description column searchable Works, but need to refresh the page to get rid of the "extra" results. Could be related to https://github.com/rappasoft/laravel-livewire-tables/discussions/374
<?php namespace App\Http\Livewire; use App\Models\SurveyScheduleView; use Illuminate\Database\Eloquent\Builder; use Rappasoft\LaravelLivewireTables\DataTableComponent; use Rappasoft\LaravelLivewireTables\Views\Column; class SurveyScheduleTable extends DataTableComponent { public string $defaultSortColumn = 'prevSurveyDate'; public string $defaultSortDirection = 'asc'; public bool $singleColumnSorting = false; public bool $paginationEnabled = false; public function columns(): array { return [ Column::make('ID', 'id'), Column::make('Description', 'description') ->searchable(), Column::make('Previous', 'prevSurveyDate') ->sortable(), Column::make('Prev Survey ID', 'prevSurveyID'), Column::make('Current', 'currSurveyDate') ->sortable(), Column::make('Current Survey ID', 'currSurveyID'), ]; } public function rowView(): string { // Use a custom row view so that things like the manufacturer, // modality, description, location can be made clickable URLs return 'livewire-tables.survey-schedule-row'; } public function query(): Builder { return SurveyScheduleView::query() ->with('machine', 'prevSurvey', 'currSurvey'); } }
<?php namespace App\Http\Livewire; use App\Models\SurveyScheduleView; use Illuminate\Database\Eloquent\Builder; use Rappasoft\LaravelLivewireTables\DataTableComponent; use Rappasoft\LaravelLivewireTables\Views\Column; class SurveyScheduleTable extends DataTableComponent { public string $defaultSortColumn = 'prevSurveyDate'; public string $defaultSortDirection = 'asc'; public bool $singleColumnSorting = false; public bool $paginationEnabled = false; public function columns(): array { return [ Column::make('ID', 'id') , Column::make('Description', 'description'), Column::make('Previous', 'prevSurveyDate') ->sortable(), Column::make('Prev Survey ID', 'prevSurveyID'), Column::make('Current', 'currSurveyDate') ->sortable(), Column::make('Current Survey ID', 'currSurveyID'), ]; } public function rowView(): string { // Use a custom row view so that things like the manufacturer, // modality, description, location can be made clickable URLs return 'livewire-tables.survey-schedule-row'; } public function query(): Builder { return SurveyScheduleView::query() ->with('machine', 'prevSurvey', 'currSurvey'); } }
Use request path info as fallback
<?php namespace Kunstmaan\LanguageChooserBundle\LocaleGuesser; use Lunetics\LocaleBundle\LocaleGuesser\AbstractLocaleGuesser; use Lunetics\LocaleBundle\Validator\MetaValidator; use Symfony\Component\HttpFoundation\Request; /** * Locale Guesser for detecting the locale in the url * * @author Matthias Breddin <[email protected]> * @author Christophe Willemsen <[email protected]> */ class UrlLocaleGuesser extends AbstractLocaleGuesser { /** * @var MetaValidator */ private $metaValidator; /** * Constructor * * @param MetaValidator $metaValidator MetaValidator */ public function __construct(MetaValidator $metaValidator) { $this->metaValidator = $metaValidator; } /** * Method that guess the locale based on the Url * * @param Request $request * * @return boolean True if locale is detected, false otherwise */ public function guessLocale(Request $request) { $localeValidator = $this->metaValidator; $path = $request->getPathInfo(); if ($request->attributes->has('path')) { $path = $request->attributes->get('path'); } if (!$path) { return false; } $parts = array_filter(explode("/", $path)); $locale = array_shift($parts); if ($localeValidator->isAllowed($locale)) { $this->identifiedLocale = $locale; return true; } return false; } }
<?php namespace Kunstmaan\LanguageChooserBundle\LocaleGuesser; use Lunetics\LocaleBundle\LocaleGuesser\AbstractLocaleGuesser; use Lunetics\LocaleBundle\Validator\MetaValidator; use Symfony\Component\HttpFoundation\Request; /** * Locale Guesser for detecting the locale in the url * * @author Matthias Breddin <[email protected]> * @author Christophe Willemsen <[email protected]> */ class UrlLocaleGuesser extends AbstractLocaleGuesser { /** * @var MetaValidator */ private $metaValidator; /** * Constructor * * @param MetaValidator $metaValidator MetaValidator */ public function __construct(MetaValidator $metaValidator) { $this->metaValidator = $metaValidator; } /** * Method that guess the locale based on the Url * * @param Request $request * * @return boolean True if locale is detected, false otherwise */ public function guessLocale(Request $request) { $localeValidator = $this->metaValidator; if ($path = $request->attributes->get('path')) { $parts = array_filter(explode("/", $path)); $locale = array_shift($parts); if ($localeValidator->isAllowed($locale)) { $this->identifiedLocale = $locale; return true; } } return false; } }