text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add Creator to Status API
package octokit import ( "fmt" "time" ) type Status struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` State string `json:"state"` TargetUrl string `json:"target_url"` Description string `json:"description"` Id int `json:"id"` Url string `json:"url"` Creator StatusCreator `json:"creator"` } type StatusCreator struct { Login string `json:"login"` Id int `json:"id"` AvatarUrl string `json:"avatar_url"` GravatarId string `json:"gravatar_id"` Url string `json:"url"` } func (c *Client) Statuses(repo Repository, sha string) ([]Status, error) { path := fmt.Sprintf("repos/%s/statuses/%s", repo, sha) var statuses []Status err := c.jsonGet(path, nil, &statuses) if err != nil { return nil, err } return statuses, nil }
package octokit import ( "fmt" "time" ) type Status struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` State string `json:"state"` TargetUrl string `json:"target_url"` Description string `json:"description"` Id int `json:"id"` Url string `json:"url"` } type StatusCreator struct { Login string `json:"login"` Id int `json:"id"` AvatarUrl string `json:"avatar_url"` GravatarId string `json:"gravatar_id"` Url string `json:"url"` } func (c *Client) Statuses(repo Repository, sha string) ([]Status, error) { path := fmt.Sprintf("repos/%s/statuses/%s", repo, sha) var statuses []Status err := c.jsonGet(path, nil, &statuses) if err != nil { return nil, err } return statuses, nil }
Update the admin interface and demo site generator Update the admin interface to feature a fully responsive, fully retina, cleaned up look and feel based on Bootstrap 3. Simultaniously updated the generated demo site to be more in line with what we use as a starting point for our websites. While this commit is squashed under my name, this is the result of the hard work by too many people to mention by name.
<?php namespace Kunstmaan\FormBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * An abstract Form Page Admin Type */ class AbstractFormPageAdminType extends AbstractType { /** * @param FormBuilderInterface $builder The form builder * @param array $options The options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title'); $builder->add('thanks', 'textarea', array('required' => false, 'attr' => array('class' => 'js-rich-editor rich-editor'))); $builder->add('subject'); $builder->add('from_email'); $builder->add('to_email'); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Kunstmaan\FormBundle\Entity\AbstractFormPage', )); } /** * @return string */ public function getName() { return 'formpage'; } }
<?php namespace Kunstmaan\FormBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * An abstract Form Page Admin Type */ class AbstractFormPageAdminType extends AbstractType { /** * @param FormBuilderInterface $builder The form builder * @param array $options The options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title'); $builder->add('thanks', 'textarea', array('required' => false, 'attr' => array('class' => 'rich_editor'))); $builder->add('subject'); $builder->add('from_email'); $builder->add('to_email'); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Kunstmaan\FormBundle\Entity\AbstractFormPage', )); } /** * @return string */ public function getName() { return 'formpage'; } }
Add docstring to the methods structure in the abstract class
from urllib import request from bs4 import BeautifulSoup class AbstractScraper(): def __init__(self, url, test=False): if test: # when testing, we simply load a file self.soup = BeautifulSoup(url.read(), "html.parser") else: self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser") def host(self): """ get the host of the url, so we can use the correct scraper (check __init__.py) """ raise NotImplementedError("This should be implemented.") def publisher_site(self): """ the original url of the publisher site """ raise NotImplementedError("This should be implemented.") def title(self): """ title of the recipe itself """ raise NotImplementedError("This should be implemented.") def total_time(self): """ total time it takes to preparate the recipe in minutes """ raise NotImplementedError("This should be implemented.") def ingredients(self): """ list of ingredients needed for the recipe """ raise NotImplementedError("This should be implemented.") def directions(self): """ directions provided on the recipe link """ raise NotImplementedError("This should be implemented.") def social_rating(self): """ social rating of the recipe in 0 - 100 scale """ raise NotImplementedError("This should be implemented.")
from urllib import request from bs4 import BeautifulSoup class AbstractScraper(): def __init__(self, url, test=False): if test: # when testing, we simply load a file self.soup = BeautifulSoup(url.read(), "html.parser") else: self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser") def host(self): raise NotImplementedError("This should be implemented.") def publisher_site(self): raise NotImplementedError("This should be implemented.") def title(self): raise NotImplementedError("This should be implemented.") def total_time(self): raise NotImplementedError("This should be implemented.") def ingredients(self): raise NotImplementedError("This should be implemented.") def directions(self): raise NotImplementedError("This should be implemented.") def social_rating(self): raise NotImplementedError("This should be implemented.")
Add option to include static values in properties
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: results[key] = source_properties[value] else: raise PropertyMappingFailedException("property %s not found in source feature" % (value)) elif type(value) == dict: if "static" in value: results[key] = value["static"] else: raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" % (key, type(value))) return results
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: results[key] = source_properties[value] else: raise PropertyMappingFailedException("property %s not found in source feature" % (value)) else: raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" % (key, type(value))) return results
Fix exchanger issue while changing Virtual currency to PLN
<?php namespace Hatimeria\BankBundle\Currency; use Hatimeria\BankBundle\Decimal\Decimal; /** * Currency exchanger * * supported currencies: PLN, Virtual * * @author michal */ class Exchanger { // pln to virtual ratio private $ratio; public function __construct($ratio) { $this->ratio = $ratio; } /** * Get exchanged amount * * @param int $amount * @param string $originalCurrency * @param string $destinationCurrency */ public function exchange($amount, $originalCurrency, $destinationCurrency = null) { if (null !== $destinationCurrency) { if ($originalCurrency == $destinationCurrency) { return $amount; } } $amount = new Decimal($amount); if($originalCurrency == CurrencyCode::PLN) { return $amount->mul($this->ratio)->getAmount(); } else { return $amount->getAmount()/$this->ratio; } } }
<?php namespace Hatimeria\BankBundle\Currency; use Hatimeria\BankBundle\Decimal\Decimal; /** * Currency exchanger * * supported currencies: PLN, Virtual * * @author michal */ class Exchanger { // pln to virtual ratio private $ratio; public function __construct($ratio) { $this->ratio = $ratio; } /** * Get exchanged amount * * @param int $amount * @param string $originalCurrency * @param string $destinationCurrency */ public function exchange($amount, $originalCurrency, $destinationCurrency = null) { if (null !== $destinationCurrency) { if ($originalCurrency == $destinationCurrency) { return $amount; } } $amount = new Decimal($amount); if($originalCurrency == CurrencyCode::PLN) { return $amount->mul($this->ratio)->getAmount(); } else { return $amount/$this->ratio; } } }
Remove doctrine manager clear due to side effect
<?php namespace Itkg\DelayEventBundle\EventListener; use Doctrine\Common\Persistence\ObjectManager; use Itkg\DelayEventBundle\Event\ProcessedEvents; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class ClearMemoryEventSubscriber */ class ClearMemoryEventSubscriber implements EventSubscriberInterface { /** * @var ObjectManager */ private $objectManager; /** * @param ObjectManager $objectManager */ public function __construct(ObjectManager $objectManager) { $this->objectManager = $objectManager; } /** * @param Event $event */ public function onFinish(Event $event) { $this->objectManager->flush(); } /** * {@inheritDoc} */ public static function getSubscribedEvents() { return array( ProcessedEvents::FINISH => 'onFinish', ); } }
<?php namespace Itkg\DelayEventBundle\EventListener; use Doctrine\Common\Persistence\ObjectManager; use Itkg\DelayEventBundle\Event\ProcessedEvents; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class ClearMemoryEventSubscriber */ class ClearMemoryEventSubscriber implements EventSubscriberInterface { /** * @var ObjectManager */ private $objectManager; /** * @param ObjectManager $objectManager */ public function __construct(ObjectManager $objectManager) { $this->objectManager = $objectManager; } /** * @param Event $event */ public function onFinish(Event $event) { $this->objectManager->flush(); $this->objectManager->clear(); } /** * {@inheritDoc} */ public static function getSubscribedEvents() { return array( ProcessedEvents::FINISH => 'onFinish', ); } }
Add the upload services based on file_upload_path configuration option
<?php namespace FlexModel\FlexModelBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * FlexModelExtension loads and manages the bundle configuration. * * @author Niels Nijens <niels@connectholland.nl> */ class FlexModelExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('flex_model.resource', $config['resource']); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); if (isset($config['file_upload_path'])) { $container->setParameter('flex_model.file_upload_path', $config['file_upload_path']); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('upload_services.xml'); } } }
<?php namespace FlexModel\FlexModelBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * FlexModelExtension loads and manages the bundle configuration. * * @author Niels Nijens <niels@connectholland.nl> */ class FlexModelExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('flex_model.resource', $config['resource']); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
Remove print statement from PaxNode config method
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __init__(self, name, **params): super(PaxNode, self).__init__(name, **params) def config(self, **params): super(PaxNode, self).config(**params) # Setup iptable rules to drop incoming packets on each interface: # Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets # to prevent the OS from handling them and responding. for intf in self.intfList(): self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name) # Disable ip_forward because otherwise this still happens, even with the above iptables rules self.cmd("sysctl -w net.ipv4.ip_forward=0") def terminate(self): # Remove iptables rules for intf in self.intfList(): self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name) super(PaxNode, self).terminate()
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __init__(self, name, **params): super(PaxNode, self).__init__(name, **params) def config(self, **params): super(PaxNode, self).config(**params) # Setup iptable rules to drop incoming packets on each interface: # Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets # to prevent the OS from handling them and responding. print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man" for intf in self.intfList(): self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name) # Disable ip_forward because otherwise this still happens, even with the above iptables rules self.cmd("sysctl -w net.ipv4.ip_forward=0") def terminate(self): # Remove iptables rules for intf in self.intfList(): self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name) super(PaxNode, self).terminate()
Fix throwing of function instead of error
const createError = require('create-error'); function ModelNotResolvedError() { ModelNotResolvedError.prototype = Object.create(Error.prototype, { constructor: { value: ModelNotResolvedError, enumerable: false, writable: true, configurable: true } }); Object.setPrototypeOf(ModelNotResolvedError, Error); function ModelNotResolvedError() { return Object.getPrototypeOf(ModelNotResolvedError).apply(this, arguments); } return ModelNotResolvedError; } module.exports = { // Thrown when a model is not found. NotFoundError: createError('NotFoundError'), // Thrown when the collection is empty upon fetching it. EmptyError: createError('EmptyError'), // Thrown when an update affects no rows NoRowsUpdatedError: createError('NoRowsUpdatedError'), // Thrown when a delete affects no rows. NoRowsDeletedError: createError('NoRowsDeletedError'), ModelNotResolvedError: ModelNotResolvedError() };
const createError = require('create-error'); function ModelNotResolvedError() { ModelNotResolvedError.prototype = Object.create(Error.prototype, { constructor: { value: ModelNotResolvedError, enumerable: false, writable: true, configurable: true } }); Object.setPrototypeOf(ModelNotResolvedError, Error); function ModelNotResolvedError() { return Object.getPrototypeOf(ModelNotResolvedError).apply(this, arguments); } return ModelNotResolvedError; } module.exports = { // Thrown when a model is not found. NotFoundError: createError('NotFoundError'), // Thrown when the collection is empty upon fetching it. EmptyError: createError('EmptyError'), // Thrown when an update affects no rows NoRowsUpdatedError: createError('NoRowsUpdatedError'), // Thrown when a delete affects no rows. NoRowsDeletedError: createError('NoRowsDeletedError'), ModelNotResolvedError };
Include the eval'd node type in the async return
""" RESTful interface to interacting with OCR plugins. """ from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict( node=evalnode, task_id=async.task_id, status=async.status, results=async.result ) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
""" RESTful interface to interacting with OCR plugins. """ from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict(task_id=async.task_id, status=async.status, results=async.result) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
Fix redirect for index when community in cookie
import AccountSelectors from '~client/account/redux/selectors' import * as CommunitySelectors from '~client/community/selectors' import * as Paths from '~client/paths' export const showMobilizationPublicView = ({ host, domain }) => { return (isSubdomain(host, domain) || !isDomain(host, domain)) } // eslint-disable-next-line export const isSubdomain = (host, domain) => host.match(`(.+)\.${domain}`) export const isDomain = (host, domain) => host.match(domain) export const getDomain = (store, serverConfig) => { const { sourceRequest: { host } } = store.getState() const domain = serverConfig.appDomain return { domain, host } } export const isIndexRedirected = (store) => (nextState, replace) => { const credentials = AccountSelectors(store.getState()).getCredentials() const community = CommunitySelectors.getCurrent(store.getState()) if (!credentials) { replace(Paths.login()) } else if (!community) { replace(Paths.list()) } else { replace(Paths.mobilizations()) } } export const IsCommunitySelected = (store) => (nextState, replace) => { const community = CommunitySelectors.getCurrent(store.getState()) if (!community) { replace(Paths.list()) } } export const UserIsLogged = (store) => (nextState, replace) => { const credentials = AccountSelectors(store.getState()).getCredentials() if (!credentials) { replace(Paths.login()) } }
import AccountSelectors from '~client/account/redux/selectors' import * as CommunitySelectors from '~client/community/selectors' import * as Paths from '~client/paths' export const showMobilizationPublicView = ({ host, domain }) => { return (isSubdomain(host, domain) || !isDomain(host, domain)) } // eslint-disable-next-line export const isSubdomain = (host, domain) => host.match(`(.+)\.${domain}`) export const isDomain = (host, domain) => host.match(domain) export const getDomain = (store, serverConfig) => { const { sourceRequest: { host } } = store.getState() const domain = serverConfig.appDomain return { domain, host } } export const isIndexRedirected = (store) => (nextState, replace) => { const credentials = AccountSelectors(store.getState()).getCredentials() if (!credentials) { UserIsLogged(store)(nextState, replace) } else { IsCommunitySelected(store)(nextState, replace) } } export const IsCommunitySelected = (store) => (nextState, replace) => { const community = CommunitySelectors.getCurrent(store.getState()) if (!community) { replace(Paths.list()) } } export const UserIsLogged = (store) => (nextState, replace) => { const credentials = AccountSelectors(store.getState()).getCredentials() if (!credentials) { replace(Paths.login()) } }
Change the new endpoint function name
from flask import Flask import relay_api.api.backend as backend server = Flask(__name__) backend.init_relays() @server.route("/relay-api/relays/", methods=["GET"]) def get_all_relays(): js = backend.get_all_relays() return js, 200 @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): js = backend.get_relay(relay_name) if not js: return "", 404 return js, 200 @server.route("/relay-api/relays/<relay_name>/on", methods=["PUT"]) def set_relay_on(relay_name): js = backend.set_relay_on(relay_name) if not js: return "", 404 return js, 200
from flask import Flask import relay_api.api.backend as backend server = Flask(__name__) backend.init_relays() @server.route("/relay-api/relays/", methods=["GET"]) def get_all_relays(): js = backend.get_all_relays() return js, 200 @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): js = backend.get_relay(relay_name) if not js: return "", 404 return js, 200 @server.route("/relay-api/relays/<relay_name>/on", methods=["PUT"]) def get_relay(relay_name): js = backend.set_relay_on(relay_name) if not js: return "", 404 return js, 200
Call engine.resize() after stylesheets load. Otherwise engine would look pixely sometimes.
import React from 'react'; import BABYLON from 'babylonjs'; export class BabylonJS extends React.Component { get defaultProps() { return { antialias: true, onEngineCreated: () => {}, onEngineAbandoned: () => {}, }; } componentDidMount() { this.engine = new BABYLON.Engine(this.canvas, this.props.antialias); this.props.onEngineCreated(this.engine); this.handleWindowResize = () => this.engine.resize(); window.addEventListener('resize', this.handleWindowResize); // Stylesheets which would result in resizing of the canvas may // still be loading. If we don’t call engine.resize() after, the // engine will render pixelated. window.addEventListener('load', this.handleWindowResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowResize); window.removeEventListener('load', this.handleWindowResize); this.handleWindowResize = null; this.props.onEngineAbandoned(this.engine); } render() { return <canvas ref={canvas => this.canvas = canvas} />; } }
import React from 'react'; import BABYLON from 'babylonjs'; export class BabylonJS extends React.Component { get defaultProps() { return { antialias: true, onEngineCreated: () => {}, onEngineAbandoned: () => {}, }; } componentDidMount() { this.engine = new BABYLON.Engine(this.canvas, this.props.antialias); this.props.onEngineCreated(this.engine); this.handleWindowResize = () => this.engine.resize(); window.addEventListener('resize', this.handleWindowResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowResize); this.handleWindowResize = null; this.props.onEngineAbandoned(this.engine); } render() { return <canvas ref={canvas => this.canvas = canvas} />; } }
Set message prefetch to 1 for DOI updater. Can help with debugging / service recovery etc.
package org.gbif.registry.cli.doiupdater; import org.gbif.common.messaging.MessageListener; import org.gbif.registry.cli.common.CommonBuilder; import org.gbif.registry.persistence.guice.RegistryMyBatisModule; import org.gbif.registry.persistence.mapper.DoiMapper; import com.google.common.util.concurrent.AbstractIdleService; import com.google.inject.Guice; import com.google.inject.Injector; /** * A CLI service that starts and stops a listener of DoiUpdate messages. Must always be only one thread - multiple * will introduce a possible race (e.g. delete before create). */ public class DoiUpdaterService extends AbstractIdleService { private final DoiUpdaterConfiguration config; private MessageListener listener; public DoiUpdaterService(DoiUpdaterConfiguration config) { this.config = config; } @Override protected void startUp() throws Exception { config.ganglia.start(); Injector inj = Guice.createInjector( new RegistryMyBatisModule(config.registry.toRegistryProperties())); listener = new MessageListener(config.messaging.getConnectionParameters(), 1); listener.listen(config.queueName, 1, new DoiUpdateListener(CommonBuilder.createRestJsonApiDataCiteService(config.datacite), inj.getInstance(DoiMapper.class), config.timeToRetryInMs)); } @Override protected void shutDown() throws Exception { if (listener != null) { listener.close(); } } }
package org.gbif.registry.cli.doiupdater; import org.gbif.common.messaging.MessageListener; import org.gbif.registry.cli.common.CommonBuilder; import org.gbif.registry.persistence.guice.RegistryMyBatisModule; import org.gbif.registry.persistence.mapper.DoiMapper; import com.google.common.util.concurrent.AbstractIdleService; import com.google.inject.Guice; import com.google.inject.Injector; /** * A CLI service that starts and stops a listener of DoiUpdate messages. Must always be only one thread - multiple * will introduce a possible race (e.g. delete before create). */ public class DoiUpdaterService extends AbstractIdleService { private final DoiUpdaterConfiguration config; private MessageListener listener; public DoiUpdaterService(DoiUpdaterConfiguration config) { this.config = config; } @Override protected void startUp() throws Exception { config.ganglia.start(); Injector inj = Guice.createInjector( new RegistryMyBatisModule(config.registry.toRegistryProperties())); listener = new MessageListener(config.messaging.getConnectionParameters()); listener.listen(config.queueName, 1, new DoiUpdateListener(CommonBuilder.createRestJsonApiDataCiteService(config.datacite), inj.getInstance(DoiMapper.class), config.timeToRetryInMs)); } @Override protected void shutDown() throws Exception { if (listener != null) { listener.close(); } } }
Apply sorting only if order by is setup
import AppError from '../infrastructure/error'; import {orderBy} from '../services/utility'; import {key as getKey, direction as getDirection} from '../sort/sort.service'; import {find} from '../column/column.service'; export default function pipeSort(data, context, next) { const model = context.model; const by = model.sort().by; let result = data; if (by.length) { const columns = model.data().columns; const mappings = []; const directions = []; for (let i = 0, length = by.length; i < length; i++) { const sortEntry = by[i]; const sortKey = getKey(sortEntry); const sortDir = getDirection(sortEntry); const sortColumn = find(columns, sortKey); if (!sortColumn) { throw new AppError('sort.pipe', `Column "${sortKey}" is not found`); } mappings.push(context.valueFactory(sortColumn)); directions.push(sortDir); } result = orderBy(data, mappings, directions); } next(result); }
import AppError from '../infrastructure/error'; import {orderBy} from '../services/utility'; import {key as getKey, direction as getDirection} from '../sort/sort.service'; import {find} from '../column/column.service'; export default function pipeSort(data, context, next) { const values = []; const directions = []; const model = context.model; const dataState = model.data(); const columns = dataState.columns; const sort = model.sort(); const by = sort.by; for (let i = 0, length = by.length; i < length; i++) { let item = by[i], key = getKey(item), value = getDirection(item), column = find(columns, key); if (!column) { throw new AppError('column.service', `Column "${key}" is not found`); } values.push(context.valueFactory(column)); directions.push(value); } const result = orderBy(data, values, directions); next(result); }
Make linter not complain, seems the JSX processor makes React needed.
import assert from 'assert'; import React from 'react'; // eslint-disable-line no-unused-vars import Page from '../../src/components/page.js'; import KataGroups from '../../src/katagroups.js'; import {default as KataGroupsComponent} from '../../src/components/katagroups.js'; import {default as KatasComponent} from '../../src/components/katas.js'; import {hasChildOfType} from '../customasserts.js'; assert.hasChildOfType = hasChildOfType; describe('kata groups component', function() { it('receives a KataGroup instance', function() { let rawData = {'group name': {items: []}}; let kataGroups = KataGroups.fromRawKataData(rawData); assert.hasChildOfType(<Page kataGroups={kataGroups} />, KataGroupsComponent); }); it('receives a Katas instance', function() { let rawData = {'group name': {items: []}}; let kataGroups = KataGroups.fromRawKataData(rawData); assert.hasChildOfType(<Page kataGroups={kataGroups} />, KatasComponent); }); });
import assert from 'assert'; import Page from '../../src/components/page.js'; import KataGroups from '../../src/katagroups.js'; import {default as KataGroupsComponent} from '../../src/components/katagroups.js'; import {default as KatasComponent} from '../../src/components/katas.js'; import {hasChildOfType} from '../customasserts.js'; assert.hasChildOfType = hasChildOfType; describe('kata groups component', function() { it('receives a KataGroup instance', function() { let rawData = {'group name': {items: []}}; let kataGroups = KataGroups.fromRawKataData(rawData); assert.hasChildOfType(<Page kataGroups={kataGroups} />, KataGroupsComponent); }); it('receives a Katas instance', function() { let rawData = {'group name': {items: []}}; let kataGroups = KataGroups.fromRawKataData(rawData); assert.hasChildOfType(<Page kataGroups={kataGroups} />, KatasComponent); }); });
Use different location for in/out
<?php require_once('Parser.php'); require_once('vendor/autoload.php'); use Symfony\Component\Yaml\Yaml; $yamlFile = 'rides.yml'; $rides = array(); $kmzWatchDir = "rides/data/in/"; $kmzDestDir = "rides/data/processed/"; $kmzDir = new DirectoryIterator($kmzWatchDir); foreach ($kmzDir as $fileinfo) { if ($fileinfo->getExtension() === 'kmz') { echo "Processing " . $fileinfo->getFilename() . PHP_EOL; $parser = new Parser($fileinfo->getRealPath()); $top = 51.545425; $right = -3.568107; $bottom = 51.539727; $left = -3.57891; $parser->geoFence($top, $right, $bottom, $left); $rides[] = $parser->getRide(); // Move KMZ into folder for map to pick up echo "Moving " . $fileinfo->getFilename() . " to {$kmzDestDir}" . PHP_EOL; rename($fileinfo->getRealPath(), $kmzDestDir . $fileinfo->getFilename()); } } $yaml = Yaml::dump($rides, 3); echo "Ride data appended to {$yamlFile}" . PHP_EOL; file_put_contents($yamlFile, $yaml, FILE_APPEND); // generate map code
<?php require_once('Parser.php'); require_once('vendor/autoload.php'); use Symfony\Component\Yaml\Yaml; $yamlFile = 'rides.yml'; $rides = array(); $kmzWatchDir = "test/data/"; $kmzDestDir = "rides/data/"; $kmzDir = new DirectoryIterator($kmzWatchDir); foreach ($kmzDir as $fileinfo) { if ($fileinfo->getExtension() === 'kmz') { echo "Processing " . $fileinfo->getFilename() . PHP_EOL; $parser = new Parser($fileinfo->getRealPath()); $top = 51.545425; $right = -3.568107; $bottom = 51.539727; $left = -3.57891; $parser->geoFence($top, $right, $bottom, $left); $rides[] = $parser->getRide(); // Move KMZ into folder for map to pick up echo "Moving " . $fileinfo->getFilename() . " to {$kmzDestDir}" . PHP_EOL; rename($fileinfo->getRealPath(), $kmzDestDir . $fileinfo->getFilename()); } } $yaml = Yaml::dump($rides, 3); echo "Ride data appended to {$yamlFile}" . PHP_EOL; file_put_contents($yamlFile, $yaml, FILE_APPEND); // generate map code
Revert "Revert "corrected database settings merge again"" This reverts commit e7766ce068eabea30c81ba699c77ed2fe488d69d.
from yacs.settings.base import settings __all__ = ['settings'] with settings as s: s.DEBUG = True s.MIDDLEWARE_CLASSES += ( 'devserver.middleware.DevServerMiddleware', ) @s.lazy_eval def debug_install_apps(s): if s.DEBUG: s.INSTALLED_APPS += ( 'django_jasmine', 'devserver', ) s.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'yacs', 'USER': 'timetable', 'PASSWORD': 'thereisn0sp00n', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'autocommit': True, } } }
from yacs.settings.base import settings __all__ = ['settings'] with settings as s: s.DEBUG = True s.MIDDLEWARE_CLASSES += ( 'devserver.middleware.DevServerMiddleware', ) @s.lazy_eval def debug_install_apps(s): if s.DEBUG: s.INSTALLED_APPS += ( 'django_jasmine', 'devserver', ) s.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydata', 'USER': 'postgreuser', 'PASSWORD': 'postgre', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'autocommit': True, } } }
:bug: Fix a typo in cli
#!/usr/bin/env node 'use strict' process.title = 'ucompiler' require('debug').enable('UCompiler:*') var UCompiler = require('..') var knownCommands = ['go', 'watch'] var parameters = process.argv.slice(2) if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) { console.log('Usage: ucompiler go|watch [path]') process.exit(0) } const options = { save: true, saveIncludedFiles: false, errorCallback: function(e) { console.log(e.stack || e) } } if (parameters[0] === 'go') { UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) { if (!result.status) { process.exit(1) } }, function(e) { options.errorCallback(e) process.exit(1) }) } else if (parameters[0] === 'watch') { UCompiler.watch( process.cwd(), options, parameters[1] ? parameters[1] .split(',') .map(function(_) { return _.trim()}) .filter(function(_) { return _}) : parameters[1] ).catch(options.errorCallback) }
#!/usr/bin/env node 'use strict' process.title = 'ucompiler' require('debug').enable('UCompiler:*') var UCompiler = require('..') var knownCommands = ['go', 'watch'] var parameters = process.argv.slice(2) if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) { console.log('Usage: ucompiler go|watch [path]') process.exit(0) } const options = { save: true, saveIncludedFiles: false, errorCallback: function(e) { console.log(e.stack || e) } } if (parameters[0] === 'go') { UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) { if (!result.status) { process.exit(1) } }, function(e) { errorCallback(e) process.exit(1) }) } else if (parameters[0] === 'watch') { UCompiler.watch( process.cwd(), options, parameters[1] ? parameters[1] .split(',') .map(function(_) { return _.trim()}) .filter(function(_) { return _}) : parameters[1] ).catch(errorCallback) }
Use 20 as default page size
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', # Any other renders, 'rest_framework.renderers.JSONRenderer', # 'rest_framework.renderers.BrowsableAPIRenderer', ), # 'DEFAULT_PARSER_CLASSES': ( # 'djangorestframework_camel_case.parser.CamelCaseJSONParser', # Any other parsers # ), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'user': '120/min', 'admin': '100/min', 'anon': '30/min', 'health': '10/min', }, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 20 }
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', # Any other renders, 'rest_framework.renderers.JSONRenderer', # 'rest_framework.renderers.BrowsableAPIRenderer', ), # 'DEFAULT_PARSER_CLASSES': ( # 'djangorestframework_camel_case.parser.CamelCaseJSONParser', # Any other parsers # ), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'user': '120/min', 'admin': '100/min', 'anon': '30/min', 'health': '10/min', }, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 30 }
Fix logic around lost connection.
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): if self.lost: dprint('lost already') return dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) if not self.lost: self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
Switch from point objects to array for easier calculations
'use strict'; class FixationsDataProcessor { constructor() { this.fixationsData = []; } process(fileContentsAsArray) { for(var c in fileContentsAsArray) { let lineItems = fileContentsAsArray[c].split(' '); this.addItemToMinute([lineItems[1], lineItems[2]], this.getMinuteFromTimestamp(parseInt(lineItems[0]))); } return this.fixationsData; } addItemToMinute(point, minute) { if(this.fixationsData[minute] === undefined) { this.fixationsData[minute] = { points: [point] } } else { this.fixationsData[minute].points.push(point); } } getMinuteFromTimestamp(timestamp) { let minute = Math.floor(timestamp * 1.67 * 0.00001); return minute; } } export default FixationsDataProcessor
'use strict'; class FixationsDataProcessor { constructor() { this.fixationsData = []; } process(fileContentsAsArray) { for(var c in fileContentsAsArray) { let lineItems = fileContentsAsArray[c].split(' '); this.addItemToMinute({ x: parseInt(lineItems[1]), y: parseInt(lineItems[2]) }, this.getMinuteFromTimestamp(parseInt(lineItems[0]))); } return this.fixationsData; } addItemToMinute(point, minute) { if(this.fixationsData[minute] === undefined) { this.fixationsData[minute] = { points: [point] } } else { this.fixationsData[minute].points.push(point); } } getMinuteFromTimestamp(timestamp) { let minute = Math.floor(timestamp * 1.67 * 0.00001); return minute; } } export default FixationsDataProcessor
Move master version to 0.1.2.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # 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. __all__ = ["__version__"] _tag_version = (0, 1, 2) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # 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. __all__ = ["__version__"] _tag_version = (0, 1, 1) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
Handle invalid returns better. Useful for if you get blocked by W3C.
'use strict'; var es = require('event-stream'), w3cjs = require('w3cjs'), gutil = require('gulp-util'), path = require('path'); /** * Handles messages. * * @param file The file array. * @param messages Array of messages returned by w3cjs. * @return boolean Return false if errors have occurred. */ function handleMessages(file, messages) { var success = true, errorText = gutil.colors.red.bold('HTML Error:'), warningText = gutil.colors.yellow.bold('HTML Warning:'); if (!Array.isArray(messages)) { gutil.log(warningText, 'Failed to run validation on', file.relative); return true; // Not sure whether this should be true or false } messages.forEach(function (message) { if (message.type === 'error') { success = false; } var type = (message.type === 'error') ? errorText : warningText, location = 'Line ' + message.lastLine + ', Column ' + message.lastColumn + ':'; gutil.log(type, file.relative, location, message.message); }); return success; } module.exports = function () { return es.map(function (file, callback) { w3cjs.validate({ file: file.path, callback: function (res) { file.w3cjs = { success: handleMessages(file, res.messages), messages: res.messages }; callback(null, file); } }); }); };
'use strict'; var es = require('event-stream'), w3cjs = require('w3cjs'), gutil = require('gulp-util'), path = require('path'); /** * Handles messages. * * @param file The file array. * @param messages Array of messages returned by w3cjs. * @return boolean Return false if errors have occurred. */ function handleMessages(file, messages) { var success = true, errorText = gutil.colors.red.bold('HTML Error:'), warningText = gutil.colors.yellow.bold('HTML Warning:'); messages.forEach(function (message) { if (message.type === 'error') { success = false; } var type = (message.type === 'error') ? errorText : warningText, location = 'Line ' + message.lastLine + ', Column ' + message.lastColumn + ':'; gutil.log(type, file.relative, location, message.message); }); return success; } module.exports = function () { return es.map(function (file, callback) { w3cjs.validate({ file: file.path, callback: function (res) { file.w3cjs = { success: handleMessages(file, res.messages), messages: res.messages }; callback(null, file); } }); }); };
Use Data.commonStore in datastore creation.
/** * core/site data store * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import connection from './connection'; import info from './info'; import reset from './reset'; import { STORE_NAME } from './constants'; import notifications from './notifications'; export { STORE_NAME }; const store = Data.combineStores( Data.commonStore, connection, info, reset, notifications, ); // Register this store on the global registry. Data.registerStore( STORE_NAME, store ); export default store;
/** * core/site data store * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import connection from './connection'; import info from './info'; import reset from './reset'; import { STORE_NAME } from './constants'; import notifications from './notifications'; export { STORE_NAME }; const store = Data.combineStores( { actions: Data.addInitializeAction( Data.commonActions ), controls: Data.commonControls, reducer: Data.addInitializeReducer( {}, ( state ) => ( { ...state } ) ), }, connection, info, reset, notifications, ); // Register this store on the global registry. Data.registerStore( STORE_NAME, store ); export default store;
Fix file name matching when clearing old lists
# -*- coding: utf-8 -*- import os import re from collections import defaultdict html_files = set() html_file_groups = defaultdict(list) newest_files = set() def get_all_files(): for n in os.listdir('output'): r = re.findall(r'\ASoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html\Z', n) if r: html_files.add(n) html_file_groups[r[0]].append(n) for k in html_file_groups: html_file_groups[k].sort() newest_files.add(html_file_groups[k][-1]) def delete_old_files(): for f in html_files - newest_files: os.remove(os.path.join('output', f)) def main(): get_all_files() delete_old_files() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import os import re from collections import defaultdict html_files = set() html_file_groups = defaultdict(list) newest_files = set() def get_all_files(): for n in os.listdir('output'): r = re.findall(r'SoftwareList_([-_0-9A-Za-z]+)_\d{14}\.html', n) if r: html_files.add(n) html_file_groups[r[0]].append(n) for k in html_file_groups: html_file_groups[k].sort() newest_files.add(html_file_groups[k][-1]) def delete_old_files(): for f in html_files - newest_files: os.remove(os.path.join('output', f)) def main(): get_all_files() delete_old_files() if __name__ == '__main__': main()
Add callback for custom render
function selectize(callback) { try { $( ".selectize" ).each(function() { var item = $(this); if (item.data('options').mode === 'full') { var valueField = item.data('options').valueField; var labelField = item.data('options').labelField; var options = { plugins: (item.data('options').plugins === null ? null : item.data('options').plugins), delimiter: item.data('options').delimiter, maxItems: item.data('options').maxItems, valueField: valueField, labelField: labelField, searchField: item.data('options').searchField, options: item.data('entity'), create: (item.data('options').create ? true : false) }; if (callback !== undefined) { options.render = callback(labelField, valueField); } item.selectize(options); } else { item.selectize({ sortField: 'text', create: (item.data('options').create ? true : false) }); } }); } catch(err) { console.log('missing selectize!'); } }
try { $( ".selectize" ).each(function() { if ($(this).data('options').mode === 'full') { $(this).selectize({ plugins: ($(this).data('options').plugins === null ? null : $(this).data('options').plugins), delimiter: $(this).data('options').delimiter, maxItems: $(this).data('options').maxItems, valueField: $(this).data('options').valueField, labelField: $(this).data('options').labelField, searchField: $(this).data('options').searchField, options: $(this).data('entity'), create: ($(this).data('options').create ? true : false) }); } else { $(this).selectize({ sortField: 'text', create: ($(this).data('options').create ? true : false) }); } }); } catch(err) { console.log('missing selectize!'); }
Enable morph rules for Danish
# coding: utf8 from __future__ import unicode_literals from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .morph_rules import MORPH_RULES from ..tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class DanishDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[LANG] = lambda text: 'da' lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) morph_rules = MORPH_RULES tag_map = TAG_MAP stop_words = STOP_WORDS class Danish(Language): lang = 'da' Defaults = DanishDefaults __all__ = ['Danish']
# coding: utf8 from __future__ import unicode_literals from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .morph_rules import MORPH_RULES from ..tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class DanishDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[LANG] = lambda text: 'da' lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) # morph_rules = MORPH_RULES tag_map = TAG_MAP stop_words = STOP_WORDS class Danish(Language): lang = 'da' Defaults = DanishDefaults __all__ = ['Danish']
Set the redirect through $context->response.
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblink Controller Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerWeblink extends ComDefaultControllerDefault { public function getRequest() { //Display only published items $this->_request->published = 1; return parent::getRequest(); } public function _actionRead(KCommandContext $context) { $weblink = parent::_actionRead($context); // Redirect the user if the request doesn't include layout=form if ($this->_request->format == 'html') { if ($weblink->url) { $context->response->setRedirect($weblink->url); } return true; } return $weblink; } }
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblink Controller Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerWeblink extends ComDefaultControllerDefault { public function getRequest() { //Display only published items $this->_request->published = 1; return parent::getRequest(); } public function _actionRead(KCommandContext $context) { $weblink = parent::_actionRead($context); // Redirect the user if the request doesn't include layout=form if ($this->_request->format == 'html') { if ($weblink->url) { $this->getService('application')->redirect($weblink->url); } return true; } return $weblink; } }
Remove useless promise in test suite
/*global browser:false, element:false, by:false */ 'use strict'; var Synonyms = require('./synonyms'); var Taxonomy = function(id){ this.id = id; }; Taxonomy.prototype.getSynonyms = function(conceptName) { var synonyms = new Synonyms(this.id, conceptName); return synonyms; }; Taxonomy.prototype.get = function(){ return browser.get('/' + this.id); }; Taxonomy.prototype.createConcept = function(conceptName){ var input = element(by.model('conceptName')); input.clear(); input.sendKeys(conceptName); var createConceptBtn = element.all(by.repeater('match in matches track by $index')).last(); createConceptBtn.click(); this.conceptName = element(by.id('concept')).element(by.binding('concept.Name')).getText(); }; Taxonomy.prototype.createElement = function(conceptName, parent, offset){ offset = offset ? offset : 0; browser.get('/' + this.id + '/concept/' + conceptName +'?action=addElement&parent=' + parent + '&offset=' + offset); this.get(); }; module.exports = Taxonomy;
/*global browser:false, element:false, by:false */ 'use strict'; var Synonyms = require('./synonyms'); var Taxonomy = function(id){ this.id = id; }; Taxonomy.prototype.getSynonyms = function(conceptName) { var synonyms = new Synonyms(this.id, conceptName); return synonyms; }; Taxonomy.prototype.get = function(){ return browser.get('/' + this.id); }; Taxonomy.prototype.createConcept = function(conceptName){ var input = element(by.model('conceptName')); input.clear(); input.sendKeys(conceptName); var createConceptBtn = element.all(by.repeater('match in matches track by $index')).last(); createConceptBtn.click(); this.conceptName = element(by.id('concept')).element(by.binding('concept.Name')).getText(); }; Taxonomy.prototype.createElement = function(conceptName, parent, offset){ offset = offset ? offset : 0; browser.get('/' + this.id + '/concept/' + conceptName +'?action=addElement&parent=' + parent + '&offset=' + offset); browser.waitForAngular(); this.get(); }; module.exports = Taxonomy;
Remove unneeded clearing of image view background drawable
package com.github.mobile.android.repo; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.github.mobile.android.R.id; import com.github.mobile.android.util.AvatarHelper; import com.madgag.android.listviews.ViewHolder; import org.eclipse.egit.github.core.User; /** * View holder to display a user/organization */ public class OrgViewHolder implements ViewHolder<User> { private final AvatarHelper avatarHelper; private final TextView nameText; private final ImageView avatarView; /** * Create org view holder * * @param view * @param avatarHelper */ public OrgViewHolder(final View view, final AvatarHelper avatarHelper) { this.avatarHelper = avatarHelper; nameText = (TextView) view.findViewById(id.tv_org_name); avatarView = (ImageView) view.findViewById(id.iv_gravatar); } @Override public void updateViewFor(final User user) { nameText.setText(user.getLogin()); avatarHelper.bind(avatarView, user); } }
package com.github.mobile.android.repo; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.github.mobile.android.R.id; import com.github.mobile.android.util.AvatarHelper; import com.madgag.android.listviews.ViewHolder; import org.eclipse.egit.github.core.User; /** * View holder to display a user/organization */ public class OrgViewHolder implements ViewHolder<User> { private final AvatarHelper avatarHelper; private final TextView nameText; private final ImageView avatarView; /** * Create org view holder * * @param view * @param avatarHelper */ public OrgViewHolder(final View view, final AvatarHelper avatarHelper) { this.avatarHelper = avatarHelper; nameText = (TextView) view.findViewById(id.tv_org_name); avatarView = (ImageView) view.findViewById(id.iv_gravatar); } @Override public void updateViewFor(final User user) { nameText.setText(user.getLogin()); avatarView.setBackgroundDrawable(null); avatarHelper.bind(avatarView, user); } }
Comment out footer until we have actual content
import React from 'react'; import * as auth from './auth.js'; import * as data from './data.js'; import Header from './header.js'; import Footer from './footer.js'; import LoadingOverlay from './loading-overlay.js'; // Authorize them to all services if they're signed in const Application = React.createClass({ componentDidMount: async function () { const handleReady = () => this.setState({isReady: true}); auth.whenReady() .then(handleReady, handleReady); try { await auth.authorize(); this.setState({isLoggedIn: true}); data.onUpdate((data) => { console.log('updated data'); this.setState({data: data || {}}); }); } catch (error) { this.setState({isLoggedIn: false}); } }, getInitialState: function () { return { data: {} }; }, render: function () { return ( <div> <LoadingOverlay shouldShow={!this.state.isReady} /> <Header /> {React.cloneElement(this.props.children, { loggedIn: this.state.isLoggedIn, data: this.state.data })} { /* <Footer /> */ } </div> ); } }); export default Application;
import React from 'react'; import * as auth from './auth.js'; import * as data from './data.js'; import Header from './header.js'; import Footer from './footer.js'; import LoadingOverlay from './loading-overlay.js'; // Authorize them to all services if they're signed in const Application = React.createClass({ componentDidMount: async function () { const handleReady = () => this.setState({isReady: true}); auth.whenReady() .then(handleReady, handleReady); try { await auth.authorize(); this.setState({isLoggedIn: true}); data.onUpdate((data) => { console.log('updated data'); this.setState({data: data || {}}); }); } catch (error) { this.setState({isLoggedIn: false}); } }, getInitialState: function () { return { data: {} }; }, render: function () { return ( <div> <LoadingOverlay shouldShow={!this.state.isReady} /> <Header /> {React.cloneElement(this.props.children, { loggedIn: this.state.isLoggedIn, data: this.state.data })} <Footer /> </div> ); } }); export default Application;
Change assemblyDir type from File to String since it needs to travel across the ether git-svn-id: bf08415a33f9c0f05ac2b054c631df0aaa894ee0@245 f54485bd-ff3a-0410-97a1-83db373c2bce
/** * Copyright (c) 2005-2007 Intalio inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intalio inc. - initial API and implementation */ package org.intalio.tempo.deployment; import java.io.Serializable; import java.util.List; /** * Deployed assembly. * <p> * This is an immutable data object returned when querying {@link DeploymentService#getDeployedAssemblies()} */ public class DeployedAssembly implements Serializable { private static final long serialVersionUID = 1L; final AssemblyId _aid; final String _assemblyDir; final List<DeployedComponent> _components; public DeployedAssembly(AssemblyId assemblyId, String assemblyDir, List<DeployedComponent> components) { _aid = assemblyId; _assemblyDir = assemblyDir; _components = components; } public AssemblyId getAssemblyId() { return _aid; } public String getAssemblyDir() { return _assemblyDir; } public List<DeployedComponent> getDeployedComponents() { return _components; } public String toString() { return _aid.toString(); } }
/** * Copyright (c) 2005-2007 Intalio inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intalio inc. - initial API and implementation */ package org.intalio.tempo.deployment; import java.io.File; import java.io.Serializable; import java.util.List; /** * Deployed assembly. * <p> * This is an immutable data object returned when querying {@link DeploymentService#getDeployedAssemblies()} */ public class DeployedAssembly implements Serializable { private static final long serialVersionUID = 1L; final AssemblyId _aid; final File _assemblyDir; final List<DeployedComponent> _components; public DeployedAssembly(AssemblyId assemblyId, File assemblyDir, List<DeployedComponent> components) { _aid = assemblyId; _assemblyDir = assemblyDir; _components = components; } public AssemblyId getAssemblyId() { return _aid; } public File getAssemblyDir() { return _assemblyDir; } public List<DeployedComponent> getDeployedComponents() { return _components; } public String toString() { return _aid.toString(); } }
Fix IMPALA-122: Lzo scanner with small scan ranges. Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e Reviewed-on: http://gerrit.ent.cloudera.com:8080/140 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Validates running with different scan range length values # import pytest from copy import copy from tests.common.test_vector import TestDimension from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY # We use very small scan ranges to exercise corner cases in the HDFS scanner more # thoroughly. In particular, it will exercise: # 1. scan range with no tuple # 2. tuple that span across multiple scan ranges MAX_SCAN_RANGE_LENGTHS = [1, 2, 5] class TestScanRangeLengths(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestScanRangeLengths, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS)) def test_scan_ranges(self, vector): if vector.get_value('table_format').file_format != 'text': pytest.xfail(reason='IMP-636') elif vector.get_value('table_format').compression_codec != 'none': pytest.xfail(reason='IMPALA-122') vector.get_value('exec_option')['max_scan_range_length'] =\ vector.get_value('max_scan_range_length') self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
Change houseprices to 6 months.
<?php class HousePrice extends Module { public $url = "https://data.bathhacked.org/resource/ifh9-xtsp.json"; function getData() { $postcodelat = self::$postCodeLoc[0]; $postcodelong = self::$postCodeLoc[1]; $startDate = date('Y-m-d', time()-6*30*24*60*60); $endDate = date('Y-m-d'); $this->url .= '?$where=date_of_transfer>%27'.$startDate.'%27%20AND%20date_of_transfer<%27'.$endDate.'%27%20AND%20within_circle(location,'.$postcodelong.','.$postcodelat.',1000)'; echo $this->url; return json_decode($this->fetch(), true); } } ?>
<?php class HousePrice extends Module { public $url = "https://data.bathhacked.org/resource/ifh9-xtsp.json"; function getData() { $postcodelat = self::$postCodeLoc[0]; $postcodelong = self::$postCodeLoc[1]; $endDate = date('Y-m-d'); $startDate = date('Y-m-d', time()-3*30*24*60*60); $this->url .= '?$where=date_of_transfer>%27'.$startDate.'%27%20AND%20date_of_transfer<%27'.$endDate.'%27%20AND%20within_circle(location,'.$postcodelong.','.$postcodelat.',1000)'; return json_decode($this->fetch(), true); } } ?>
Correct MIN_GAS_LIMIT for Frontier config
package org.ethereum.config.blockchain; import org.ethereum.config.Constants; import java.math.BigInteger; /** * Created by Anton Nashatyrev on 25.02.2016. */ public class FrontierConfig extends OlympicConfig { public static class FrontierConstants extends Constants { private static final BigInteger BLOCK_REWARD = new BigInteger("5000000000000000000"); @Override public int getDURATION_LIMIT() { return 13; } @Override public BigInteger getBLOCK_REWARD() { return BLOCK_REWARD; } @Override public int getMIN_GAS_LIMIT() { return 5000; } }; public FrontierConfig() { this(new FrontierConstants()); } public FrontierConfig(Constants constants) { super(constants); } }
package org.ethereum.config.blockchain; import org.ethereum.config.Constants; import java.math.BigInteger; /** * Created by Anton Nashatyrev on 25.02.2016. */ public class FrontierConfig extends OlympicConfig { public static class FrontierConstants extends Constants { private static final BigInteger BLOCK_REWARD = new BigInteger("5000000000000000000"); @Override public int getDURATION_LIMIT() { return 13; } @Override public BigInteger getBLOCK_REWARD() { return BLOCK_REWARD; } }; public FrontierConfig() { this(new FrontierConstants()); } public FrontierConfig(Constants constants) { super(constants); } }
Use allclose for dataprep test
import os import pandas as pd import numpy.testing as npt from gypsy import DATA_DIR from gypsy.data_prep import prep_standtable def test_prep_standtable(): data_file_name = 'raw_standtable.csv' plot_data = pd.read_csv(os.path.join(DATA_DIR, data_file_name)) expected_data_path = os.path.join( DATA_DIR, 'output', 'dataprepped_standtable.csv' ) result = prep_standtable(plot_data) expected = pd.read_csv(expected_data_path, index_col=0) assert isinstance(result, pd.DataFrame) assert npt.assert_allclose( expected.values, result.values, rtol=0.01, atol=0.1, equal_nan=True ) is None # regenerate output files # result.to_csv(expected_data_path)
import os import pandas as pd import numpy.testing as npt from gypsy import DATA_DIR from gypsy.data_prep import prep_standtable def test_prep_standtable(): data_file_name = 'raw_standtable.csv' plot_data = pd.read_csv(os.path.join(DATA_DIR, data_file_name)) expected_data_path = os.path.join( DATA_DIR, 'output', 'dataprepped_standtable.csv' ) result = prep_standtable(plot_data) expected = pd.read_csv(expected_data_path, index_col=0) assert isinstance(result, pd.DataFrame) assert npt.assert_almost_equal( expected.values, result.values, decimal=3 ) is None # regenerate output files # result.to_csv(expected_data_path)
Mark empty object as static
package com.alexstyl.specialdates.events.namedays.calendar.resource; import com.alexstyl.specialdates.events.namedays.NamedayLocale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; class NamedayJSONResourceProvider { private static final JSONArray EMPTY = new JSONArray(); private final NamedayJSONResourceLoader loader; NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) { this.loader = loader; } NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException { JSONObject json = loader.loadJSON(locale); JSONArray data = json.getJSONArray("data"); JSONArray special = getSpecialOf(json); return new NamedayJSON(data, special); } private JSONArray getSpecialOf(JSONObject json) throws JSONException { if (json.has("special")) { return json.getJSONArray("special"); } return EMPTY; } }
package com.alexstyl.specialdates.events.namedays.calendar.resource; import com.alexstyl.specialdates.events.namedays.NamedayLocale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; class NamedayJSONResourceProvider { private final NamedayJSONResourceLoader loader; private final JSONArray jsonArray = new JSONArray(); NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) { this.loader = loader; } NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException { JSONObject json = loader.loadJSON(locale); JSONArray data = json.getJSONArray("data"); JSONArray special = getSpecialOf(json); return new NamedayJSON(data, special); } private JSONArray getSpecialOf(JSONObject json) throws JSONException { if (json.has("special")) { return json.getJSONArray("special"); } return jsonArray; } }
Add composer loader for production
<?php /** * This script is intended to be run as the inbuilt webserver's "router" script. * Procedural code below is necessary when triggered from inbuilt webserver * as this script is the point-of-entry for the whole application. * * Uses Gateway class to decide whether to serve static content or begin * request / response within PHP.Gt. * * PHP.Gt (http://php.gt) * @copyright Copyright β’Έ 2014 Bright Flair Ltd. (http://brightflair.com) * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses */ namespace Gt\Cli; $autoloader = realpath(__DIR__ . "/../../../../autoload.php"); if(false === $autoloader) { // Assume installed globally. $autoloader = realpath(__DIR__ . "/../../vendor/autoload.php"); } if(false === $autoloader) { die("Composer autoloader missing. Have you installed correctly?"); } require($autoloader); // Only allow this script to be invoked from inbuilt webserver. $sapi = php_sapi_name(); switch($sapi) { case "cli-server": return Gateway::serve($_SERVER["REQUEST_URI"]); case "cli": throw new InvalidContextException(php_sapi_name()); default: // When using third-party webserver: return new \Gt\Core\Go(); }
<?php /** * This script is intended to be run as the inbuilt webserver's "router" script. * Procedural code below is necessary when triggered from inbuilt webserver * as this script is the point-of-entry for the whole application. * * Uses Gateway class to decide whether to serve static content or begin * request / response within PHP.Gt. * * PHP.Gt (http://php.gt) * @copyright Copyright β’Έ 2014 Bright Flair Ltd. (http://brightflair.com) * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses */ namespace Gt\Cli; $autoloader = realpath(__DIR__ . "/../../vendor/autoload.php"); if(false === $autoloader) { die("Composer autoloader missing. Have you installed correctly?"); } require($autoloader); // Only allow this script to be invoked from inbuilt webserver. $sapi = php_sapi_name(); switch($sapi) { case "cli-server": return Gateway::serve($_SERVER["REQUEST_URI"]); case "cli": throw new InvalidContextException(php_sapi_name()); default: // When using third-party webserver: return new \Gt\Core\Go(); }
Change init of watch and server
function setup(options, imports, register) { // Import var server = imports.server.http; var port = imports.server.port; var watch = imports.watch; var workspace = imports.workspace; var logger = imports.logger.namespace("codebox"); // Start server server.listen(port); server.on('listening', function() { logger.log("Server is listening on ", port); }); watch.init(workspace.root) .then(function() { logger.log("Started Watch"); }) .fail(function(err) { logger.error("Failed to start Watch because of:"); logger.exception(err, false); }).fin(function() { // Register register(null, {}); }); } // Exports module.exports = setup;
function setup(options, imports, register) { // Import var server = imports.server.http; var port = imports.server.port; var watch = imports.watch; var workspace = imports.workspace; var logger = imports.logger.namespace("codebox"); // Start server server.listen(port); server.on('listening', function() { logger.log("Server is listening on ", port); watch.init(workspace.root) .then(function() { logger.log("Started Watch"); }) .fail(function(err) { logger.error("Failed to start Watch because of:"); logger.exception(err, false); }).fin(function() { // Register register(null, {}); }); }) } // Exports module.exports = setup;
Add extra check to ensure child is an actual React component
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import cx from 'classnames'; import theme from './theme.css'; class Icon extends PureComponent { static propTypes = { children: PropTypes.any, className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal']), opacity: PropTypes.number, tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']), }; static defaultProps = { color: 'teal', tint: 'normal', opacity: 0.84, }; render() { const { children, className, color, tint, opacity, ...others } = this.props; const classNames = cx(theme[color], theme[tint], className); return ( <Box className={classNames} data-teamleader-ui="icon" element="span" {...others}> {React.Children.map(children, child => { // Check if child is an actual React component // if so, pass the needed props. If not, just render it. if (!child.type) { return child; } return React.cloneElement(child, { opacity, }); })} </Box> ); } } export default Icon;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import cx from 'classnames'; import theme from './theme.css'; class Icon extends PureComponent { static propTypes = { children: PropTypes.any, className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal']), opacity: PropTypes.number, tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']), }; static defaultProps = { color: 'teal', tint: 'normal', opacity: 0.84, }; render() { const { children, className, color, tint, opacity, ...others } = this.props; const classNames = cx(theme[color], theme[tint], className); return ( <Box className={classNames} data-teamleader-ui="icon" element="span" {...others}> {React.Children.map(children, child => { return React.cloneElement(child, { opacity, }); })} </Box> ); } } export default Icon;
Update example workflow to show you can use classes
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 # A simpleflow activity can be any callable, so a function works, but a class # will also work given the processing happens in __init__() @activity.with_attributes(task_list='quickstart', version='example') class Delay(object): def __init__(self, t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' task_list = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(Delay, t, y) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) futures.wait(yy, z) return z.result
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 @activity.with_attributes(task_list='quickstart', version='example') def delay(t, x): time.sleep(t) return x class BasicWorkflow(Workflow): name = 'basic' version = 'example' task_list = 'example' def run(self, x, t=30): y = self.submit(increment, x) yy = self.submit(delay, t, y) z = self.submit(double, y) print '({x} + 1) * 2 = {result}'.format( x=x, result=z.result) futures.wait(yy, z) return z.result
Set debuggee in HelloWorld example
/* See license.txt for terms of usage */ "use strict"; const self = require("sdk/self"); const { Cu, Ci } = require("chrome"); const { Panel } = require("dev/panel.js"); const { Class } = require("sdk/core/heritage"); const { Tool } = require("dev/toolbox"); /** * This object represents a new {@Toolbox} panel */ const MyPanel = Class( /** @lends MyPanel */ { extends: Panel, label: "My Panel", tooltip: "My panel tooltip", icon: "./icon-16.png", url: "./myPanel.html", /** * Executed by the framework when an instance of this panel is created. * There is one instance of this panel per {@Toolbox}. The panel is * instantiated when selected in the toolbox for the first time. */ initialize: function(options) { }, /** * Executed by the framework when the panel is destroyed. */ dispose: function() { }, /** * Executed by the framework when the panel content iframe is * constructed. Allows e.g to connect the backend through * `debuggee` object */ setup: function(options) { console.log("MyPanel.setup" + options.debuggee); this.debuggee = options.debuggee; // TODO: connect to backend using options.debuggee }, onReady: function() { console.log("MyPanel.onReady " + this.debuggee); } }); const myTool = new Tool({ name: "MyTool", panels: { myPanel: MyPanel } });
/* See license.txt for terms of usage */ "use strict"; const self = require("sdk/self"); const { Cu, Ci } = require("chrome"); const { Panel } = require("dev/panel.js"); const { Class } = require("sdk/core/heritage"); const { Tool } = require("dev/toolbox"); /** * This object represents a new {@Toolbox} panel */ const MyPanel = Class( /** @lends MyPanel */ { extends: Panel, label: "My Panel", tooltip: "My panel tooltip", icon: "./icon-16.png", url: "./myPanel.html", /** * Executed by the framework when an instance of this panel is created. * There is one instance of this panel per {@Toolbox}. The panel is * instantiated when selected in the toolbox for the first time. */ initialize: function(options) { }, /** * Executed by the framework when the panel is destroyed. */ dispose: function() { }, /** * Executed by the framework when the panel content iframe is * constructed. Allows e.g to connect the backend through * `debuggee` object */ setup: function(options) { // TODO: connect to backend using options.debuggee }, }); const myTool = new Tool({ name: "MyTool", panels: { myPanel: MyPanel } });
Add url to user badge properties
<?php /** * Copyright (c) ppy Pty Ltd <contact@ppy.sh>. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Models; /** * @property \Carbon\Carbon|null $awarded * @property string $description * @property string $image * @property string $url * @property int $user_id */ class UserBadge extends Model { protected $table = 'osu_badges'; protected $primaryKey = 'user_id'; protected $dates = ['awarded']; public $timestamps = false; public function imageUrl() { return "https://assets.ppy.sh/profile-badges/{$this->image}"; } }
<?php /** * Copyright (c) ppy Pty Ltd <contact@ppy.sh>. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Models; /** * @property \Carbon\Carbon|null $awarded * @property string $description * @property string $image * @property int $user_id */ class UserBadge extends Model { protected $table = 'osu_badges'; protected $primaryKey = 'user_id'; protected $dates = ['awarded']; public $timestamps = false; public function imageUrl() { return "https://assets.ppy.sh/profile-badges/{$this->image}"; } }
Fix flake8 errors: E123 closing bracket does not match indentation of opening bracket's line
import pytest from thefuck.rules.git_remote_seturl_add import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='git remote set-url origin url', stderr="fatal: No such remote")]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', stderr=""), Command('git remote add origin url'), Command('git remote remove origin'), Command('git remote prune origin'), Command('git remote set-branches origin branch')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git remote set-url origin git@github.com:nvbn/thefuck.git'), 'git remote add origin git@github.com:nvbn/thefuck.git')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
import pytest from thefuck.rules.git_remote_seturl_add import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='git remote set-url origin url', stderr="fatal: No such remote")]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', stderr=""), Command('git remote add origin url'), Command('git remote remove origin'), Command('git remote prune origin'), Command('git remote set-branches origin branch') ]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git remote set-url origin git@github.com:nvbn/thefuck.git'), 'git remote add origin git@github.com:nvbn/thefuck.git')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
Change browser build to UMD
'use strict'; var webpack = require('webpack'); var plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.optimize.OccurenceOrderPlugin() ]; if (process.env.NODE_ENV === 'production') { plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }) ); } var reactExternal = { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' }; module.exports = { externals: { 'react': reactExternal, 'react-native': reactExternal }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: 'Redux', libraryTarget: 'umd' }, plugins: plugins, resolve: { extensions: ['', '.js'] } };
'use strict'; var webpack = require('webpack'); var plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.optimize.OccurenceOrderPlugin() ]; if (process.env.NODE_ENV === 'production') { plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }) ); } module.exports = { externals: { 'react': 'React', 'react-native': 'React' }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: 'Redux', libraryTarget: 'var' }, plugins: plugins, resolve: { extensions: ['', '.js'] } };
Switch entry point to click's cli
from distutils.core import setup import os from setuptools import find_packages __version__ = 'unknown' version_path = os.path.join(os.path.split(__file__)[0], 'banneret/version.py') with open(version_path) as version_file: exec(version_file.read()) URL = 'https://github.com/lancelote/banneret' setup( name='banneret', packages=find_packages(exclude=['tests', '*.test', '*.test.*']), version=__version__, description='CLI helpers for PyCharm management', author='Pavel Karateev', author_email='pavel.karateev@jetbrains.com', url=URL, download_url=URL + '/archive/{}.tar.gz'.format(__version__), keywords=['pycharm', 'cli'], entry_points={ 'console_scripts': [ 'bnrt = banneret.main:cli' ] }, install_requires=[ 'click' ], extras_require={ 'test': ['pytest', 'pytest-mock', 'tox'], 'lint': ['pylint', 'pydocstyle', 'pycodestyle', 'mypy'], 'docker': ['docker'] } )
from distutils.core import setup import os from setuptools import find_packages __version__ = 'unknown' version_path = os.path.join(os.path.split(__file__)[0], 'banneret/version.py') with open(version_path) as version_file: exec(version_file.read()) URL = 'https://github.com/lancelote/banneret' setup( name='banneret', packages=find_packages(exclude=['tests', '*.test', '*.test.*']), version=__version__, description='CLI helpers for PyCharm management', author='Pavel Karateev', author_email='pavel.karateev@jetbrains.com', url=URL, download_url=URL + '/archive/{}.tar.gz'.format(__version__), keywords=['pycharm', 'cli'], entry_points={ 'console_scripts': [ 'bnrt = banneret.main:main' ] }, install_requires=[ 'click' ], extras_require={ 'test': ['pytest', 'pytest-mock', 'tox'], 'lint': ['pylint', 'pydocstyle', 'pycodestyle', 'mypy'], 'docker': ['docker'] } )
Use PExpect to change the logging buffer size (logging buffered <size>) on pynet-rtr2. Verify this change by examining the output of 'show run'.
# Use PExpect to change the logging buffer size (logging buffered <size>) on pynet-rtr2. Verify this change by examining the output of 'show run'. #!/usr/bin/env python import sys from getpass import getpass import time import pexpect def main(): ip_addr = '50.76.53.27' username = 'pyclass' port = 8022 password = getpass() # ssh -l pyclass 50.76.53.27 -p 8022 ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port)) #Useful for debugging the session #ssh_conn.logfile = sys.stdout ssh_conn.timeout = 3 ssh_conn.expect('ssword:') time.sleep(1) ssh_conn.sendline(password) ssh_conn.expect('#') ssh_conn.sendline('terminal lenght 0') ssh_conn.expect('#') ssh_conn.sendline('configure terminal') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('logging buffered 20000') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('exit') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('show running-config') time.sleep(2) ssh_conn.expect('no logging console') # Print the output of the show ip int brief command. print ssh_conn.before if __name__ == "__main__": main()
#!/usr/bin/env python import sys from getpass import getpass import time import pexpect def main(): ip_addr = '50.76.53.27' username = 'pyclass' port = 8022 password = getpass() # ssh -l pyclass 50.76.53.27 -p 8022 ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port)) #Useful for debugging the session #ssh_conn.logfile = sys.stdout ssh_conn.timeout = 3 ssh_conn.expect('ssword:') time.sleep(1) ssh_conn.sendline(password) ssh_conn.expect('#') ssh_conn.sendline('terminal lenght 0') ssh_conn.expect('#') ssh_conn.sendline('configure terminal') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('logging buffered 20000') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('exit') time.sleep(1) ssh_conn.expect('#') ssh_conn.sendline('show running-config') time.sleep(2) ssh_conn.expect('no logging console') # Print the output of the show ip int brief command. print ssh_conn.before if __name__ == "__main__": main()
Fix travis, make sure skipif condition resolves to a bool
#!/usr/bin/env python # -*- coding: utf-8 -*- """ skipif_markers -------------- Contains pytest skipif markers to be used in the suite. """ import pytest import os try: os.environ[u'TRAVIS'] except KeyError: travis = False else: travis = True try: os.environ[u'DISABLE_NETWORK_TESTS'] except KeyError: no_network = False else: no_network = True # For some reason pytest incorrectly uses the first reason text regardless of # which condition matches. Using a unified message for now # travis_reason = 'Works locally with tox but fails on Travis.' # no_network_reason = 'Needs a network connection to GitHub.' reason = 'Fails on Travis or else there is no network connection to GitHub' skipif_travis = pytest.mark.skipif(travis, reason=reason) skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ skipif_markers -------------- Contains pytest skipif markers to be used in the suite. """ import pytest import os try: travis = os.environ[u'TRAVIS'] except KeyError: travis = False try: no_network = os.environ[u'DISABLE_NETWORK_TESTS'] except KeyError: no_network = False # For some reason pytest incorrectly uses the first reason text regardless of # which condition matches. Using a unified message for now # travis_reason = 'Works locally with tox but fails on Travis.' # no_network_reason = 'Needs a network connection to GitHub.' reason = 'Fails on Travis or else there is no network connection to GitHub' skipif_travis = pytest.mark.skipif(travis, reason=reason) skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
Add dynamic alias task for running individual tests
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { all: { src: ['benchmarks/*.js'], options: { times: 10 } } }, nodeunit: { files: ['test/*_test.js'], }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: { src: 'Gruntfile.js' }, lib: { src: ['lib/**/*.js'] }, test: { src: ['test/**/*_test.js'] }, }, }); // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events grunt.registerTask('test', function(file) { grunt.config('nodeunit.files', String(grunt.config('nodeunit.files')).replace('*', file || '*')); grunt.task.run('nodeunit'); }); grunt.loadNpmTasks('grunt-benchmark'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('default', ['jshint', 'nodeunit']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { all: { src: ['benchmarks/*.js'], options: { times: 10 } } }, nodeunit: { files: ['test/*_test.js'], }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: { src: 'Gruntfile.js' }, lib: { src: ['lib/**/*.js'] }, test: { src: ['test/**/*_test.js'] }, } }); grunt.loadNpmTasks('grunt-benchmark'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('default', ['jshint', 'nodeunit']); };
Fix issue with auto complete when more than 1 editor has been created
from pyqode.core import modes from pyqode.core.api import TextHelper class AutoCompleteMode(modes.AutoCompleteMode): def __init__(self): super(AutoCompleteMode, self).__init__() try: self.QUOTES_FORMATS.pop("'") self.SELECTED_QUOTES_FORMATS.pop("'") self.MAPPING.pop("'") except KeyError: pass def _on_key_pressed(self, event): helper = TextHelper(self.editor) indent = helper.line_indent() * ' ' if self.editor.textCursor().positionInBlock() == len(indent): self.QUOTES_FORMATS['"'] = '%s:' else: self.QUOTES_FORMATS['"'] = '%s' self.QUOTES_FORMATS['{'] = '\n' + indent + '%s' self.QUOTES_FORMATS['['] = '\n' + indent + '%s' super(AutoCompleteMode, self)._on_key_pressed(event)
from pyqode.core import modes from pyqode.core.api import TextHelper class AutoCompleteMode(modes.AutoCompleteMode): def __init__(self): super(AutoCompleteMode, self).__init__() self.QUOTES_FORMATS.pop("'") self.SELECTED_QUOTES_FORMATS.pop("'") self.MAPPING.pop("'") def _on_key_pressed(self, event): helper = TextHelper(self.editor) indent = helper.line_indent() * ' ' if self.editor.textCursor().positionInBlock() == len(indent): self.QUOTES_FORMATS['"'] = '%s:' else: self.QUOTES_FORMATS['"'] = '%s' self.QUOTES_FORMATS['{'] = '\n' + indent + '%s' self.QUOTES_FORMATS['['] = '\n' + indent + '%s' super(AutoCompleteMode, self)._on_key_pressed(event)
Modify migration model to be correct
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('./database'); const db = database.db; const sqlFile = database.sqlFile; class Migration { constructor(id, from, to, updateTime) { this.id = id; this.from = from; this.to = to; this.updateTime = updateTime; } static createTables() { return db.none(sqlFile('group/create_migration_tables.sql')); } async insert(conn = db) { const migration = this; if (migration.id !== undefined) { throw new Error('Attempt to insert a migration that already has an ID'); } const resp = await conn.one(sqlFile('group/insert_new_migration.sql'), migration); this.id = resp.id; } } module.exports = Migration;
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('./database'); const db = database.db; const sqlFile = database.sqlFile; class Migration { constructor(id, from, to) { this.id = id; this.from = from this.to = to; } static createTables() { return db.none(sqlFile('group/create_migration_tables.sql')); } async insert(conn = db) { const group = this; if (group.id !== undefined) { throw new Error('Attempt to insert a group that already has an ID'); } const resp = await conn.one(sqlFile('group/insert_new_group.sql'), group); // resp = { id: 42 }, hence this line this.id = resp.id; } } module.exports = Migration;
Fix 'body' selector in init function
;var conpigurator = { active:false, handleChange:function(event){ if($(event.target).hasClass('conpiguratorInput')){ if(event.target.value && event.target.value !== '' && typeof event.target.value === 'string'){ if(event.target.dataset){ var pigment = event.target.value; if(pigment.substring(0,1) !== '#') pigment = '#'+pigment; pigment = (pigment.length > 7)? pigment.substring(0,7) : pigment; conpigurator.conpigurateElements(event.target.dataset.conpigbg,'backgroundColor',pigment); conpigurator.conpigurateElements(event.target.dataset.conpigborder,'borderColor',pigment); conpigurator.conpigurateElements(event.target.dataset.conpigtext,'color',pigment); } } } }, conpigurateElements:function(selector,colorProperty,pigment){ if(selector){ colorProperty = colorProperty || 'backgroundColor'; $(selector).css(colorProperty,pigment); } }, init:function(){ if(!conpigurator.active){ $('body').on('change',function(event){conpigurator.handleChange(event);}); conpigurator.active = true; } } };
;var conpigurator = { active:false, handleChange:function(event){ if($(event.target).hasClass('conpiguratorInput')){ if(event.target.value && event.target.value !== '' && typeof event.target.value === 'string'){ if(event.target.dataset){ var pigment = event.target.value; if(pigment.substring(0,1) !== '#') pigment = '#'+pigment; pigment = (pigment.length > 7)? pigment.substring(0,7) : pigment; conpigurator.conpigurateElements(event.target.dataset.conpigbg,'backgroundColor',pigment); conpigurator.conpigurateElements(event.target.dataset.conpigborder,'borderColor',pigment); conpigurator.conpigurateElements(event.target.dataset.conpigtext,'color',pigment); } } } }, conpigurateElements:function(selector,colorProperty,pigment){ if(selector){ colorProperty = colorProperty || 'backgroundColor'; $(selector).css(colorProperty,pigment); } }, init:function(){ if(!conpigurator.active){ $(body).on('change',function(event){conpigurator.handleChange(event);}); conpigurator.active = true; } } };
Make db upgrade step 20 more robust. git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@5815 af82e41b-90c4-0310-8c96-b1721e28e2e2
from trac.db import Table, Column, Index, DatabaseManager from trac.core import TracError from trac.versioncontrol.cache import CACHE_YOUNGEST_REV def do_upgrade(env, ver, cursor): """Modify the repository cache scheme (if needed) Now we use the 'youngest_rev' entry in the system table to explicitly store the youngest rev in the cache. """ db = env.get_db_cnx() try: repos = env.get_repository() youngest = repos.get_youngest_rev_in_cache(db) or '' except TracError: # no repository available youngest = '' # deleting first, for the 0.11dev and 0.10.4dev users cursor.execute("DELETE FROM system WHERE name=%s", (CACHE_YOUNGEST_REV,)) cursor.execute("INSERT INTO system (name, value) VALUES (%s, %s)", (CACHE_YOUNGEST_REV, youngest))
from trac.db import Table, Column, Index, DatabaseManager from trac.core import TracError from trac.versioncontrol.cache import CACHE_YOUNGEST_REV def do_upgrade(env, ver, cursor): """Modify the repository cache scheme (if needed) Now we use the 'youngest_rev' entry in the system table to explicitly store the youngest rev in the cache. """ db = env.get_db_cnx() try: repos = env.get_repository() youngest = repos.get_youngest_rev_in_cache(db) or '' # deleting first, for the 0.11dev and 0.10.4dev users cursor.execute("DELETE FROM system WHERE name=%s", (CACHE_YOUNGEST_REV,)) cursor.execute("INSERT INTO system (name, value) VALUES (%s, %s)", (CACHE_YOUNGEST_REV, youngest)) except TracError: # no repository available pass
Use 'o' as the order by parameter in clean_query_string
# django from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # standard library def paginate(request, objects, page_size=25): paginator = Paginator(objects, page_size) page = request.GET.get('p') try: paginated_objects = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. paginated_objects = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. paginated_objects = paginator.page(paginator.num_pages) return paginated_objects def clean_query_string(request): clean_query_set = request.GET.copy() clean_query_set = dict( (k, v) for k, v in request.GET.items() if k != 'o' ) try: del clean_query_set['p'] except: pass mstring = [] for key in clean_query_set.keys(): valuelist = request.GET.getlist(key) mstring.extend(['%s=%s' % (key, val) for val in valuelist]) return '&'.join(mstring)
# django from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # standard library def paginate(request, objects, page_size=25): paginator = Paginator(objects, page_size) page = request.GET.get('p') try: paginated_objects = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. paginated_objects = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. paginated_objects = paginator.page(paginator.num_pages) return paginated_objects def clean_query_string(request): clean_query_set = request.GET.copy() clean_query_set = dict( (k, v) for k, v in request.GET.items() if not k.startswith('o') ) try: del clean_query_set['p'] except: pass mstring = [] for key in clean_query_set.keys(): valuelist = request.GET.getlist(key) mstring.extend(['%s=%s' % (key, val) for val in valuelist]) return '&'.join(mstring)
Move to 100% of Testing Code Coverage for Isbn::Validation
<?php class ValidationTest extends PHPUnit_Framework_TestCase { public function testIsbn10() { $this->assertTrue(Isbn\Validation::isbn10('8881837188')); $this->assertFalse(Isbn\Validation::isbn10('8881837187')); } public function testIsbn13() { $this->assertTrue(Isbn\Validation::isbn13('9788889527191')); $this->assertFalse(Isbn\Validation::isbn13('9788889527190')); } public function testIsbn() { $this->assertTrue(Isbn\Validation::isbn('8881837188')); $this->assertFalse(Isbn\Validation::isbn('8881837187')); $this->assertTrue(Isbn\Validation::isbn('9788889527191')); $this->assertFalse(Isbn\Validation::isbn('9788889527190')); $this->assertFalse(Isbn\Validation::isbn('97888895271910')); } }
<?php class ValidationTest extends PHPUnit_Framework_TestCase { public function testIsbn10() { $this->assertTrue(Isbn\Validation::isbn10('8881837188')); $this->assertFalse(Isbn\Validation::isbn10('8881837187')); } public function testIsbn13() { $this->assertTrue(Isbn\Validation::isbn13('9788889527191')); $this->assertFalse(Isbn\Validation::isbn13('9788889527190')); } public function testIsbn() { $this->assertTrue(Isbn\Validation::isbn('8881837188')); $this->assertFalse(Isbn\Validation::isbn('8881837187')); $this->assertTrue(Isbn\Validation::isbn('9788889527191')); $this->assertFalse(Isbn\Validation::isbn('9788889527190')); } }
Fix Catchable fatal error en objetos null al llamar a __toString()
<?php function imc_parse_text($str,$obj){ preg_match_all("|%(.*)%|U", $str, $match, PREG_PATTERN_ORDER); foreach($match[1] AS $field){ if(!isset($obj[$field])){ echo '<p style="color:red"><b>ParseError</b>: Field <b>'.$field.'</b> not found on object <b>'.get_class($obj)."</b>.</p>"; $str = str_replace('%'.$field.'%','',$str); }else{ $str = str_replace('%'.$field.'%',$obj[$field],$str); } } preg_match_all("|#(.*)#|U", $str, $match, PREG_PATTERN_ORDER); foreach($match[1] AS $function){ if(!is_null($obj->$function()->__toString())) $str = str_replace('#'.$function.'#',$obj->$function(),$str); else $str = str_replace('#'.$function.'#','',$str); } return html_entity_decode($str); }
<?php function imc_parse_text($str,$obj){ preg_match_all("|%(.*)%|U", $str, $match, PREG_PATTERN_ORDER); foreach($match[1] AS $field){ if(!isset($obj[$field])){ echo '<p style="color:red"><b>ParseError</b>: Field <b>'.$field.'</b> not found on object <b>'.get_class($obj)."</b>.</p>"; $str = str_replace('%'.$field.'%','',$str); }else{ $str = str_replace('%'.$field.'%',$obj[$field],$str); } } preg_match_all("|#(.*)#|U", $str, $match, PREG_PATTERN_ORDER); foreach($match[1] AS $function){ $str = str_replace('#'.$function.'#',$obj->$function(),$str); } return html_entity_decode($str); }
Fix ember-table column definition importing
import EmberTableColumnDefinition from 'ember-table/models/column-definition'; import ListFormPageController from '../controllers/list-form-page'; export default ListFormPageController.extend({ _currentRow: undefined, actions: { // Save the currentRow on rowClicked. rowClick: function(record) { this.set('_currentRow', record); }, saveLookupDialog: function() { var saveTo = this.get('saveTo'); if (!saveTo) { throw new Error('Don\'t know where to save - no saveTo data defined.'); } saveTo.model.set(saveTo.propName, this.get('_currentRow')); // Manually set isDirty flag, because its not working now // when change relation props. // No check for 'old' and 'new' lookup data equality, because ember // will do it automatically after bug fix. saveTo.model.send('becomeDirty'); } }, /* * Override a function to create EmberTableColumnDefinition object * without sortable-column mixin. */ createColumnDefinition: function(params) { return EmberTableColumnDefinition.create(params); }, clear: function() { this.set('_currentRow', undefined); this.set('saveTo', undefined); this.set('modelProjection', undefined); return this; } });
import EmberTableColumnDefinition from '../column-definition'; import ListFormPageController from '../controllers/list-form-page'; export default ListFormPageController.extend({ _currentRow: undefined, actions: { // Save the currentRow on rowClicked. rowClick: function(record) { this.set('_currentRow', record); }, saveLookupDialog: function() { var saveTo = this.get('saveTo'); if (!saveTo) { throw new Error('Don\'t know where to save - no saveTo data defined.'); } saveTo.model.set(saveTo.propName, this.get('_currentRow')); // Manually set isDirty flag, because its not working now // when change relation props. // No check for 'old' and 'new' lookup data equality, because ember // will do it automatically after bug fix. saveTo.model.send('becomeDirty'); } }, /* * Override a function to create EmberTableColumnDefinition object * without sortable-column mixin. */ createColumnDefinition: function(params) { return EmberTableColumnDefinition.create(params); }, clear: function() { this.set('_currentRow', undefined); this.set('saveTo', undefined); this.set('modelProjection', undefined); return this; } });
Comment out missed curly brace
// ========================================================================== // Application JavaScript for IMTD? // ========================================================================== document.addEventListener('DOMContentLoaded', init); function init() { var trainInfo = document.querySelector('.train-info'); trainInfo.addEventListener('click', function(e) { handleDelayInfoClick(e); }); function handleDelayInfoClick(event) { event.preventDefault(); if (event.target.parentElement.parentElement.nextSibling.classList.contains('delay-info--show')) { event.target.parentElement.parentElement.nextSibling.classList.remove('delay-info--show') } else { event.target.parentElement.parentElement.nextSibling.classList.add('delay-info--show'); } } // function handleRefresh() { // var oReq = new XMLHttpRequest(); // oReq.addEventListener("load", handleResponse); // oReq.open("GET", "http://localhost:5000/fetch"); // oReq.send(); // } // function handleResponse(res) { // console.log(res); // var data = JSON.parse(res.target.response); // if (res.target.status === 200) { // // OK // } //} }
// ========================================================================== // Application JavaScript for IMTD? // ========================================================================== document.addEventListener('DOMContentLoaded', init); function init() { var trainInfo = document.querySelector('.train-info'); trainInfo.addEventListener('click', function(e) { handleDelayInfoClick(e); }); function handleDelayInfoClick(event) { event.preventDefault(); if (event.target.parentElement.parentElement.nextSibling.classList.contains('delay-info--show')) { event.target.parentElement.parentElement.nextSibling.classList.remove('delay-info--show') } else { event.target.parentElement.parentElement.nextSibling.classList.add('delay-info--show'); } } // function handleRefresh() { // var oReq = new XMLHttpRequest(); // oReq.addEventListener("load", handleResponse); // oReq.open("GET", "http://localhost:5000/fetch"); // oReq.send(); // } // function handleResponse(res) { // console.log(res); // var data = JSON.parse(res.target.response); // if (res.target.status === 200) { // // OK // } } }
Add color as an optional property
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Loader from 'react-loader'; import { oneOrManyChildElements } from '../../prop-types'; export default class LoaderComponent extends Component { static propTypes = { children: oneOrManyChildElements, loaded: PropTypes.bool, className: PropTypes.string, color: PropTypes.string, }; static defaultProps = { children: null, loaded: false, className: '', color: '#373a3c', }; render() { const { children, loaded, className, color, } = this.props; return ( <Loader loaded={loaded} // lines={10} width={4} scale={0.6} color={color} component="span" className={className} > {children} </Loader> ); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Loader from 'react-loader'; import { oneOrManyChildElements } from '../../prop-types'; export default class LoaderComponent extends Component { static propTypes = { children: oneOrManyChildElements, loaded: PropTypes.bool, className: PropTypes.string, }; static defaultProps = { children: null, loaded: false, className: '', }; render() { const { children, loaded, className, } = this.props; return ( <Loader loaded={loaded} // lines={10} width={4} scale={0.6} color="#373a3c" component="span" className={className} > {children} </Loader> ); } }
Sort function imports to fit with documentation order
"""Collection of :class:`~chainer.Function` implementations.""" # Parameterized function classes from batch_normalization import BatchNormalization from convolution_2d import Convolution2D from embed_id import EmbedID from inception import Inception from linear import Linear from parameter import Parameter from prelu import PReLU # Array manipulation functions from concat import concat from copy import copy from dropout import dropout from identity import identity # Activation functions from basic_math import exp, log from leaky_relu import leaky_relu from lstm import lstm from relu import relu from sigmoid import sigmoid from softmax import softmax from tanh import tanh # Pooling functions from pooling_2d import average_pooling_2d, max_pooling_2d # Loss, evaluation and aggregation from accuracy import accuracy from mean_squared_error import mean_squared_error from softmax_cross_entropy import softmax_cross_entropy from sum import sum
# Non-parameterized functions from accuracy import accuracy from basic_math import exp, log from concat import concat from copy import copy from dropout import dropout from identity import identity from leaky_relu import leaky_relu from lstm import lstm from mean_squared_error import mean_squared_error from pooling_2d import average_pooling_2d, max_pooling_2d from relu import relu from sigmoid import sigmoid from softmax import softmax from softmax_cross_entropy import softmax_cross_entropy from sum import sum from tanh import tanh # Parameterized layers from batch_normalization import BatchNormalization from convolution_2d import Convolution2D from embed_id import EmbedID from inception import Inception from linear import Linear from parameter import Parameter from prelu import PReLU
Speed up webpack bundle builds This is the equivalent of: https://github.com/facebook/relay/commit/f7f6c100b98450b9587a2bbf3fdaf21c78b024cc Speeds up the first-build from 12s to 4s on my machine.
import express from 'express'; import graphQLHTTP from 'express-graphql'; import path from 'path'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import {Schema} from './data/schema'; const APP_PORT = 3000; const GRAPHQL_PORT = 8080; // Expose a GraphQL endpoint var graphQLServer = express(); graphQLServer.use('/', graphQLHTTP({schema: Schema, pretty: true})); graphQLServer.listen(GRAPHQL_PORT, () => console.log( `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` )); // Serve the Relay app var compiler = webpack({ entry: path.resolve(__dirname, 'js', 'app.js'), module: { loaders: [ { exclude: /node_modules/, loader: 'babel', query: {stage: 0, plugins: ['./build/babelRelayPlugin']}, test: /\.js$/, } ] }, output: {filename: 'app.js', path: '/'} }); var app = new WebpackDevServer(compiler, { contentBase: '/public/', proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`}, publicPath: '/js/', stats: {colors: true} }); // Serve static resources app.use('/', express.static(path.resolve(__dirname, 'public'))); app.listen(APP_PORT, () => { console.log(`App is now running on http://localhost:${APP_PORT}`); });
import express from 'express'; import graphQLHTTP from 'express-graphql'; import path from 'path'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import {Schema} from './data/schema'; const APP_PORT = 3000; const GRAPHQL_PORT = 8080; // Expose a GraphQL endpoint var graphQLServer = express(); graphQLServer.use('/', graphQLHTTP({schema: Schema, pretty: true})); graphQLServer.listen(GRAPHQL_PORT, () => console.log( `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` )); // Serve the Relay app var compiler = webpack({ entry: path.resolve(__dirname, 'js', 'app.js'), module: { loaders: [ { test: /\.js$/, loader: 'babel', query: {stage: 0, plugins: ['./build/babelRelayPlugin']} } ] }, output: {filename: 'app.js', path: '/'} }); var app = new WebpackDevServer(compiler, { contentBase: '/public/', proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`}, publicPath: '/js/', stats: {colors: true} }); // Serve static resources app.use('/', express.static(path.resolve(__dirname, 'public'))); app.listen(APP_PORT, () => { console.log(`App is now running on http://localhost:${APP_PORT}`); });
Update test assertion on validation message
'use strict'; var expect = require('chai').expect; var validator = require('../'); describe('Date validator', function () { var simpleRules = { birthday: ['date-format:YYYY-MM-DD'] }; var getTestObject = function () { return { birthday: '1993-09-02', }; }; it('should success', function () { var result = validator.validate(simpleRules, getTestObject()); var err = result.messages; expect(result.success).to.equal(true); expect(err).to.not.have.property('birthday'); }); it('should fail', function () { var testObj = getTestObject(); testObj.birthday = '02-09-1993'; var result = validator.validate(simpleRules, testObj); var err = result.messages; expect(result.success).to.equal(false); expect(err).to.have.property('birthday'); expect(err.birthday['date-format:$1']).to.equal('Birthday must be in format YYYY-MM-DD.'); }); });
'use strict'; var expect = require('chai').expect; var validator = require('../'); describe('Date validator', function () { var simpleRules = { birthday: ['date-format:YYYY-MM-DD'] }; var getTestObject = function () { return { birthday: '1993-09-02', }; }; it('should success', function () { var result = validator.validate(simpleRules, getTestObject()); var err = result.messages; expect(result.success).to.equal(true); expect(err).to.not.have.property('birthday'); }); it('should fail', function () { var testObj = getTestObject(); testObj.birthday = '02-09-1993'; var result = validator.validate(simpleRules, testObj); var err = result.messages; expect(result.success).to.equal(false); expect(err).to.have.property('birthday'); expect(err.birthday.date).to.equal('Date format must conform YYYY-MM-DD.'); }); });
Add missing event in previous commit
package logging import ( "fmt" "time" durationfmt "github.com/cloudfoundry/bosh-micro-cli/durationfmt" bmui "github.com/cloudfoundry/bosh-micro-cli/ui" ) type Event struct { Time time.Time Stage string Total int Task string State string Index int } type EventLogger interface { AddEvent(event Event) } func NewEventLogger(ui bmui.UI) EventLogger { return &eventLogger{ ui: ui, startedTasks: make(map[string]time.Time), } } type eventLogger struct { ui bmui.UI startedTasks map[string]time.Time } func (e *eventLogger) AddEvent(event Event) { key := fmt.Sprintf("%s > %s.", event.Stage, event.Task) if event.State == "started" { if event.Index == 1 { e.ui.Sayln(fmt.Sprintf("Started %s", event.Stage)) } e.ui.Say(fmt.Sprintf("Started %s", key)) e.startedTasks[key] = event.Time } else if event.State == "finished" { duration := event.Time.Sub(e.startedTasks[key]) e.ui.Sayln(fmt.Sprintf(" Done (%s)", durationfmt.Format(duration))) if event.Index == event.Total { e.ui.Sayln(fmt.Sprintf("Done %s", event.Stage)) } } }
package logging import ( "fmt" durationfmt "github.com/cloudfoundry/bosh-micro-cli/durationfmt" "time" bmui "github.com/cloudfoundry/bosh-micro-cli/ui" ) type EventLogger interface { // NEW AddEvent(event Event) } func NewEventLogger(ui bmui.UI) EventLogger { return &eventLogger{ ui: ui, startedTasks: make(map[string]time.Time), } } type eventLogger struct { ui bmui.UI startedTasks map[string]time.Time } func (e *eventLogger) AddEvent(event Event) { key := fmt.Sprintf("%s > %s.", event.Stage, event.Task) if event.State == "started" { if event.Index == 1 { e.ui.Sayln(fmt.Sprintf("Started %s", event.Stage)) } e.ui.Say(fmt.Sprintf("Started %s", key)) e.startedTasks[key] = event.Time } else if event.State == "finished" { duration := event.Time.Sub(e.startedTasks[key]) e.ui.Sayln(fmt.Sprintf(" Done (%s)", durationfmt.Format(duration))) if event.Index == event.Total { e.ui.Sayln(fmt.Sprintf("Done %s", event.Stage)) } } }
Test if album can be pulled from Audio Station
'use strict'; require('../../../env'); let payload = {}; payload.build = function() { return (req, res, next) => { console.log(req.query); // req.body.album = album; req.body.api_key = process.env.API_KEY; req.body.artist = req.query.artist; req.body.format = 'json'; req.body.method = 'track.scrobble'; req.body.sk = process.env.SK; req.body.timestamp = Math.floor(new Date() / 1000); req.body.track = req.query.title; next(); }; }; payload.squish = function() { return (req, res, next) => { let raw = ''; for (var key in req.body) { if (req.body.hasOwnProperty(key) && key != 'format' && key != 'secret') { raw += key + req.body[key]; }; }; if (req.body.secret) { raw += req.body.secret; } else { raw += process.env.SECRET; } req.body.api_sig = raw; next(); }; }; module.exports = payload;
'use strict'; require('../../../env'); let payload = {}; payload.build = function() { return (req, res, next) => { // req.body.album = album; req.body.api_key = process.env.API_KEY; req.body.artist = req.query.artist; req.body.format = 'json'; req.body.method = 'track.scrobble'; req.body.sk = process.env.SK; req.body.timestamp = Math.floor(new Date() / 1000); req.body.track = req.query.title; next(); }; }; payload.squish = function() { return (req, res, next) => { let raw = ''; for (var key in req.body) { if (req.body.hasOwnProperty(key) && key != 'format' && key != 'secret') { raw += key + req.body[key]; }; }; if (req.body.secret) { raw += req.body.secret; } else { raw += process.env.SECRET; } req.body.api_sig = raw; next(); }; }; module.exports = payload;
Allow reading player options from config
#!/usr/bin/env node 'use strict'; const co = require('co'); const { Game, ReadlineInterface } = require('../'); const path = require('path'); const args = process.argv.slice(2); function *loadGame(pathArgIndex) { const target = args[pathArgIndex]; if (!target) throw new Error('No game path provided'); const parsed = path.parse(target); const game = new Game(); switch (parsed.ext) { case '.json': yield game.loadJson(target); break; case '.esf': yield game.loadScene(target); break; default: yield game.loadDir(target); break; } return game; } const actions = { play: function*() { const game = yield loadGame(1); yield game.run(new ReadlineInterface(), game.data.config.playerOptions); }, export: function*() { const game = yield loadGame(1); yield game.saveJson(args[2]); }, }; function *main() { const action = args[0]; const func = actions[action]; if (!func) throw new Error(`'${action}' is not a valid action`); yield func(); } co(main).catch(err => console.error(err.stack));
#!/usr/bin/env node 'use strict'; const co = require('co'); const { Game, ReadlineInterface } = require('../'); const path = require('path'); const args = process.argv.slice(2); function *loadGame(pathArgIndex) { const target = args[pathArgIndex]; if (!target) throw new Error('No game path provided'); const parsed = path.parse(target); const game = new Game(); switch (parsed.ext) { case '.json': yield game.loadJson(target); break; case '.esf': yield game.loadScene(target); break; default: yield game.loadDir(target); break; } return game; } const actions = { play: function*() { const game = yield loadGame(1); yield game.run(new ReadlineInterface()); }, export: function*() { const game = yield loadGame(1); yield game.saveJson(args[2]); }, }; function *main() { const action = args[0]; const func = actions[action]; if (!func) throw new Error(`'${action}' is not a valid action`); yield func(); } co(main).catch(err => console.error(err.stack));
Set timestamps flag true for user schema
var bcrypt = require('bcrypt-nodejs'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: String, email: { type: String, unique: true, lowercase: true }, password: { type: String, required: true }, passwordResetToken: String, passwordResetExpires: Date }, { timestamps: true }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, function(err, salt) { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) { return next(err); } user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; var User = mongoose.model('User', userSchema); module.exports = User;
var bcrypt = require('bcrypt-nodejs'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: String, email: { type: String, unique: true, lowercase: true }, password: { type: String, required: true }, passwordResetToken: String, passwordResetExpires: Date }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, function(err, salt) { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) { return next(err); } user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; var User = mongoose.model('User', userSchema); module.exports = User;
[zmarkdown] Allow using details for custom-blocks
const gh = require('hast-util-sanitize/lib/github') const katex = require('./katex') const merge = require('deepmerge') module.exports = merge.all([gh, katex, { tagNames: ['span', 'abbr', 'figure', 'figcaption', 'iframe'], attributes: { a: ['ariaHidden', 'class', 'className'], abbr: ['title'], code: ['class', 'className'], details: ['class', 'className'], div: ['id', 'class', 'className'], h1: ['ariaHidden'], h2: ['ariaHidden'], h3: ['ariaHidden'], iframe: ['allowfullscreen', 'frameborder', 'height', 'src', 'width'], img: ['class', 'className'], span: ['id', 'data-count', 'class', 'className'], summary: ['class', 'className'], th: ['colspan', 'colSpan', 'rowSpan', 'rowspan'], td: ['colspan', 'colSpan', 'rowSpan', 'rowspan'], }, protocols: { href: ['ftp', 'dav', 'sftp', 'magnet', 'tftp', 'view-source'], src: ['ftp', 'dav', 'sftp', 'tftp'], }, clobberPrefix: '', clobber: [], }])
const gh = require('hast-util-sanitize/lib/github') const katex = require('./katex') const merge = require('deepmerge') module.exports = merge.all([gh, katex, { tagNames: ['span', 'abbr', 'figure', 'figcaption', 'iframe'], attributes: { a: ['ariaHidden', 'class', 'className'], div: ['id', 'class', 'className'], span: ['id', 'data-count', 'class', 'className'], h1: ['ariaHidden'], h2: ['ariaHidden'], h3: ['ariaHidden'], abbr: ['title'], img: ['class'], code: ['className'], th: ['colspan', 'colSpan', 'rowSpan', 'rowspan'], td: ['colspan', 'colSpan', 'rowSpan', 'rowspan'], iframe: ['allowfullscreen', 'frameborder', 'height', 'src', 'width'], }, protocols: { href: ['ftp', 'dav', 'sftp', 'magnet', 'tftp', 'view-source'], src: ['ftp', 'dav', 'sftp', 'tftp'], }, clobberPrefix: '', clobber: [], }])
Update the factory after common js editor change
/******************************************************************************* * Copyright (c) 2014 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package com.codenvy.ide.editor.orion.client; import javax.inject.Inject; import com.codenvy.ide.editor.common.client.filetype.FileTypeIdentifier; import com.codenvy.ide.editor.common.client.texteditor.EditorWidgetFactory; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorPartView; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorPartViewImpl; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorViewFactory; public class OrionTextEditorViewFactory implements EmbeddedTextEditorViewFactory { @Inject private EditorWidgetFactory<OrionEditorWidget> widgetFactory; @Inject private FileTypeIdentifier fileTypeIdentifier; @Override public EmbeddedTextEditorPartView createTextEditorPartView() { return new EmbeddedTextEditorPartViewImpl<OrionEditorWidget>(this.widgetFactory, this.fileTypeIdentifier); } }
/******************************************************************************* * Copyright (c) 2014 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package com.codenvy.ide.editor.orion.client; import javax.inject.Inject; import com.codenvy.ide.Resources; import com.codenvy.ide.dto.DtoFactory; import com.codenvy.ide.editor.common.client.texteditor.EditorWidgetFactory; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorPartView; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorPartViewImpl; import com.codenvy.ide.editor.common.client.texteditor.EmbeddedTextEditorViewFactory; public class OrionTextEditorViewFactory implements EmbeddedTextEditorViewFactory { @Inject private EditorWidgetFactory<OrionEditorWidget> widgetFactory; @Override public EmbeddedTextEditorPartView createTextEditorPartView(final Resources resources, DtoFactory dtoFactory) { return new EmbeddedTextEditorPartViewImpl<OrionEditorWidget>(this.widgetFactory); } }
Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
Refresh sign fix + comments in permissions files + more trimming in permission matching
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class VersionNumbering { final static String version = "248"; static String name = "default"; static final String slash = System.getProperty("file.separator"); static String prefix = "default"; static void updateUpdatr() { if( !(new File( "Updatr")).exists() ) { (new File( "Updatr")).mkdir(); } try { BufferedWriter bw = new BufferedWriter(new FileWriter("Updatr" + slash + name + ".updatr")); bw.write( "name=" + name ); bw.newLine(); bw.write( "version=" + version ); bw.newLine(); bw.write( "url=www.prydwen.net/minec/latest" + prefix + "/" + name + ".updatr"); bw.newLine(); bw.write( "file=www.prydwen.net/minec/latest" + prefix + "/" + name + ".updatr"); bw.newLine(); bw.write( "notes="); bw.newLine(); bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class VersionNumbering { final static String version = "247"; static String name = "default"; static final String slash = System.getProperty("file.separator"); static String prefix = "default"; static void updateUpdatr() { if( !(new File( "Updatr")).exists() ) { (new File( "Updatr")).mkdir(); } try { BufferedWriter bw = new BufferedWriter(new FileWriter("Updatr" + slash + name + ".updatr")); bw.write( "name=" + name ); bw.newLine(); bw.write( "version=" + version ); bw.newLine(); bw.write( "url=www.prydwen.net/minec/latest" + prefix + "/" + name + ".updatr"); bw.newLine(); bw.write( "file=www.prydwen.net/minec/latest" + prefix + "/" + name + ".updatr"); bw.newLine(); bw.write( "notes="); bw.newLine(); bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Add field instead of alter field
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0013_make_rendition_upload_callable'), ('catalogue', '0010_auto_20160616_1048'), ] operations = [ migrations.AddField( model_name='category', name='description', field=models.TextField(verbose_name='Description', blank=True), ), migrations.AddField( model_name='category', name='image', field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True), ), migrations.AddField( model_name='category', name='name', field=models.CharField(max_length=255, verbose_name='Name', db_index=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0013_make_rendition_upload_callable'), ('catalogue', '0010_auto_20160616_1048'), ] operations = [ migrations.AddField( model_name='category', name='description', field=models.TextField(verbose_name='Description', blank=True), ), migrations.AddField( model_name='category', name='image', field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True), ), migrations.AlterField( model_name='category', name='name', field=models.CharField(max_length=255, verbose_name='Name', db_index=True), ), ]
Fix grammar in a Javadoc
/* * Copyright 2017, 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. */ /** * The API for the JDBC-based storage implementation. * * @see io.spine.server.storage.jdbc.JdbcStorageFactory for the library entry point */ @ParametersAreNonnullByDefault package io.spine.server.storage.jdbc; import javax.annotation.ParametersAreNonnullByDefault;
/* * Copyright 2017, 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. */ /** * The API for the JDBC-based storage implementations. * * @see io.spine.server.storage.jdbc.JdbcStorageFactory for the library entry point */ @ParametersAreNonnullByDefault package io.spine.server.storage.jdbc; import javax.annotation.ParametersAreNonnullByDefault;
Fix gallery URL detection for feeds... again They changed the HTML structure again it seems
<?php class ExPage_Index extends ExPage_Abstract { public function isLastPage() { return (count($this->find('td.ptds + td.ptdd')) > 0); } public function getGalleries() { $ret = array(); $links = $this->find('.itg.gld .gl1t a'); foreach ($links as $linkElem) { $gallery = new stdClass(); $link = pq($linkElem); $gallery->name = $link->text(); preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches); if (isset($matches[1]) && isset($matches[2])) { $gallery->exhenid = $matches[1]; $gallery->hash = $matches[2]; $ret[] = $gallery; } } return $ret; } }
<?php class ExPage_Index extends ExPage_Abstract { public function isLastPage() { return (count($this->find('td.ptds + td.ptdd')) > 0); } public function getGalleries() { $ret = array(); $links = $this->find('.itg.gld .gl1t .glname a'); foreach ($links as $linkElem) { $gallery = new stdClass(); $link = pq($linkElem); $gallery->name = $link->text(); preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches); if (isset($matches[1]) && isset($matches[2])) { $gallery->exhenid = $matches[1]; $gallery->hash = $matches[2]; $ret[] = $gallery; } } return $ret; } }
Allow public access to default settings
/*! * jQuery Sticky Footer v1.2.1 * * Copyright 2014 miWebb and other contributors * Released under the MIT license */ (function($) { $.fn.stickyFooter = function(options) { // Options var options = $.extend({}, $.fn.stickyFooter.defaults, options); // Element var element = this; // Initialize stickyFooter(element, options); // Resize event $(window).resize(function() { stickyFooter(element, options); }); } $.fn.stickyFooter.defaults = { class: 'sticky-footer', frame: '', content: '#page' } function stickyFooter(element, options) { // Set footer height var height = $(element).outerHeight(true); // Add content height $(options.content).each(function() { height += $(this).outerHeight(true); }); // Add the sitcky footer class if the footer & content height are smaller then the frame height if(height < $(options.frame ? options.frame : element.parent()).height()) { $(element).addClass(options.class); } else { $(element).removeClass(options.class); } } })(jQuery);
/*! * jQuery Sticky Footer v1.2.1 * * Copyright 2014 miWebb and other contributors * Released under the MIT license */ (function($) { $.fn.stickyFooter = function(options) { // Options var options = $.extend({ class: 'sticky-footer', content: '#page', frame: this.parent() }, options); // Element var element = this; // Initialize stickyFooter(element, options); // Resize event $(window).resize(function() { stickyFooter(element, options); }); } function stickyFooter(element, options) { // Set footer height var height = $(element).outerHeight(true); // Add content height $(options.content).each(function() { height += $(this).outerHeight(true); }); // Add the sitcky footer class if the footer & content height are smaller then the frame height if(height < $(options.frame).height()) { $(element).addClass(options.class); } else { $(element).removeClass(options.class); } } })(jQuery);
Update visible_to reference to visible_to_author
from rest_framework import serializers from service.authors.serializers import SimpleAuthorSerializer from service.comments.serializers import CommentSerializer from social.app.models.post import Post class PostSerializer(serializers.HyperlinkedModelSerializer): # Not required by the spec, but makes testing a little easier url = serializers.HyperlinkedIdentityField( view_name="service:post-detail", source='id' ) author = SimpleAuthorSerializer() comments = CommentSerializer(many=True) contentType = serializers.CharField(source="content_type", read_only=True) visibleTo = serializers.HyperlinkedRelatedField( many=True, read_only=True, source="visible_to_author", view_name="service:author-detail", lookup_field="pk" ) categories = serializers.ListField( source="categories_list", read_only=True ) class Meta: model = Post fields = ("title", "source", "origin", "description", "contentType", "content", "author", "categories", "comments", "published", "id", "url", "visibility", "visibleTo", "unlisted")
from rest_framework import serializers from service.authors.serializers import SimpleAuthorSerializer from service.comments.serializers import CommentSerializer from social.app.models.post import Post class PostSerializer(serializers.HyperlinkedModelSerializer): # Not required by the spec, but makes testing a little easier url = serializers.HyperlinkedIdentityField( view_name="service:post-detail", source='id' ) author = SimpleAuthorSerializer() comments = CommentSerializer(many=True) contentType = serializers.CharField(source="content_type", read_only=True) visibleTo = serializers.HyperlinkedRelatedField( many=True, read_only=True, source="visible_to", view_name="service:author-detail", lookup_field="pk" ) categories = serializers.ListField( source="categories_list", read_only=True ) class Meta: model = Post fields = ("title", "source", "origin", "description", "contentType", "content", "author", "categories", "comments", "published", "id", "url", "visibility", "visibleTo", "unlisted")
Update album art size at Yandex.Music
controller = new BasicController({ supports: { playpause: true, next: true, previous: true, favorite: true, thumbsDown: false // Changes dynamically }, playPauseSelector: '.player-controls__btn_play', previousSelector: '.player-controls__btn_prev', nextSelector: '.player-controls__btn_next', titleSelector: '.player-controls .track__title', artistSelector: '.player-controls .track__artists', playStateSelector: '.player-controls__btn_play', playStateClass: 'player-controls__btn_pause', artworkImageSelector: '.player-controls .album-cover', favoriteSelector: '.player-controls .like', isFavoriteSelector: '.player-controls .like_on', thumbsDownSelector: '.dislike.player-controls__btn' }); controller.override('getAlbumArt', function() { var img = document.querySelector(this.artworkImageSelector); if (img) { return img.src.replace('50x50', '150x150'); } return undefined }); controller.override('isPlaying', function(_super) { this.supports.thumbsDown = window.getComputedStyle(document.querySelector(this.thumbsDownSelector)).display != 'none' return _super() });
controller = new BasicController({ supports: { playpause: true, next: true, previous: true, favorite: true, thumbsDown: false // Changes dynamically }, playPauseSelector: '.player-controls__btn_play', previousSelector: '.player-controls__btn_prev', nextSelector: '.player-controls__btn_next', titleSelector: '.player-controls .track__title', artistSelector: '.player-controls .track__artists', playStateSelector: '.player-controls__btn_play', playStateClass: 'player-controls__btn_pause', artworkImageSelector: '.player-controls .album-cover', favoriteSelector: '.player-controls .like', isFavoriteSelector: '.player-controls .like_on', thumbsDownSelector: '.dislike.player-controls__btn' }); controller.override('getAlbumArt', function() { var img = document.querySelector(this.artworkImageSelector); if (img) { return img.src.replace('40x40', '150x150'); } return undefined }); controller.override('isPlaying', function(_super) { this.supports.thumbsDown = window.getComputedStyle(document.querySelector(this.thumbsDownSelector)).display != 'none' return _super() });
Add method for changing fonts
// ==UserScript== // @name Kurahen Premium // @namespace karachan.org // @version 1.0 // @include http://www.karachan.org/* // @include http://karachan.org/* // @exclude http://www.karachan.org/*/src/* // @exclude http://karachan.org/*/src/* // ==/UserScript== (function () { 'use strict'; var KurahenPremium = function () { }; KurahenPremium.prototype.changeBoardTitle = function (newTitle) { document.title = newTitle; document.getElementsByClassName('boardTitle')[0].innerHTML = newTitle; }; KurahenPremium.prototype.setCookie = function (name, value) { document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; path=/; max-age=2592000'; }; KurahenPremium.prototype.changeFonts = function () { var newLink = document.createElement('link'); newLink.href = '//fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,latin-ext'; newLink.rel = 'stylesheet'; var existingLink = document.getElementsByTagName('link')[0]; existingLink.parentNode.insertBefore(newLink, existingLink); document.body.style.fontFamily = 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif'; }; })();
// ==UserScript== // @name Kurahen Premium // @namespace karachan.org // @version 1.0 // @include http://www.karachan.org/* // @include http://karachan.org/* // @exclude http://www.karachan.org/*/src/* // @exclude http://karachan.org/*/src/* // ==/UserScript== (function () { 'use strict'; var KurahenPremium = function () { }; KurahenPremium.prototype.changeBoardTitle = function (newTitle) { document.title = newTitle; document.getElementsByClassName('boardTitle')[0].innerHTML = newTitle; }; KurahenPremium.prototype.setCookie = function (name, value) { document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; path=/; max-age=2592000'; }; })();
Revert "Fix for not setting Gofig global/user dirs" This reverts commit d04023572e47e5c18fa549fe7f7de301e8470c63.
package core import ( "github.com/akutz/gofig" ) func init() { initDrivers() gofig.Register(globalRegistration()) gofig.Register(driverRegistration()) } func globalRegistration() *gofig.Registration { r := gofig.NewRegistration("Global") r.Yaml(` rexray: host: tcp://:7979 logLevel: warn `) r.Key(gofig.String, "h", "tcp://:7979", "The REX-Ray host", "rexray.host") r.Key(gofig.String, "l", "warn", "The log level (error, warn, info, debug)", "rexray.logLevel") return r } func driverRegistration() *gofig.Registration { r := gofig.NewRegistration("Driver") r.Yaml(` rexray: osDrivers: - linux storageDrivers: - libstorage volumeDrivers: - docker `) r.Key(gofig.String, "", "linux", "The OS drivers to consider", "rexray.osDrivers") r.Key(gofig.String, "", "", "The storage drivers to consider", "rexray.storageDrivers") r.Key(gofig.String, "", "docker", "The volume drivers to consider", "rexray.volumeDrivers") return r }
package core import ( "fmt" "github.com/akutz/gofig" "github.com/emccode/rexray/util" ) func init() { initDrivers() gofig.SetGlobalConfigPath(util.EtcDirPath()) gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", util.HomeDir())) gofig.Register(globalRegistration()) gofig.Register(driverRegistration()) } func globalRegistration() *gofig.Registration { r := gofig.NewRegistration("Global") r.Yaml(` rexray: host: tcp://:7979 logLevel: warn `) r.Key(gofig.String, "h", "tcp://:7979", "The REX-Ray host", "rexray.host") r.Key(gofig.String, "l", "warn", "The log level (error, warn, info, debug)", "rexray.logLevel") return r } func driverRegistration() *gofig.Registration { r := gofig.NewRegistration("Driver") r.Yaml(` rexray: osDrivers: - linux storageDrivers: - libstorage volumeDrivers: - docker `) r.Key(gofig.String, "", "linux", "The OS drivers to consider", "rexray.osDrivers") r.Key(gofig.String, "", "", "The storage drivers to consider", "rexray.storageDrivers") r.Key(gofig.String, "", "docker", "The volume drivers to consider", "rexray.volumeDrivers") return r }
Add a requirement for serving the assets in all tests
import os import subprocess from unittest import TestCase import re from app import generate_profiles class TestGenerateProfiles(TestCase): gen = generate_profiles.GenerateProfiles network_environment = "%s/misc/network-environment" % gen.bootcfg_path @classmethod def setUpClass(cls): subprocess.check_output(["make", "-C", cls.gen.project_path]) cls.gen = generate_profiles.GenerateProfiles() if os.path.isfile("%s" % cls.network_environment): os.remove("%s" % cls.network_environment) @classmethod def tearDownClass(cls): if os.path.isfile("%s" % cls.network_environment): os.remove("%s" % cls.network_environment) def test_00_ip_address(self): self.assertFalse(os.path.isfile("%s" % self.network_environment)) ip = self.gen.ip_address match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip) self.assertIsNotNone(match) self.assertTrue(os.path.isfile("%s" % self.network_environment))
import os from unittest import TestCase import re from app import generate_profiles class TestGenerateProfiles(TestCase): gen = generate_profiles.GenerateProfiles network_environment = "%s/misc/network-environment" % gen.bootcfg_path @classmethod def setUpClass(cls): cls.gen = generate_profiles.GenerateProfiles() if os.path.isfile("%s" % cls.network_environment): os.remove("%s" % cls.network_environment) @classmethod def tearDownClass(cls): if os.path.isfile("%s" % cls.network_environment): os.remove("%s" % cls.network_environment) def test_00_ip_address(self): self.assertFalse(os.path.isfile("%s" % self.network_environment)) ip = self.gen.ip_address match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip) self.assertIsNotNone(match) self.assertTrue(os.path.isfile("%s" % self.network_environment))
Test more upto 11 instances for the positive tests.
package test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import javax.script.ScriptException; import org.clafer.ast.AstModel; import org.clafer.collection.Triple; import org.clafer.compiler.ClaferCompiler; import org.clafer.compiler.ClaferSolver; import org.clafer.javascript.Javascript; import org.clafer.objective.Objective; import org.clafer.scope.Scope; import static org.junit.Assert.*; import org.junit.Test; /** * * @author jimmy */ public class PositiveTest { @Test public void testPositives() throws IOException, ScriptException, URISyntaxException { File dir = new File(PositiveTest.class.getResource("/positive").toURI()); assertTrue(dir.isDirectory()); for (File test : dir.listFiles()) { Triple<AstModel, Scope, Objective[]> p = Javascript.readModel(test); ClaferSolver s = ClaferCompiler.compile(p.getFst(), p.getSnd()); assertTrue(test + " failed", s.find()); for (int i = 0; i < 10 && s.find(); i++) { } } } }
package test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import javax.script.ScriptException; import org.clafer.ast.AstModel; import org.clafer.collection.Triple; import org.clafer.compiler.ClaferCompiler; import org.clafer.compiler.ClaferSolver; import org.clafer.javascript.Javascript; import org.clafer.objective.Objective; import org.clafer.scope.Scope; import static org.junit.Assert.*; import org.junit.Test; /** * * @author jimmy */ public class PositiveTest { @Test public void testPositives() throws IOException, ScriptException, URISyntaxException { File dir = new File(PositiveTest.class.getResource("/positive").toURI()); assertTrue(dir.isDirectory()); for (File test : dir.listFiles()) { Triple<AstModel, Scope, Objective[]> p = Javascript.readModel(test); ClaferSolver s = ClaferCompiler.compile(p.getFst(), p.getSnd()); assertTrue(test + " failed", s.find()); } } }
Fix failing mock of cache backend
# -*- coding: utf-8 -*- import unittest from thumbnails.backends import generate_filename, get_thumbnail from thumbnails.conf import settings from thumbnails.images import SourceFile, Thumbnail from .compat import mock class BackendTestCase(unittest.TestCase): def test_generate_filename(self): self.assertEqual( generate_filename(SourceFile('url'), '100x200', 'center', None), ['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b'] ) self.assertEqual( generate_filename(SourceFile('url'), '200x200', 'center', None), ['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad'] ) @mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True) def test_get_thumbnail_cached(self): self.assertTrue(get_thumbnail('', '200')) @mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail') def test_get_thumbnail(self, mock_engine_get_thumbnail): thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200') self.assertTrue(mock_engine_get_thumbnail.called) self.assertTrue(isinstance(thumbnail, Thumbnail))
# -*- coding: utf-8 -*- import unittest from thumbnails.backends import generate_filename, get_thumbnail from thumbnails.images import SourceFile, Thumbnail from .compat import mock class BackendTestCase(unittest.TestCase): def test_generate_filename(self): self.assertEqual( generate_filename(SourceFile('url'), '100x200', 'center', None), ['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b'] ) self.assertEqual( generate_filename(SourceFile('url'), '200x200', 'center', None), ['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad'] ) @mock.patch('thumbnails.backends.cache_get', lambda x: True) def test_get_thumbnail_cached(self): self.assertTrue(get_thumbnail('', '200')) @mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail') def test_get_thumbnail(self, mock_engine_get_thumbnail): thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200') self.assertTrue(mock_engine_get_thumbnail.called) self.assertTrue(isinstance(thumbnail, Thumbnail))
Use const keyword to declare variables
const dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { const type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, dataviewDefinition.options, dataviewDefinition.sql); } };
var dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { var type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, dataviewDefinition.options, dataviewDefinition.sql); } };
Replace process.stdin getter on IISNode
/* ================================================ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β• ========== Server Initialization =============== */ // IISNode doesn't have a functional process.stdin // Replace it so things dont complain if(process.env.IISNODE_VERSION){ process.__defineGetter__('stdin', function(){}); } // This project uses TypeScript // We compile at runtime require('typescript-require')({ nodeLib: false, targetES5: true, exitOnError: true }); // Make sure we dont have any old pre-compiled scripts // Rimraf is essentially rm -rf require("rimraf").sync("./tmp/"); // This script is the node entry point // But everything cool happens in firefly.ts require("./firefly.ts");
/* ================================================ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β• ========== Server Initialization =============== */ process.stdin = function(){}; // This project uses TypeScript // We compile at runtime require('typescript-require')({ nodeLib: false, targetES5: true, exitOnError: true }); // Make sure we dont have any old pre-compiled scripts // Rimraf is essentially rm -rf require("rimraf").sync("./tmp/"); // This script is the node entry point // But everything cool happens in firefly.ts require("./firefly.ts");
Install sun java when using cloudera
from kokki import * env.include_recipe("java.jre") apt_list_path = '/etc/apt/sources.list.d/cloudera.list' apt = ( "deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n" "deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n" ).format(distro=env.system.lsb['codename']) Execute("apt-get update", action="nothing") Execute("curl -s http://archive.cloudera.com/debian/archive.key | sudo apt-key add -", not_if = "(apt-key list | grep Cloudera > /dev/null)") File(apt_list_path, owner = "root", group ="root", mode = 0644, content = apt, notifies = [("run", env.resources["Execute"]["apt-get update"], True)])
from kokki import * apt_list_path = '/etc/apt/sources.list.d/cloudera.list' apt = ( "deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n" "deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n" ).format(distro=env.system.lsb['codename']) Execute("apt-get update", action="nothing") Execute("curl -s http://archive.cloudera.com/debian/archive.key | sudo apt-key add -", not_if = "(apt-key list | grep Cloudera > /dev/null)") File(apt_list_path, owner = "root", group ="root", mode = 0644, content = apt, notifies = [("run", env.resources["Execute"]["apt-get update"], True)])
Set the hashing rounds low to speed up tests
<?php namespace Tests; use Cake\Chronos\Chronos; use Illuminate\Support\Facades\Hash; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; /** * Setup tests. */ public function setUp() { parent::setUp(); Hash::setRounds(4); $this->setKnownUuidFactory(); } /** * Tear down tests. */ protected function tearDown() { parent::tearDown(); Chronos::setTestNow(); } /** * Handles the known UUID handling in certain unit tests. Use the "KnownUuid" trait * in order to enable this ability. */ public function setKnownUuidFactory() { // do nothing } }
<?php namespace Tests; use Cake\Chronos\Chronos; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; /** * Setup tests. */ public function setUp() { parent::setUp(); $this->setKnownUuidFactory(); } /** * Tear down tests. */ protected function tearDown() { parent::tearDown(); Chronos::setTestNow(); } /** * Handles the known UUID handling in certain unit tests. Use the "KnownUuid" trait * in order to enable this ability. */ public function setKnownUuidFactory() { // do nothing } }
Fix issue with time import
package main import ( "github.com/robfig/cron" "github.com/spf13/viper" "github.com/markbao/redditdaily/redditdaily" "fmt" ) func main() { viper.SetConfigType("yaml") viper.SetConfigName("config") viper.AddConfigPath("../") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } c := cron.New(); error := c.AddFunc(fmt.Sprintf("0 %v %v * * *", viper.GetInt("cron_min"), viper.GetInt("cron_hour")), redditdaily.Run) if error != nil { fmt.Println(error) } c.Start(); fmt.Println("Cron started.") select{} }
package main import ( "github.com/robfig/cron" "github.com/spf13/viper" "github.com/markbao/redditdaily/redditdaily" "fmt" "time" ) func main() { viper.SetConfigType("yaml") viper.SetConfigName("config") viper.AddConfigPath("../") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } c := cron.New(); error := c.AddFunc(fmt.Sprintf("0 %v %v * * *", viper.GetInt("cron_min"), viper.GetInt("cron_hour")), redditdaily.Run) if error != nil { fmt.Println(error) } c.Start(); fmt.Println("Cron started.") select{} }
BLD: Fix format string for Python-2.6
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{0}.c".format(s) for s in sources], depends=(["src/{0}.template.c".format(s) for s in source_templates] + ["src/{0}.template.h".format(s) for s in header_templates] + ["src/{0}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') sources = ["_pywt", "common", "convolution", "wavelets", "wt"] source_templates = ["convolution", "wt"] headers = ["templating", "wavelets_coeffs"] header_templates = ["convolution", "wt", "wavelets_coeffs"] # add main PyWavelets module config.add_extension( '_pywt', sources=["src/{}.c".format(s) for s in sources], depends=(["src/{}.template.c".format(s) for s in source_templates] + ["src/{}.template.h".format(s) for s in header_templates] + ["src/{}.h".format(s) for s in headers]), include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Revert "Revert "fixed pen styling bug"" This reverts commit d262982255df13839daae4fec30accd9617ed157.
package application.Actions; import javafx.geometry.Point2D; import application.SLogoCanvas; import application.Turtle; public class ForwardAction extends AbstractAction { public ForwardAction(double distance) { myValue = distance; } @Override public void update(Turtle turtle, SLogoCanvas canvas) { Point2D previousLocation = turtle.getLocation(); double remainder = myValue; while (remainder > 0) { //I PROMISE I WILL COME UP WITH A BETTER SOLUTION //BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING //PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH if (turtle.getPen().isDashed() && remainder >= 30) { canvas.displayLine(turtle.move(30)); remainder -= 30; } else if (turtle.getPen().isDotted() && remainder >= 5) { canvas.displayLine(turtle.move(5)); remainder -= 5; } else { canvas.displayLine(turtle.move(1)); remainder -= 1; } } // System.out.println("***Prior Location: " + prevLoc); // System.out.println("***Prior Location: " + turt.getLocation()); } @Override public String toString() { return "fwd " + myValue; } }
package application.Actions; import javafx.geometry.Point2D; import application.SLogoCanvas; import application.Turtle; public class ForwardAction extends AbstractAction { public ForwardAction(double distance) { myValue = distance; } @Override public void update(Turtle turtle, SLogoCanvas canvas) { Point2D previousLocation = turtle.getLocation(); double remainder = myValue; while (remainder > 0) { //I PROMISE I WILL COME UP WITH A BETTER SOLUTION //BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING //PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH if (turtle.getPen().isDashed() && myValue > 30) { canvas.displayLine(turtle.move(30)); remainder -= 20; } else if (turtle.getPen().isDotted() && myValue > 5) { canvas.displayLine(turtle.move(5)); remainder -= 5; } else { canvas.displayLine(turtle.move(1)); remainder -= 1; } } // System.out.println("***Prior Location: " + prevLoc); // System.out.println("***Prior Location: " + turt.getLocation()); } @Override public String toString() { return "fwd " + myValue; } }
Set charset to utf8 on mysql
package store import ( "fmt" "github.com/Sirupsen/logrus" "github.com/solderapp/solder/config" ) // Load initializes the database connection. func Load(cfg *config.Config) *Store { driver := cfg.Database.Driver connect := "" switch driver { case "mysql": connect = fmt.Sprintf( "%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local", cfg.Database.Username, cfg.Database.Password, cfg.Database.Host, cfg.Database.Name, ) case "postgres": connect = fmt.Sprintf( "postgres://%s:%s@%s/%s?sslmode=disable", cfg.Database.Username, cfg.Database.Password, cfg.Database.Host, cfg.Database.Name, ) case "sqlite": connect = cfg.Database.Name default: logrus.Fatal("Unknown database driver selected") } logrus.Infof("using database driver %s", driver) logrus.Infof("using database config %s", connect) return New( driver, connect, ) }
package store import ( "fmt" "github.com/Sirupsen/logrus" "github.com/solderapp/solder/config" ) // Load initializes the database connection. func Load(cfg *config.Config) *Store { driver := cfg.Database.Driver connect := "" switch driver { case "mysql": connect = fmt.Sprintf( "%s:%s@(%s)/%s?parseTime=True&loc=Local", cfg.Database.Username, cfg.Database.Password, cfg.Database.Host, cfg.Database.Name, ) case "postgres": connect = fmt.Sprintf( "postgres://%s:%s@%s/%s?sslmode=disable", cfg.Database.Username, cfg.Database.Password, cfg.Database.Host, cfg.Database.Name, ) case "sqlite": connect = cfg.Database.Name default: logrus.Fatal("Unknown database driver selected") } logrus.Infof("using database driver %s", driver) logrus.Infof("using database config %s", connect) return New( driver, connect, ) }
Change theme color to green and blue
/* eslint-disable no-underscore-dangle */ import { SheetsRegistry } from 'jss'; import { createMuiTheme, createGenerateClassName } from 'material-ui/styles'; import green from 'material-ui/colors/green'; import blue from 'material-ui/colors/blue'; // A theme with custom primary and secondary color. // It's optional. const theme = createMuiTheme({ palette: { primary: { light: green[500], main: green[800], dark: green[900], }, secondary: { light: blue[300], main: blue[500], dark: blue[700], }, }, }); function createPageContext() { return { theme, // This is needed in order to deduplicate the injection of CSS in the page. sheetsManager: new Map(), // This is needed in order to inject the critical CSS. sheetsRegistry: new SheetsRegistry(), // The standard class name generator. generateClassName: createGenerateClassName(), }; } export default function getPageContext() { // Make sure to create a new context for every server-side request so that data // isn't shared between connections (which would be bad). if (!process.browser) { return createPageContext(); } // Reuse context on the client-side. if (!global.__INIT_MATERIAL_UI__) { global.__INIT_MATERIAL_UI__ = createPageContext(); } return global.__INIT_MATERIAL_UI__; }
/* eslint-disable no-underscore-dangle */ import { SheetsRegistry } from 'jss'; import { createMuiTheme, createGenerateClassName } from 'material-ui/styles'; import purple from 'material-ui/colors/purple'; import green from 'material-ui/colors/green'; // A theme with custom primary and secondary color. // It's optional. const theme = createMuiTheme({ palette: { primary: { light: purple[300], main: purple[500], dark: purple[700], }, secondary: { light: green[300], main: green[500], dark: green[700], }, }, }); function createPageContext() { return { theme, // This is needed in order to deduplicate the injection of CSS in the page. sheetsManager: new Map(), // This is needed in order to inject the critical CSS. sheetsRegistry: new SheetsRegistry(), // The standard class name generator. generateClassName: createGenerateClassName(), }; } export default function getPageContext() { // Make sure to create a new context for every server-side request so that data // isn't shared between connections (which would be bad). if (!process.browser) { return createPageContext(); } // Reuse context on the client-side. if (!global.__INIT_MATERIAL_UI__) { global.__INIT_MATERIAL_UI__ = createPageContext(); } return global.__INIT_MATERIAL_UI__; }
Use pyscss instead of libsass, as it should be able to be successfully installed on our managed servers.
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='hybridize', version='0.1', packages=['hybridize'], include_package_data=True, install_requires = [ 'setuptools', 'django', 'django-compressor', 'django_mobileesp', 'pyscss', ], license='Apache License, Version 2.0', # example license description='Django plugin that allows apps to be consumed in native-hybrid mobile apps.', long_description=README, url='http://www.example.com/', author='Your Name', author_email='yourname@example.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='hybridize', version='0.1', packages=['hybridize'], include_package_data=True, install_requires = [ 'setuptools', 'django', 'django-compressor', 'django_mobileesp', 'libsass', ], license='Apache License, Version 2.0', # example license description='Django plugin that allows apps to be consumed in native-hybrid mobile apps.', long_description=README, url='http://www.example.com/', author='Your Name', author_email='yourname@example.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Make it clear that you should never access this._private_data directly.
var _ = require('underscore'); var deepSet = function (obj, pathString, value) { var path = pathString.split('.'); var len = path.length; for (var i = 0; i < len; i++) { if (i == len - 1) { obj[path[i]] = value; } else { if (!_.has(obj, path[i])) { obj[path[i]] = {}; } obj = obj[path[i]]; } } }; var deepUnset = function (obj, pathString) { var path = pathString.split('.'); var len = path.length; for (var i = 0; i < len; i++) { if (i == len - 1) { delete obj[path[i]]; } else { if (!_.has(obj, path[i])) { break; } obj = obj[path[i]]; } } }; var DataManager = function (joist) { this._private_data = {}; }; DataManager.prototype.patch = function (set, unset) { var that = this; _.each(set, function (value, key) { deepSet(that._private_data, key, value); }); _.each(unset, function (key) { deepUnset(that._private_data, key); }); return this.getData(); }; DataManager.prototype.getData = function () { return JSON.parse(JSON.stringify(this._private_data)); }; module.exports = DataManager;
var _ = require('underscore'); var deepSet = function (obj, pathString, value) { var path = pathString.split('.'); var len = path.length; for (var i = 0; i < len; i++) { if (i == len - 1) { obj[path[i]] = value; } else { if (!_.has(obj, path[i])) { obj[path[i]] = {}; } obj = obj[path[i]]; } } }; var deepUnset = function (obj, pathString) { var path = pathString.split('.'); var len = path.length; for (var i = 0; i < len; i++) { if (i == len - 1) { delete obj[path[i]]; } else { if (!_.has(obj, path[i])) { break; } obj = obj[path[i]]; } } }; var DataManager = function (joist) { this.data = {}; }; DataManager.prototype.patch = function (set, unset) { var that = this; _.each(set, function (value, key) { deepSet(that.data, key, value); }); _.each(unset, function (key) { deepUnset(that.data, key); }); return this.data; }; DataManager.prototype.getData = function () { return JSON.parse(JSON.stringify(this.data)); }; module.exports = DataManager;
Remove resolver intercept cache basename logic And replace with basic stripping of leading ./ and trailing .sol
function ResolverIntercept(resolver) { this.resolver = resolver; this.cache = {}; } ResolverIntercept.prototype.require = function(import_path) { // Modify import_path so the cache key is deterministic // Remove preceding `./` and `.sol` extension import_path = import_path.replace(/^\.\\/, "").replace(/\.sol$/i, ""); // TODO: Using the import path for relative files may result in multiple // paths for the same file. This could return different objects since it won't be a cache hit. if (this.cache[import_path]) { return this.cache[import_path]; } // Note, will error if nothing is found. var resolved = this.resolver.require(import_path); this.cache[import_path] = resolved; // During migrations, we could be on a network that takes a long time to accept // transactions (i.e., contract deployment close to block size). Because successful // migration is more important than wait time in those cases, we'll synchronize "forever". resolved.synchronization_timeout = 0; return resolved; }; ResolverIntercept.prototype.contracts = function() { var self = this; return Object.keys(this.cache).map(function(key) { return self.cache[key]; }); }; module.exports = ResolverIntercept;
const path = require("path"); function ResolverIntercept(resolver) { this.resolver = resolver; this.cache = {}; }; ResolverIntercept.prototype.require = function(import_path) { // Modify import_path so the cache key is consistently based only on the contract name. // This works because Truffle already prevents more than one contract with the same name. // Ref: https://github.com/trufflesuite/truffle/issues/1087 import_path = path.basename(import_path).replace(/\.sol$/i, ''); // TODO: Using the import path for relative files may result in multiple // paths for the same file. This could return different objects since it won't be a cache hit. if (this.cache[import_path]) { return this.cache[import_path]; } // Note, will error if nothing is found. var resolved = this.resolver.require(import_path); this.cache[import_path] = resolved; // During migrations, we could be on a network that takes a long time to accept // transactions (i.e., contract deployment close to block size). Because successful // migration is more important than wait time in those cases, we'll synchronize "forever". resolved.synchronization_timeout = 0; return resolved; }; ResolverIntercept.prototype.contracts = function() { var self = this; return Object.keys(this.cache).map(function(key) { return self.cache[key]; }); }; module.exports = ResolverIntercept;
Fix the website tutorial build to escape <=.
var path = require('path'); var fs = require('fs-extra'); var pug = require('pug'); var buildUtils = require('../examples/build-utils'); // generate the tutorials fs.ensureDirSync('website/source/tutorials'); var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source')); tutorials.map(function (json) { var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8'); pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug'); var fn = pug.compile(pugTemplate, { pretty: false, filename: path.relative('.', path.resolve(json.dir, 'index.pug')) }); var html = fn(json); html = html.replace(/<=/g, '&lt;=').replace(/>=/g, '&gt;='); html = `--- layout: tutorial title: ${json.title} about: ${json.about.text} tutorialCss: ${JSON.stringify(json.tutorialCss)} tutorialJs: ${JSON.stringify(json.tutorialJs)} --- ` + html; fs.writeFileSync(path.resolve(json.output, 'index.html'), html); }); // copy common files fs.copySync('tutorials/common', 'website/source/tutorials/common'); buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
var path = require('path'); var fs = require('fs-extra'); var pug = require('pug'); var buildUtils = require('../examples/build-utils'); // generate the tutorials fs.ensureDirSync('website/source/tutorials'); var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source')); tutorials.map(function (json) { var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8'); pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug'); var fn = pug.compile(pugTemplate, { pretty: false, filename: path.relative('.', path.resolve(json.dir, 'index.pug')) }); var html = fn(json); html = `--- layout: tutorial title: ${json.title} about: ${json.about.text} tutorialCss: ${JSON.stringify(json.tutorialCss)} tutorialJs: ${JSON.stringify(json.tutorialJs)} --- ` + html; fs.writeFileSync(path.resolve(json.output, 'index.html'), html); }); // copy common files fs.copySync('tutorials/common', 'website/source/tutorials/common'); buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
Update blueprint to current versions.
var EOL = require('os').EOL; module.exports = { name: 'ember-cli-mocha', normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { var addonContext = this; return this.addBowerPackagesToProject([ { name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.8' }, { name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.2.2' }, { name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.6' } ]).then(function() { if ('removePackageFromProject' in addonContext) { return addonContext.removePackageFromProject('ember-cli-qunit'); } }); } };
var EOL = require('os').EOL; module.exports = { name: 'ember-cli-mocha', normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { var addonContext = this; return this.addBowerPackagesToProject([ { name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.6' }, { name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.1.3' }, { name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.3' } ]).then(function() { if ('removePackageFromProject' in addonContext) { return addonContext.removePackageFromProject('ember-cli-qunit'); } }); } };
Remove images created by tests
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
Refactor code to use HttpKernel and a new Framework class
<?php require_once __DIR__."/../vendor/autoload.php"; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; use Symfony\Component\HttpKernel; use Scarlett; function render_template($request) { extract($request->attributes->all(), EXTR_SKIP); ob_start(); include sprintf(__DIR__."/../src/pages/%s.php", $_route); return new Response(ob_get_clean(), 200); } $request = Request::createFromGlobals(); $routes = include __DIR__."/../src/app.php"; $context = new Routing\RequestContext(); $context->fromRequest($request); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); $resolver = new HttpKernel\Controller\ControllerResolver(); $scarlett = new Scarlett\Framework($matcher, $resolver); $response = $scarlett->handle($request); $response->send();
<?php require_once __DIR__."/../vendor/autoload.php"; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; function render_template($request) { extract($request->attributes->all(), EXTR_SKIP); ob_start(); include sprintf(__DIR__."/../src/pages/%s.php", $_route); return new Response(ob_get_clean(), 200); } $request = Request::createFromGlobals(); $routes = include __DIR__."/../src/app.php"; $context = new Routing\RequestContext(); $context->fromRequest($request); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); try{ $request->attributes->add($matcher->match($request->getPathInfo())); $response = call_user_func($request->attributes->get('_controller'), $request); }catch(Routing\Exception\ResourceNotFoundException $e) { $response = new Response('Not found', 404); }catch(Exception $e){ $response = new Response($e->getMessage(), 500); } $response->send();
Add bleach as a requirement
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='django-bleach', version="0.1.0", description='Easily use bleach with Django models and templates', author='Tim Heap', author_email='heap.tim@gmail.com', url='https://bitbucket.org/ionata/django-bleach', packages=['django_bleach',], install_requires = ['bleach'], package_data={}, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='django-bleach', version="0.1.0", description='Easily use bleach with Django models and templates', author='Tim Heap', author_email='heap.tim@gmail.com', url='https://bitbucket.org/ionata/django-bleach', packages=['django_bleach',], package_data={}, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
Rewrite as sparse array class
// See Purple/license.txt for Google BSD license // Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com define(['lib/Base'], function (Base) { var SparseArray = {}; SparseArray.set = function(p_id, data) { this.objectsByP_ID[p_id] = data; this.p_ids.push(p_id); }; // maybe undefined. SparseArray.get = function(p_id) { return this.objectsByP_ID[p_id]; }; SparseArray.Iterator = Base.extend({ initialize: function(sparseArray) { this.sparseArray = sparseArray; }, next: function() { if (!this.index) { this.index = this.sparseArray.p_ids.length; } this.index--; if (this.index < 0) { return undefined; } else { var p_id = this.p_ids[this.index]; return this.sparseArray.objectsByP_ID[p_id]; } } }); SparseArray.initialize = function(name) { this.name = name; this.objectsByP_ID = {}; this.p_ids = []; }; return Base.extend(SparseArray); });
// See Purple/license.txt for Google BSD license // Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com define(['lib/Base'], function (Base) { var EventIndex = {}; EventIndex.recv = function(data) { this.objectBuffer.push(data); }; EventIndex._getMatcher = function(constraints) { return function(obj) { return true; }; }; // API EventIndex.filter = function(constraints, thenFnOfObject) { // flush any new events to the object buffer this._update(); var matcher = this._getMatcher(constraints); var max = this.objectBuffer.length; for (var i = 0; i < max; i++) { var obj = this.objectBuffer[i]; if (matcher(obj)) { if (!thenFnOfObject(obj)) break; } } }; EventIndex.initialize = function() { this.objectBuffer = []; }; EventIndex.disconnect = function() { delete this.objectBuffer; }; return Base.extend(EventIndex); });