text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Set default value for path of config
<?php namespace RMiller\PhpSpecExtension; use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface; use Behat\Testwork\ServiceContainer\ExtensionManager; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; class PhpSpecExtension implements ExtensionInterface { /** * {@inheritDoc} */ public function load(ContainerBuilder $container, array $config) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__)); $loader->load('services.xml'); $container->setParameter('phpspec_extension.path', $config['path']); $container->setParameter('phpspec_extension.config', $config['config']); } /** * {@inheritDoc} */ public function configure(ArrayNodeDefinition $builder) { $builder ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('bin/phpspec')->end() ->scalarNode('config')->defaultValue('phpspec.yml')->end() ->end() ->end(); } /** * {@inheritDoc} */ public function getConfigKey() { return 'phpspec'; } /** * {@inheritdoc} */ public function initialize(ExtensionManager $extensionManager) { } /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { } }
<?php namespace RMiller\PhpSpecExtension; use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface; use Behat\Testwork\ServiceContainer\ExtensionManager; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; class PhpSpecExtension implements ExtensionInterface { /** * {@inheritDoc} */ public function load(ContainerBuilder $container, array $config) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__)); $loader->load('services.xml'); $container->setParameter('phpspec_extension.path', $config['path']); $container->setParameter('phpspec_extension.config', $config['config']); } /** * {@inheritDoc} */ public function configure(ArrayNodeDefinition $builder) { $builder ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('bin/phpspec')->end() ->scalarNode('config')->defaultNull()->end() ->end() ->end(); } /** * {@inheritDoc} */ public function getConfigKey() { return 'phpspec'; } /** * {@inheritdoc} */ public function initialize(ExtensionManager $extensionManager) { } /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { } }
Fix an error when deleting a GitHub webhook user
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('stage')->nullable(); $table->integer('server_id')->unsigned(); $table->string('repository'); $table->string('email_notification_recipient')->nullable(); $table->text('attributes'); $table->integer('days_to_keep_deployments')->unsigned()->nullable(); $table->integer('max_number_of_deployments_to_keep')->unsigned()->nullable(); $table->tinyInteger('keep_last_deployment')->unsigned(); $table->string('github_webhook_secret')->nullable(); $table->integer('github_webhook_user_id')->unsigned()->nullable(); $table->timestamps(); $table->foreign('server_id') ->references('id') ->on('servers'); $table->foreign('github_webhook_user_id') ->references('id') ->on('users') ->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('projects'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('stage')->nullable(); $table->integer('server_id')->unsigned(); $table->string('repository'); $table->string('email_notification_recipient')->nullable(); $table->text('attributes'); $table->integer('days_to_keep_deployments')->unsigned()->nullable(); $table->integer('max_number_of_deployments_to_keep')->unsigned()->nullable(); $table->tinyInteger('keep_last_deployment')->unsigned(); $table->string('github_webhook_secret')->nullable(); $table->integer('github_webhook_user_id')->unsigned()->nullable(); $table->timestamps(); $table->foreign('server_id') ->references('id') ->on('servers'); $table->foreign('github_webhook_user_id') ->references('id') ->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('projects'); } }
Add call to show at pynotify
#!/usr/bin/env python import urllib2 import ssl # Define the sites we want to poll and the timeout. SITES = ( 'https://redmine.codegrove.org', 'http://koodilehto.fi', 'http://vakiopaine.net', ) TIMEOUT = 5 try: import gntp.notifier notification = gntp.notifier.mini except ImportError: try: import pygtk pygtk.require('2.0') import pynotify def gtk_out(data): n = pynotify.Notification( 'Koodilehto Service Error', data ) n.show() notification = gtk_out except ImportError: def out(data): print data notification = out def poll(sites, timeout, ok, error): """Checks if the given URLs are online.""" for site in sites: ok('Polling ' + site) try: response = urllib2.urlopen(site, timeout=timeout) response.read() except urllib2.URLError as e: code = str(e.code) if hasattr(e, 'code') else '' error(site + ' ' + code) except ssl.SSLError as e: error(site + ' ' + e.message) except Exception as e: error(site + ' ' + e.message) else: ok('OK') def empty(data): pass if __name__ == '__main__': poll(SITES, timeout=TIMEOUT, ok=empty, error=notification)
#!/usr/bin/env python import urllib2 import ssl # Define the sites we want to poll and the timeout. SITES = ( 'https://redmine.codegrove.org', 'http://koodilehto.fi', 'http://vakiopaine.net', ) TIMEOUT = 5 try: import gntp.notifier notification = gntp.notifier.mini except ImportError: try: import pygtk pygtk.require('2.0') import pynotify def gtk_out(data): pynotify.Notification( 'Koodilehto Service Error', data ) notification = gtk_out except ImportError: def out(data): print data notification = out def poll(sites, timeout, ok, error): """Checks if the given URLs are online.""" for site in sites: ok('Polling ' + site) try: response = urllib2.urlopen(site, timeout=timeout) response.read() except urllib2.URLError as e: code = str(e.code) if hasattr(e, 'code') else '' error(site + ' ' + code) except ssl.SSLError as e: error(site + ' ' + e.message) except Exception as e: error(site + ' ' + e.message) else: ok('OK') def empty(data): pass if __name__ == '__main__': poll(SITES, timeout=TIMEOUT, ok=empty, error=notification)
Remove double slash in filename
<?php namespace Fillet\Writer; use Symfony\Component\Yaml\Dumper as YamlDumper; /** * Generates a Post for Sculpin * * @package Fillet\Writer */ class PostWriter extends AbstractWriter { /** * Write out a set of data into a file * * @param array $data Data to use for constructing the page */ public function write($data) { $post_date_string = $data['post_date']->format('Y-m-d H:i:s'); $slug = $this->generateSlug($data['title']); $filename = $data['post_date']->format('Y-m-d') . '-' . $slug; $headerData = [ 'title' => $data['title'], 'date' => $post_date_string, 'layout' => 'post', 'slug' => $slug, 'categories' => $data['categories'], 'tags' => $data['tags'], ]; $dumper = new YamlDumper(); $header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL; $filename = $this->destinationFolder . $filename; if ($this->isMarkdownEnabled()) { $filename .= '.md'; $data['content'] = $this->toMarkdown($data['content']); } else { $filename .= '.html'; } file_put_contents($filename, $header . PHP_EOL . $data['content']); } }
<?php namespace Fillet\Writer; use Symfony\Component\Yaml\Dumper as YamlDumper; /** * Generates a Post for Sculpin * * @package Fillet\Writer */ class PostWriter extends AbstractWriter { /** * Write out a set of data into a file * * @param array $data Data to use for constructing the page */ public function write($data) { $post_date_string = $data['post_date']->format('Y-m-d H:i:s'); $slug = $this->generateSlug($data['title']); $filename = $data['post_date']->format('Y-m-d') . '-' . $slug; $headerData = [ 'title' => $data['title'], 'date' => $post_date_string, 'layout' => 'post', 'slug' => $slug, 'categories' => $data['categories'], 'tags' => $data['tags'], ]; $dumper = new YamlDumper(); $header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL; $filename = $this->destinationFolder . '/' . $filename; if ($this->isMarkdownEnabled()) { $filename .= '.md'; $data['content'] = $this->toMarkdown($data['content']); } else { $filename .= '.html'; } file_put_contents($filename, $header . PHP_EOL . $data['content']); } }
Rename the easter egg command.
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * Class is a test command class. */ public class TestCommand implements Command { private Options options; private GnuParser parser; public TestCommand(Application app) { this.parser = new GnuParser(); this.options = new Options(); options.addOption("a", false, "testikomento"); } @Override public String getDescription() { return "This is an easter egg test command."; } @Override public String getName() { return "easter-egg"; } @Override public void run(String[] args) { try { CommandLine line = this.parser.parse(options, args); if (line.hasOption("a")) { System.out.println("Let's run easter egg with -a"); } else { System.out.println("Let's run easter egg."); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } }
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * Class is a test command class. */ public class TestCommand implements Command { private Options options; private GnuParser parser; public TestCommand(Application app) { this.parser = new GnuParser(); this.options = new Options(); options.addOption("a", false, "testikomento"); } @Override public String getDescription() { return "This is an easter egg test command."; } @Override public String getName() { return "EasterEgg"; } @Override public void run(String[] args) { try { CommandLine line = this.parser.parse(options, args); if (line.hasOption("a")) { System.out.println("Let's run easter egg with -a"); } else { System.out.println("Let's run easter egg."); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } }
Make image upload work in all cases
$( document ).ready( function() { function showUploadedImage( source ) { $( "#userImage" ).attr( "src", source ); } function createImageError() { $( '#image-form' ).prepend( "<div class='alert alert-danger'>This isn't an image</div>" ) } function removeImageError() { $( '#image-form .alert.alert-danger' ).remove(); } function toggleSubmit() { $( "#imageSubmit" ).toggle(); $( "#uploading" ).toggle(); } $( "#image-form" ).submit( function() { var image = document.getElementById( "image" ).files[ 0 ]; var token = $( "input[type=hidden]" ).val(); var formdata = new FormData(); removeImageError(); if ( !image ) { createImageError(); return false; } toggleSubmit(); formdata.append( "image", image ); formdata.append( "token", token ); $.ajax( { url: "image/create", type: "POST", data: formdata, cache: false, dataType: "json", processData: false, contentType: false, success: function( res ) { var reader = new FileReader(); reader.onloadend = function ( e ) { showUploadedImage( e.target.result ); } reader.readAsDataURL( image ); toggleSubmit(); }, error: function( jqXHR, textStatus, errorThrown ) { createImageError(); $( "#imageSubmit" ).show(); $( "#uploading" ).hide(); } } ); return false; } ); } );
$( document ).ready( function() { function showUploadedImage( source ) { $( "#userImage" ).attr( "src", source ); } $( "#image-form" ).submit( function() { var image = document.getElementById( "image" ).files[ 0 ]; if ( !image ) { $( '#image-form' ).prepend( "<div class='alert alert-danger'>This isn't an image</div>" ) return false; } var token = $( "input[type=hidden]" ).val(); var formdata = new FormData(); var reader = new FileReader(); $( "#imageSubmit" ).hide(); $( "#uploading" ).show(); reader.onloadend = function ( e ) { showUploadedImage( e.target.result ); } reader.readAsDataURL( image ); formdata.append( "image", image ); formdata.append( "token", token ); $.ajax( { url: "image/create", type: "POST", data: formdata, cache: false, dataType: false, processData: false, contentType: false, success: function( res ) { $( "#imageSubmit" ).show(); $( "#uploading" ).hide(); }, error: function( res ) { $( "#imageSubmit" ).show(); $( "#uploading" ).hide(); } } ); return false; } ); } );
Change publication date to Epub; more up-to-date
import os.path import string import urllib, re from datetime import datetime from xml.dom.minidom import parse, parseString # Django from django.core import serializers from django.conf import settings from django.db import models # Methodmint def pubmed(keywords, latest_query=None): # Get matching publications from Pubmed service # We explode the keywords append [TW] for all text-search # then build a string for the datetime since last update keywordl = keywords.split(',') keywordq = '(' + '[TW] '.join(keywordl) + '[TW])' # produce[TW] this[TW] string[TW] if latest_query == None: timeq = '' else: timeq = ' AND ("%s"[Date - Epub] : "3000"[Date - Epub])' % latest_query.strftime("%Y/%m/%d") print "Querying pubmed with: %s %s" % (keywordq, timeq) f = urllib.urlopen("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=%s %s" % (keywordq, timeq)) # Build DOM for requested data dom = parse(f) f.close() uris = [] if dom: if dom.getElementsByTagName('Id'): for item in dom.getElementsByTagName('Id'): uris.append( 'pmid:%d' % int( item.childNodes[0].data ) ) uris = uris[:25] # Limit max number of subsequent requests return uris
import os.path import string import urllib, re from datetime import datetime from xml.dom.minidom import parse, parseString # Django from django.core import serializers from django.conf import settings from django.db import models # Methodmint def pubmed(keywords, latest_query=None): # Get matching publications from Pubmed service # We explode the keywords append [TW] for all text-search # then build a string for the datetime since last update keywordl = keywords.split(',') keywordq = '(' + '[TW] '.join(keywordl) + '[TW])' # produce[TW] this[TW] string[TW] if latest_query == None: timeq = '' else: timeq = ' AND ("%s"[Date - Publication] : "3000"[Date - Publication])' % latest_query.strftime("%Y/%m/%d") print "Querying pubmed with: %s %s" % (keywordq, timeq) f = urllib.urlopen("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=%s %s" % (keywordq, timeq)) # Build DOM for requested data dom = parse(f) f.close() uris = [] if dom: if dom.getElementsByTagName('Id'): for item in dom.getElementsByTagName('Id'): uris.append( 'pmid:%d' % int( item.childNodes[0].data ) ) uris = uris[:25] # Limit max number of subsequent requests return uris
Change default day to 'empty' day for testing
import {Controller} from 'ringa'; import Repository from '../Repository'; import moment from 'moment'; export default class RepositoryController extends Controller { constructor(bus) { super('RepositoryController', bus); this.repository = new Repository(); //--------------------------------- // RepositoryController.GET_TODAY //--------------------------------- this.addListener('getToday', [ ($ringaEvent) => { let day = moment('2017-04-09'); $ringaEvent.detail.today = this.repository.getDay(day.toDate()); } ]); //--------------------------------- // RepositoryController.GET_DAY //--------------------------------- this.addListener('getDay', []); //--------------------------------- // RepositoryController.GET_DAY_LIST //--------------------------------- this.addListener('getDayList', [ ($ringaEvent) => { $ringaEvent.detail.dayList = this.repository.get('Day'); } ]); //--------------------------------- // RepositoryController.TOGGLE_TASK_COMPLETED //--------------------------------- this.addListener('toggleTaskCompleted', [ (task) => { this.repository.toggleTaskCompleted(task); } ]); //--------------------------------- // RepositoryController.UPDATE_TASK_DESCRIPTION //--------------------------------- this.addListener('updateTaskDescription', [ (task, desc) => { this.repository.updateTaskDescription(task, desc); } ]); } }
import {Controller} from 'ringa'; import Repository from '../Repository'; import moment from 'moment'; export default class RepositoryController extends Controller { constructor(bus) { super('RepositoryController', bus); this.repository = new Repository(); //--------------------------------- // RepositoryController.GET_TODAY //--------------------------------- this.addListener('getToday', [ ($ringaEvent) => { let day = moment('2017-04-13'); $ringaEvent.detail.today = this.repository.getDay(day.toDate()); } ]); //--------------------------------- // RepositoryController.GET_DAY //--------------------------------- this.addListener('getDay', []); //--------------------------------- // RepositoryController.GET_DAY_LIST //--------------------------------- this.addListener('getDayList', [ ($ringaEvent) => { $ringaEvent.detail.dayList = this.repository.get('Day'); } ]); //--------------------------------- // RepositoryController.TOGGLE_TASK_COMPLETED //--------------------------------- this.addListener('toggleTaskCompleted', [ (task) => { this.repository.toggleTaskCompleted(task); } ]); //--------------------------------- // RepositoryController.UPDATE_TASK_DESCRIPTION //--------------------------------- this.addListener('updateTaskDescription', [ (task, desc) => { this.repository.updateTaskDescription(task, desc); } ]); } }
Change class name to DuplicateScripts
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateScripts(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateScripts, self).__init__() self.total_duplicate = 0 self.list_duplicate = [] def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print("%d duplicate scripts found" % self.total_duplicate) for duplicate in self.list_duplicate: print duplicate def analyze(self, scratch): """Run and return the results from the DuplicateChecks plugin.""" scripts_set = set() for script in self.iter_scripts(scratch): blocks_list = [] for name, _, _ in self.iter_blocks(script.blocks): blocks_list.append(name) blocks_tuple = tuple(blocks_list) if blocks_tuple in scripts_set: if len(blocks_list)>3: self.total_duplicate += 1 self.list_duplicate.append(blocks_list) else: scripts_set.add(blocks_tuple)
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateChecks(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateChecks, self).__init__() self.total_duplicate = 0 self.list_duplicate = [] def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print("%d duplicate scripts found" % self.total_duplicate) for duplicate in self.list_duplicate: print duplicate def analyze(self, scratch): """Run and return the results from the DuplicateChecks plugin.""" scripts_set = set() for script in self.iter_scripts(scratch): blocks_list = [] for name, _, _ in self.iter_blocks(script.blocks): blocks_list.append(name) blocks_tuple = tuple(blocks_list) if blocks_tuple in scripts_set: if len(blocks_list)>3: self.total_duplicate += 1 self.list_duplicate.append(blocks_list) else: scripts_set.add(blocks_tuple)
Fix java test case as well for method rename
import java.io.File; import org.opensim.modeling.*; class TestXsensDataReader { public static void test_XsensDataReader() { // Test creation and population of XsensDataReaderSettings object XsensDataReaderSettings settings = new XsensDataReaderSettings(); ExperimentalSensor nextSensor = new ExperimentalSensor("000_00B421AF", "shank"); settings.append_ExperimentalSensors(nextSensor); settings.set_trial_prefix(0, "MT_012005D6_031-"); // Test costruct XsensDataReader from a XsensDataReaderSettings object XsensDataReader xsensDataReader = new XsensDataReader(settings); // Make sure types returned by the xsensDataReader are usable in Java StdMapStringAbstractDataTable tables = xsensDataReader.readSource(""); // Check that custom accessors are available and return usable types // Only spot check of the table is done as actual testing of contents // lives in the C++ tests TimeSeriesTableVec3 accelTableTyped = IMUDataReader.getLinearAccelerationsTable(tables); assert accelTableTyped.getNumRows() == 3369; assert accelTableTyped.getNumColumns() == 1; assert accelTableTyped. getTableMetaDataString("DataRate").equals("100.000000"); } public static void main(String[] args) { test_XsensDataReader(); } };
import java.io.File; import org.opensim.modeling.*; class TestXsensDataReader { public static void test_XsensDataReader() { // Test creation and population of XsensDataReaderSettings object XsensDataReaderSettings settings = new XsensDataReaderSettings(); ExperimentalSensor nextSensor = new ExperimentalSensor("000_00B421AF", "shank"); settings.append_ExperimentalSensors(nextSensor); settings.set_trial_prefix(0, "MT_012005D6_031-"); // Test costruct XsensDataReader from a XsensDataReaderSettings object XsensDataReader xsensDataReader = new XsensDataReader(settings); // Make sure types returned by the xsensDataReader are usable in Java StdMapStringAbstractDataTable tables = xsensDataReader.readData(""); // Check that custom accessors are available and return usable types // Only spot check of the table is done as actual testing of contents // lives in the C++ tests TimeSeriesTableVec3 accelTableTyped = IMUDataReader.getLinearAccelerationsTable(tables); assert accelTableTyped.getNumRows() == 3369; assert accelTableTyped.getNumColumns() == 1; assert accelTableTyped. getTableMetaDataString("DataRate").equals("100.000000"); } public static void main(String[] args) { test_XsensDataReader(); } };
Add Python 3 compatibility and flake8 testing
#!/usr/bin/env python2.7 from __future__ import print_function import re, sys, markdown, requests, bs4 as BeautifulSoup try: # Python 2 reload except NameError: # Python 3 from importlib import reload reload(sys) sys.setdefaultencoding('utf8') def check_url(url): try: return bool(requests.head(url, allow_redirects=True)) except Exception as e: print('Error checking URL %s: %s' % (url, e)) return False def retrieve_urls(filename): with open(filename) as fd: mdtext = fd.read() html_text = markdown.markdown(mdtext) soup = BeautifulSoup.BeautifulSoup(html_text, "html.parser") return [a['href'] for a in soup.findAll('a')] def check_urls(filename): print('checking URLs for %s' % filename) ok = True for url in retrieve_urls(filename): r = "(?:http[s]?://[^)]+)" u = re.findall(r, url) if not u: continue msg = 'Checking %s => ' % (u[0],) if check_url(u[0]): print(msg, 'OK') else: print(msg, 'FAILED') ok = False return ok def main(): ok = True for filename in sys.argv[1:]: try: ok &= check_urls(filename) except IOError as e: print(e) ok = False exit(0 if ok else 1) if __name__ == '__main__': main()
#!/usr/bin/env python2.7 import re, sys, markdown, requests, bs4 as BeautifulSoup reload(sys) sys.setdefaultencoding('utf8') def check_url(url): try: return bool(requests.head(url, allow_redirects=True)) except Exception as e: print 'Error checking URL %s: %s' % (url, e) return False def retrieve_urls(filename): with open(filename) as fd: mdtext = fd.read() html_text = markdown.markdown(mdtext) soup = BeautifulSoup.BeautifulSoup(html_text, "html.parser") return [a['href'] for a in soup.findAll('a')] def check_urls(filename): print 'checking URLs for %s' % (filename,) ok = True for url in retrieve_urls(filename): r = "(?:http[s]?://[^)]+)" u = re.findall(r, url) if not u: continue msg = 'Checking %s => ' % (u[0],) if check_url(u[0]): print msg, 'OK' else: print msg, 'FAILED' ok = False return ok def main(): ok = True for filename in sys.argv[1:]: try: ok &= check_urls(filename) except IOError as e: print e ok = False exit (0 if ok else 1) if __name__ == '__main__': main()
Remove the requests dependency altogether. (Makes no sense for such small a tool.)
from functools import partial import subprocess import urllib2 import multiprocessing import json def get_pkg_info(pkg_name): req = urllib2.Request('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) handler = urllib2.urlopen(req) status = handler.getcode() if status == 200: content = handler.read() return json.loads(content) else: raise ValueError('Package %r not found on PyPI.' % (pkg_name,)) def latest_version(pkg_name, silent=False): try: info = get_pkg_info(pkg_name) except ValueError: if silent: return None else: raise return info['info']['version'] def get_latest_versions(pkg_names): pool = multiprocessing.Pool(min(12, len(pkg_names))) get_latest = partial(latest_version, silent=True) versions = pool.map(get_latest, pkg_names) return zip(pkg_names, versions) def get_installed_pkgs(editables=False): for line in subprocess.check_output(['pip', 'freeze']).split('\n'): if not line: continue if line.startswith('-e'): if editables: yield line.split('#egg=', 1)[1], None, True else: name, version = line.split('==') yield name, version, False
from functools import partial import subprocess import requests import multiprocessing import json def get_pkg_info(pkg_name, session): r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,)) if r.status_code == requests.codes.ok: return json.loads(r.text) else: raise ValueError('Package %r not found on PyPI.' % (pkg_name,)) def latest_version(pkg_name, session, silent=False): try: info = get_pkg_info(pkg_name, session) except ValueError: if silent: return None else: raise return info['info']['version'] def get_latest_versions(pkg_names): with requests.session() as session: pool = multiprocessing.Pool(min(12, len(pkg_names))) get_latest = partial(latest_version, session=session, silent=True) versions = pool.map(get_latest, pkg_names) return zip(pkg_names, versions) def get_installed_pkgs(editables=False): for line in subprocess.check_output(['pip', 'freeze']).split('\n'): if not line: continue if line.startswith('-e'): if editables: yield line.split('#egg=', 1)[1], None, True else: name, version = line.split('==') yield name, version, False
fix: Add meta content for preventing double tab
import React from 'react' import PropTypes from 'prop-types' export default class HTML extends React.Component { render() { return ( <html {...this.props.htmlAttributes}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, minimum-scale=1, maximum-scale=1, user-scalable=0, viewport-fit=cover" /> {this.props.headComponents} </head> <body {...this.props.bodyAttributes}> {this.props.preBodyComponents} <noscript>You need to enable JavaScript to run this app.</noscript> <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ) } } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, }
import React from 'react' import PropTypes from 'prop-types' export default class HTML extends React.Component { render() { return ( <html {...this.props.htmlAttributes}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, minimum-scale=1, maximum-scale=2" /> {this.props.headComponents} </head> <body {...this.props.bodyAttributes}> {this.props.preBodyComponents} <noscript>You need to enable JavaScript to run this app.</noscript> <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: this.props.body }} /> {this.props.postBodyComponents} </body> </html> ) } } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, }
Correct logging level for messages.
#!/usr/bin/env python from chunk import Chunk import logging import struct class Parser(object): ChunkAliasMap = {} def __init__(self, kind): self._kind = kind self._chunks = [] def loadFile(self, filename): with open(filename) as iff: chunk = Chunk(iff) logging.info('Reading file "%s"' % filename) if chunk.getname() == 'FORM' and chunk.read(4) == self._kind: iff.seek(12) while True: try: chunk = Chunk(iff) except EOFError: break name = chunk.getname() size = chunk.getsize() data = chunk.read() logging.debug('Encountered %s chunk of size %d' % (name, size)) self._chunks.append(self._parseChunk(name, data)) else: logging.error('File %s is not of IFF/%s type.' % (filename, self._kind)) return False return True def _parseChunk(self, name, data): orig_name = name for alias, names in self.ChunkAliasMap.items(): if name in names: name = alias handler = getattr(self, 'handle%s' % name, None) if handler: data = handler(data) else: logging.warning('No handler for %s chunk.' % orig_name) return (orig_name, data)
#!/usr/bin/env python from chunk import Chunk import logging import struct class Parser(object): ChunkAliasMap = {} def __init__(self, kind): self._kind = kind self._chunks = [] def loadFile(self, filename): with open(filename) as iff: chunk = Chunk(iff) logging.error('Reading file "%s"' % filename) if chunk.getname() == 'FORM' and chunk.read(4) == self._kind: iff.seek(12) while True: try: chunk = Chunk(iff) except EOFError: break name = chunk.getname() size = chunk.getsize() data = chunk.read() logging.info('Encountered %s chunk of size %d' % (name, size)) self._chunks.append(self._parseChunk(name, data)) else: logging.error('File %s is not of IFF/%s type.' % (filename, self._kind)) return False return True def _parseChunk(self, name, data): orig_name = name for alias, names in self.ChunkAliasMap.items(): if name in names: name = alias handler = getattr(self, 'handle%s' % name, None) if handler: data = handler(data) else: logging.warning('No handler for %s chunk.' % orig_name) return (orig_name, data)
Fix error when toggling slot selection
import * as Utils from '../../utils' export const updateSlotSelectionStateInWorkspace = (state, payload) => { const { elementId, slotId, type } = payload const selectedSlots = Utils.selectedSlots(state) let slotSelectionState = { } // Toggle state, only select slot if it is not already selected if(!Utils.isSlotSelected(selectedSlots, slotId)) { slotSelectionState = { elementId, slotId } } return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, pipe: { ...state.selectionState.pipe, [type]: slotSelectionState } } }) } export const removeSlotSelectionState = (state) => { return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, pipe: { input: { }, output: { } } } }) } export const addSelectedElementToWorkspace = (state, payload) => { const { elementId, mousePosition } = payload return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, element: { id: elementId, mousePosition } } }) } export const removeSelectedElementFromWorkspace = (state) => { return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, element: { } } }) }
import * as Utils from '../../utils' export const updateSlotSelectionStateInWorkspace = (state, payload) => { const { elementId, slotId, type } = payload const selectedSlots = Utils.selectedSlots(state) let slotSelectionState = null // Toggle state, only select slot if it is not already selected if(!Utils.isSlotSelected(selectedSlots, slotId)) { slotSelectionState = { elementId, slotId } } return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, pipe: { ...state.selectionState.pipe, [type]: slotSelectionState } } }) } export const removeSlotSelectionState = (state) => { return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, pipe: { input: { }, output: { } } } }) } export const addSelectedElementToWorkspace = (state, payload) => { const { elementId, mousePosition } = payload return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, element: { id: elementId, mousePosition } } }) } export const removeSelectedElementFromWorkspace = (state) => { return Object.assign({}, state, { ...state, selectionState: { ...state.selectionState, element: { } } }) }
Indent and deindent selected block of text - gemo style
jQuery(function($) { /* tab handling - gemo style */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; var selected = this.value.slice(start, end); if (e.shiftKey) { // deindent var replacement = selected.replace(/^\t/gm, ''); } else { // indent var replacement = selected.replace(/^/gm, '\t'); } this.value = this.value.slice(0, start) + replacement + this.value.slice(end); this.setSelectionRange(start, end + replacement.length - selected.length ); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
jQuery(function($) { /* tab insertion handling */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; this.value = this.value.slice(0, start) + '\t' + this.value.slice(end); this.setSelectionRange(start + 1, start + 1); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
Support python 3.7, 3.8, 3.9, 3.10
#-*- coding: utf-8 -*- from setuptools import setup, find_packages import YaDiskClient setup( name='YaDiskClient', version=YaDiskClient.__version__, include_package_data=True, py_modules=['YaDiskClient'], url='https://github.com/TyVik/YaDiskClient', license='MIT', author='TyVik', author_email='[email protected]', description='Clent for Yandex.Disk', long_description=open('README.rst').read(), install_requires=['requests'], packages=find_packages(), keywords='Yandex.Disk, webdav, client, python, Yandex', # test_suite='YaDiskClient.test_YaDiskClient' # this line is commented because tests needs Yandex login and password classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Utilities', 'Topic :: System :: Archiving :: Backup', ], )
#-*- coding: utf-8 -*- from setuptools import setup, find_packages import YaDiskClient setup( name='YaDiskClient', version=YaDiskClient.__version__, include_package_data=True, py_modules=['YaDiskClient'], url='https://github.com/TyVik/YaDiskClient', license='MIT', author='TyVik', author_email='[email protected]', description='Clent for Yandex.Disk', long_description=open('README.rst').read(), install_requires=['requests'], packages=find_packages(), keywords='Yandex.Disk, webdav, client, python, Yandex', # test_suite='YaDiskClient.test_YaDiskClient' # this line is commented because tests needs Yandex login and password classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Utilities', 'Topic :: System :: Archiving :: Backup', ], )
Add console log to debug message and sender
import config from '../../index'; import express from 'express'; import request from 'request'; class WebhookService { constructor () {}; static tokenVerify (req, res) { if (!req.query['hub.verify_token'] === config.FACEBOOK_PAGE_ACCESS_TOKEN) { return res.send('Error, wrong token'); } return res.send(req.query['hub.challenge']); } static messageEvent (req, res) { let messagingEvents = req.body.entry[0].messaging; console.log(req.body) messagingEvents.map(messagingEvent => { let message = messagingEvent.message.text; let sender = messagingEvent.sender.id; console.log('Destinatário: ', sender, 'Mensagem: ', message) WebhookService.textMessage(sender, message); }) res.sendStatus(200); } static textMessage (sender, text) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: config.FACEBOOK_PAGE_ACCESS_TOKEN }, method: 'POST', json: { recipient: { id: sender }, message: { text: text }, } }, (error, response, body) => { if (error) { console.log('Error sending messages: ', error) return; } if (response.body.error) { console.log('Error: ', response.body.error) return; } }) } } export default WebhookService;
import config from '../../index'; import express from 'express'; import request from 'request'; class WebhookService { constructor () {}; static tokenVerify (req, res) { if (req.query['hub.verify_token'] !== config.FACEBOOK_PAGE_ACCESS_TOKEN) { return res.send('Error, wrong token'); } return res.send(req.query['hub.challenge']); } static messageEvent (req, res) { let messagingEvents = req.body.entry[0].messaging; console.log(req.body) messagingEvents.map(messagingEvent => { let message = messagingEvent.message.text; let sender = messagingEvent.sender.id; WebhookService.textMessage(sender, message.substring(0, 200)); }) res.sendStatus(200); } static textMessage (sender, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: config.FACEBOOK_PAGE_ACCESS_TOKEN }, method: 'POST', json: { recipient: { id: sender }, message: { text: message }, } }, (error, response, body) => { if (error) { console.log('Error sending messages: ', error) return; } if (response.body.error) { console.log('Error: ', response.body.error) return; } }) } } export default WebhookService;
Revert "api key deleted from the list of required parameters"
package org.atlasapi.application.auth; import static com.google.common.base.Preconditions.checkNotNull; import javax.servlet.http.HttpServletRequest; import org.atlasapi.application.Application; import org.atlasapi.application.ApplicationSources; import org.atlasapi.application.ApplicationStore; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher { public static final String API_KEY_QUERY_PARAMETER = "key"; private final ApplicationStore reader; public ApiKeySourcesFetcher(ApplicationStore reader) { this.reader = checkNotNull(reader); } @Override public ImmutableSet<String> getParameterNames() { return ImmutableSet.of(API_KEY_QUERY_PARAMETER); } @Override public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException { String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER); if (apiKey == null) { apiKey = request.getHeader(API_KEY_QUERY_PARAMETER); } if (apiKey != null) { Optional<Application> app = reader.applicationForKey(apiKey); if (!app.isPresent() || app.get().isRevoked()) { throw new InvalidApiKeyException(apiKey); } return Optional.of(app.get().getSources()); } return Optional.absent(); } }
package org.atlasapi.application.auth; import static com.google.common.base.Preconditions.checkNotNull; import javax.servlet.http.HttpServletRequest; import org.atlasapi.application.Application; import org.atlasapi.application.ApplicationSources; import org.atlasapi.application.ApplicationStore; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher { public static final String API_KEY_QUERY_PARAMETER = "key"; private final ApplicationStore reader; public ApiKeySourcesFetcher(ApplicationStore reader) { this.reader = checkNotNull(reader); } @Override public ImmutableSet<String> getParameterNames() { return ImmutableSet.of(); } @Override public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException { String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER); if (apiKey == null) { apiKey = request.getHeader(API_KEY_QUERY_PARAMETER); } if (apiKey != null) { Optional<Application> app = reader.applicationForKey(apiKey); if (!app.isPresent() || app.get().isRevoked()) { throw new InvalidApiKeyException(apiKey); } return Optional.of(app.get().getSources()); } return Optional.absent(); } }
Access proptypes via prop-types packages instead of React in LimitSelect component
/** * * LimitSelect * */ import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { map } from 'lodash'; import styles from './styles.scss'; class LimitSelect extends React.Component { componentWillMount() { const id = _.uniqueId(); this.setState({ id }); } /** * Return the list of default values to populate the select options * * @returns {number[]} */ getOptionsValues() { return [10, 20, 50, 100]; } render() { return ( <form className="form-inline"> <div className={styles.selectWrapper}> <select onChange={this.props.handleChange} className={`form-control ${styles.select}`} id={this.state.id} value={this.props.limit} > {map(this.getOptionsValues(), (optionValue, key) => <option value={optionValue} key={key}>{optionValue}</option>)} </select> </div> <label className={styles.label} htmlFor={this.state.id}> <FormattedMessage id="content-manager.components.LimitSelect.itemsPerPage" /> </label> </form> ); } } LimitSelect.propTypes = { handleChange: PropTypes.func.isRequired, limit: PropTypes.number.isRequired, }; export default LimitSelect;
/** * * LimitSelect * */ import React from 'react'; // import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { map } from 'lodash'; import styles from './styles.scss'; class LimitSelect extends React.Component { componentWillMount() { const id = _.uniqueId(); this.setState({ id }); } /** * Return the list of default values to populate the select options * * @returns {number[]} */ getOptionsValues() { return [10, 20, 50, 100]; } render() { return ( <form className="form-inline"> <div className={styles.selectWrapper}> <select onChange={this.props.handleChange} className={`form-control ${styles.select}`} id={this.state.id} value={this.props.limit} > {map(this.getOptionsValues(), (optionValue, key) => <option value={optionValue} key={key}>{optionValue}</option>)} </select> </div> <label className={styles.label} htmlFor={this.state.id}> <FormattedMessage id="content-manager.components.LimitSelect.itemsPerPage" /> </label> </form> ); } } LimitSelect.propTypes = { handleChange: PropTypes.func.isRequired, limit: PropTypes.number.isRequired, }; export default LimitSelect;
MetaCPAN: Move MetaCPAN to group 'base'.
(function(env) { env.ddg_spice_meta_cpan = function(api_result) { "use strict"; if (!(api_result && api_result.author && api_result.version)) { return Spice.failed('meta_cpan'); } var query = DDG.get_query().replace(/\s*(metacpan|meta cpan|cpanm?)\s*/i, '').replace(/-/g, '::'); var link = "search?q=" + encodeURIComponent(query); if (api_result.module && api_result.module.length > 0 && api_result.module[0].associated_pod) { link = "module/" + api_result.module[0].associated_pod; } Spice.add({ id: "meta_cpan", name: "MetaCPAN", data: api_result, meta: { sourceName: "MetaCPAN", sourceUrl: 'https://metacpan.org/' + link }, templates: { group: 'base', options: { content: 'record', moreAt: true } }, normalize: function(item){ return{ record_keys: ['abstract','author','version','description'] }; } }); } }(this));
(function(env) { env.ddg_spice_meta_cpan = function(api_result) { "use strict"; if (!(api_result && api_result.author && api_result.version)) { return Spice.failed('meta_cpan'); } var query = DDG.get_query().replace(/\s*(metacpan|meta cpan|cpanm?)\s*/i, '').replace(/-/g, '::'); var link = "search?q=" + encodeURIComponent(query); if (api_result.module && api_result.module.length > 0 && api_result.module[0].associated_pod) { link = "module/" + api_result.module[0].associated_pod; } Spice.add({ id: "meta_cpan", name: "MetaCPAN", data: api_result, meta: { sourceName: "MetaCPAN", sourceUrl: 'https://metacpan.org/' + link }, templates: { group: 'info', options: { content: 'record' } }, normalize: function(item){ return{ record_keys: ['abstract','author','version','description'] }; } }); } }(this));
Fix the webpack putting files into dist/ by mistake
require('dotenv').config(); const path = require('path'); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: "bundle.js", path: path.resolve(__dirname, "./public/js/"), publicPath: "/js/" }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] };
require('dotenv').config(); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: './public/js/bundle.js' }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] };
Add Metalsmith plugins to list of ignored unused packages Add metalsmith-* to list of packages ignored when checking unused
'use strict'; const depcheck = require('depcheck'); const ora = require('ora'); function skipUnused(currentState) { return currentState.get('skipUnused') || // manual option to ignore this currentState.get('global') || // global modules currentState.get('update') || // in the process of doing an update !currentState.get('cwdPackageJson').name; // there's no package.json } function checkUnused(currentState) { const spinner = ora(`Checking for unused packages. --skip-unused if you don't want this.`); spinner.enabled = currentState.get('spinner'); spinner.start(); return new Promise(resolve => { if (skipUnused(currentState)) { resolve(currentState); } const depCheckOptions = { ignoreDirs: [ 'sandbox', 'dist', 'generated', '.generated', 'build', 'fixtures' ], ignoreMatches: [ 'gulp-*', 'grunt-*', 'karma-*', 'angular-*', 'babel-*', 'metalsmith-*', 'grunt' ] }; depcheck(currentState.get('cwd'), depCheckOptions, resolve); }).then(depCheckResults => { spinner.stop(); const unusedDependencies = [].concat(depCheckResults.dependencies, depCheckResults.devDependencies); currentState.set('unusedDependencies', unusedDependencies); return currentState; }); } module.exports = checkUnused;
'use strict'; const depcheck = require('depcheck'); const ora = require('ora'); function skipUnused(currentState) { return currentState.get('skipUnused') || // manual option to ignore this currentState.get('global') || // global modules currentState.get('update') || // in the process of doing an update !currentState.get('cwdPackageJson').name; // there's no package.json } function checkUnused(currentState) { const spinner = ora(`Checking for unused packages. --skip-unused if you don't want this.`); spinner.enabled = currentState.get('spinner'); spinner.start(); return new Promise(resolve => { if (skipUnused(currentState)) { resolve(currentState); } const depCheckOptions = { ignoreDirs: [ 'sandbox', 'dist', 'generated', '.generated', 'build', 'fixtures' ], ignoreMatches: [ 'gulp-*', 'grunt-*', 'karma-*', 'angular-*', 'babel-*', 'grunt' ] }; depcheck(currentState.get('cwd'), depCheckOptions, resolve); }).then(depCheckResults => { spinner.stop(); const unusedDependencies = [].concat(depCheckResults.dependencies, depCheckResults.devDependencies); currentState.set('unusedDependencies', unusedDependencies); return currentState; }); } module.exports = checkUnused;
FIX stock transfer restrict lot when lost is reserved
from openerp import models, fields, api, _ from openerp.exceptions import UserError class StockPackOperation(models.Model): _inherit = 'stock.pack.operation' code = fields.Selection( related='picking_id.picking_type_id.code', string='Operation Type', readonly=True) @api.one @api.constrains('pack_lot_ids') def validate_quantity(self): if self.code != 'incoming' and self.pack_lot_ids: for pack in self.pack_lot_ids: quants = self.env['stock.quant'].search( [('id', 'in', pack.lot_id.quant_ids.ids), ('location_id', '=', self.location_id.id), '|', ('reservation_id', '=', False), ('reservation_id.picking_id', '=', self. picking_id.id)]) if quants: qty = sum([x.qty for x in quants]) else: qty = 0.0 if qty < pack.qty: raise UserError( _('Sending amount can not exceed the quantity in\ stock for this product in this lot. \ \n Product:%s \ \n Lot:%s \ \n Stock:%s') % (pack.lot_id.product_id. name, pack.lot_id.name, qty))
from openerp import models, fields, api, _ from openerp.exceptions import UserError class StockPackOperation(models.Model): _inherit = 'stock.pack.operation' code = fields.Selection( related='picking_id.picking_type_id.code', string='Operation Type', readonly=True) @api.one @api.constrains('pack_lot_ids') def validate_quantity(self): if self.code != 'incoming' and self.pack_lot_ids: for pack in self.pack_lot_ids: quants = self.env['stock.quant'].search( [('id', 'in', pack.lot_id.quant_ids.ids), ('location_id', '=', self.location_id.id)]) if quants: qty = sum([x.qty for x in quants]) else: qty = 0.0 if qty < pack.qty: raise UserError( _('Sending amount can not exceed the quantity in\ stock for this product in this lot. \ \n Product:%s \ \n Lot:%s \ \n Stock:%s') % (pack.lot_id.product_id. name, pack.lot_id.name, qty))
Use Type[ET] as enum passed to init is a Type
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any, Type # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField",) ET = TypeVar("ET", Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """ data_type_name = "Enum" def __init__(self, enum, **options): # type: (Type[ET], **Any) -> None # Generate choices structure from choices choices = options.pop("choices", None) options["choices"] = tuple((e, e.name) for e in choices or enum) super(EnumField, self).__init__(**options) self.enum = enum @property def choices_doc_text(self): """ Choices converted for documentation purposes. """ return tuple((v.value, n) for v, n in self.choices) def to_python(self, value): # type: (Any) -> Optional[ET] if value is None: return # Attempt to convert try: return self.enum(value) except ValueError: # If value is an empty string return None # Do this check here to support enums that define an option using # an empty string. if value is "": return raise ValidationError(self.error_messages["invalid_choice"] % value) def prepare(self, value): # type: (Optional[ET]) -> Any if value in self.enum: return value.value
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField", ) ET = TypeVar('ET', Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """ data_type_name = "Enum" def __init__(self, enum, **options): # type: (ET, **Any) -> None # Generate choices structure from choices choices = options.pop("choices", None) options["choices"] = tuple((e, e.name) for e in choices or enum) super(EnumField, self).__init__(**options) self.enum = enum @property def choices_doc_text(self): """ Choices converted for documentation purposes. """ return tuple((v.value, n) for v, n in self.choices) def to_python(self, value): # type: (Any) -> Optional[ET] if value is None: return # Attempt to convert try: return self.enum(value) except ValueError: # If value is an empty string return None # Do this check here to support enums that define an option using # an empty string. if value is "": return raise ValidationError(self.error_messages['invalid_choice'] % value) def prepare(self, value): # type: (Optional[ET]) -> Any if value in self.enum: return value.value
Remove method declared in parent.
<?php namespace Rogue\Types; class ActionType extends Type { private const HOST_EVENT = 'host-event'; private const HAVE_CONVERSATION = 'have-a-conversation'; private const DONATE_SOMETHING = 'donate-something'; private const MAKE_SOMETHING = 'make-something'; private const SHARE_SOMETHING = 'share-something'; private const FLAG_CONTENT = 'flag-content'; private const SUBMIT_TIP = 'submit-tip'; private const DISTRIBUTE_CONTENT = 'distribute-content'; private const ATTEND_EVENT = 'attend-event'; private const SIGN_PETITION = 'sign-petition'; private const CONTACT_DECISIONMAKER = 'contact-decisionmaker'; /** * Returns labeled list of values. * * @return array */ public static function labels() { return [ self::HOST_EVENT => 'Host an Event', self::HAVE_CONVERSATION => 'Have a Conversation', self::DONATE_SOMETHING => 'Donate Something', self::MAKE_SOMETHING => 'Make Something', self::SHARE_SOMETHING => 'Share Something (Online)', self::FLAG_CONTENT => 'Flag Content', self::SUBMIT_TIP => 'Submit Tips & Opinions', self::DISTRIBUTE_CONTENT => 'Distribute Content (IRL)', self::ATTEND_EVENT => 'Attend an Event', self::SIGN_PETITION => 'Sign a Petition', self::CONTACT_DECISIONMAKER => 'Contact a Decision-Maker', ]; } }
<?php namespace Rogue\Types; class ActionType extends Type { private const HOST_EVENT = 'host-event'; private const HAVE_CONVERSATION = 'have-a-conversation'; private const DONATE_SOMETHING = 'donate-something'; private const MAKE_SOMETHING = 'make-something'; private const SHARE_SOMETHING = 'share-something'; private const FLAG_CONTENT = 'flag-content'; private const SUBMIT_TIP = 'submit-tip'; private const DISTRIBUTE_CONTENT = 'distribute-content'; private const ATTEND_EVENT = 'attend-event'; private const SIGN_PETITION = 'sign-petition'; private const CONTACT_DECISIONMAKER = 'contact-decisionmaker'; /** * Returns labeled list of values. * * @return array */ public static function labels() { return [ self::HOST_EVENT => 'Host an Event', self::HAVE_CONVERSATION => 'Have a Conversation', self::DONATE_SOMETHING => 'Donate Something', self::MAKE_SOMETHING => 'Make Something', self::SHARE_SOMETHING => 'Share Something (Online)', self::FLAG_CONTENT => 'Flag Content', self::SUBMIT_TIP => 'Submit Tips & Opinions', self::DISTRIBUTE_CONTENT => 'Distribute Content (IRL)', self::ATTEND_EVENT => 'Attend an Event', self::SIGN_PETITION => 'Sign a Petition', self::CONTACT_DECISIONMAKER => 'Contact a Decision-Maker', ]; } public static function label($type) { return array_get(self::labels(), $type); } }
Update key shortcut for new signature
$(document).ready(function() { $(document).keyup(function(e) { var tag = e.target.tagName.toLowerCase(); if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) { if (e.keyCode==78 || e.keyCode==77) { $('.nav-menu-icon').trigger('click'); } else if (e.keyCode==65) { $('.search-menu-icon').trigger('click'); } else if (e.keyCode==73 && e.shiftKey) { $( "#new-ip" ).click(); } else if (e.keyCode==73) { $( "#new-indicator" ).click(); } else if (e.keyCode==69 && e.shiftKey) { $( "#new-event" ).click(); } else if (e.keyCode==69) { $( "#new-email-yaml" ).click(); } else if (e.keyCode==68) { $( "#new-domain" ).click(); } else if (e.keyCode==80) { $( "#new-pcap" ).click(); } else if (e.keyCode==83 && e.shiftKey) { $( "#new-signature" ).click(); } else if (e.keyCode==83) { $( "#new-sample" ).click(); } else if (e.keyCode==27) { $( ".mm-opened").trigger('close'); } else if (e.shiftKey && e.keyCode==191) { $( "#shortcut-keys").click(); } } }); });
$(document).ready(function() { $(document).keyup(function(e) { var tag = e.target.tagName.toLowerCase(); if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) { if (e.keyCode==78 || e.keyCode==77) { $('.nav-menu-icon').trigger('click'); } else if (e.keyCode==65) { $('.search-menu-icon').trigger('click'); } else if (e.keyCode==73 && e.shiftKey) { $( "#new-ip" ).click(); } else if (e.keyCode==73) { $( "#new-indicator" ).click(); } else if (e.keyCode==69 && e.shiftKey) { $( "#new-event" ).click(); } else if (e.keyCode==69) { $( "#new-email-yaml" ).click(); } else if (e.keyCode==68) { $( "#new-domain" ).click(); } else if (e.keyCode==80) { $( "#new-pcap" ).click(); } else if (e.keyCode==83) { $( "#new-sample" ).click(); } else if (e.keyCode==83) { $( "#new-signature" ).click(); } else if (e.keyCode==27) { $( ".mm-opened").trigger('close'); } else if (e.shiftKey && e.keyCode==191) { $( "#shortcut-keys").click(); } } }); });
Fix handling of create_sample command on dev API endpoint This was completely broken.
from logging import getLogger from virtool.api.response import no_content from virtool.fake.wrapper import FakerWrapper from virtool.http.routes import Routes from virtool.samples.fake import create_fake_sample from virtool.subtractions.fake import create_fake_fasta_upload, create_fake_finalized_subtraction from virtool.utils import random_alphanumeric logger = getLogger(__name__) routes = Routes() faker = FakerWrapper() @routes.post("/api/dev") async def dev(req): data = await req.json() user_id = req["client"].user_id command = data.get("command") if command == "clear_users": await req.app["db"].users.delete_many({}) await req.app["db"].sessions.delete_many({}) await req.app["db"].keys.delete_many({}) logger.debug("Cleared users") if command == "create_subtraction": upload_id, upload_name = await create_fake_fasta_upload( req.app, req["client"].user_id ) await create_fake_finalized_subtraction( req.app, upload_id, upload_name, random_alphanumeric(8), user_id ) if command == "create_sample": await create_fake_sample( req.app, random_alphanumeric(8), req["client"].user_id, False, True ) return no_content()
from logging import getLogger from virtool.api.response import no_content from virtool.fake.wrapper import FakerWrapper from virtool.http.routes import Routes from virtool.samples.fake import create_fake_samples from virtool.subtractions.fake import create_fake_fasta_upload, create_fake_finalized_subtraction from virtool.utils import random_alphanumeric logger = getLogger(__name__) routes = Routes() faker = FakerWrapper() @routes.post("/api/dev") async def dev(req): data = await req.json() user_id = req["client"].user_id command = data.get("command") if command == "clear_users": await req.app["db"].users.delete_many({}) await req.app["db"].sessions.delete_many({}) await req.app["db"].keys.delete_many({}) logger.debug("Cleared users") if command == "create_subtraction": upload_id, upload_name = await create_fake_fasta_upload( req.app, req["client"].user_id ) await create_fake_finalized_subtraction( req.app, upload_id, upload_name, random_alphanumeric(8), user_id ) if command == "create_sample": await create_fake_samples(req.app) return no_content()
Fix gruntfile.js default build task.
/// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' /> /* This file in the main entry point for defining grunt tasks and using grunt plugins. Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409 */ module.exports = function (grunt) { grunt.initConfig({ bower: { install: { options: { targetDir: "wwwroot/lib", layout: "byComponent", cleanTargetDir: true } } }, concat: { js: { src: "Assets/js/*.js", dest: "wwwroot/js/site.js" }, css: { src: "Assets/css/*.css", dest: "wwwroot/css/site.css" } }, }); grunt.registerTask("default", ["bower:install"]); grunt.loadNpmTasks("grunt-bower-task"); grunt.loadNpmTasks("grunt-contrib-concat"); };
/// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' /> /* This file in the main entry point for defining grunt tasks and using grunt plugins. Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409 */ module.exports = function (grunt) { grunt.initConfig({ bower: { install: { options: { targetDir: "wwwroot/lib", layout: "byComponent", cleanTargetDir: true } } }, concat: { js: { src: "Assets/js/*.js", dest: "wwwroot/js/site.js" }, css: { src: "Assets/css/*.css", dest: "wwwroot/css/site.css" } }, }); grunt.registerTask("default", ["bower:install concat"]); grunt.loadNpmTasks("grunt-bower-task"); grunt.loadNpmTasks("grunt-contrib-concat"); };
Fix bug in the ascii bar graph
__author__="UShareSoft" def print_graph(values): max=0 for v in values: if len(v)>max: max=len(v) for v in values: value = int(values[v]) if len(v)<max: newV=v+(" " * int(max-len(v))) if value!=-1: print newV, value*'|'+'-'*int(50-value) else: print newV,20*'-'+"UNLIMITED"+21*'-' else: if value!=-1: print v, value*'|'+'-'*int(50-value) else: print v,20*'-'+"UNLIMITED"+21*'-'
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. __author__="UShareSoft" def print_graph(values): max=0 for v in values: if len(v)>max: max=len(v) for v in values: if len(v)<max: newV=v+(" " * int(max-len(v))) if values[v]!=-1: print newV, values[v]*'|'+'-'*int(50-values[v]) else: print newV,20*'-'+"UNLIMITED"+21*'-' else: if values[v]!=-1: print v, values[v]*'|'+'-'*int(50-values[v]) else: print v,20*'-'+"UNLIMITED"+21*'-'
Fix the Monasca Log API tempest tests The Tempest Manager class must have changed and the service argument apparently no longer exists. Instead, it was being set as the scope which caused the catalog to not be retrieved See-also: If934bac4e2cd833fe4e381c373218383354969ec Change-Id: I43c023e91eb93e2c19096b0de812eabf7b2db62c
# Copyright 2015-2016 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from monasca_log_api_tempest.services import log_api_v2_client from monasca_log_api_tempest.services import log_api_v3_client from monasca_log_api_tempest.services import log_search_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.log_api_clients = { "v2": log_api_v2_client.LogApiV2Client( self.auth_provider, 'logs_v2', None ), "v3": log_api_v3_client.LogApiV3Client( self.auth_provider, 'logs', None ) } self.log_search_client = log_search_client.LogsSearchClient( self.auth_provider, 'logs-search', None )
# Copyright 2015 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from monasca_log_api_tempest.services import log_api_v2_client from monasca_log_api_tempest.services import log_api_v3_client from monasca_log_api_tempest.services import log_search_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.log_api_clients = { "v2": log_api_v2_client.LogApiV2Client( self.auth_provider, 'logs_v2', None ), "v3": log_api_v3_client.LogApiV3Client( self.auth_provider, 'logs', None ) } self.log_search_client = log_search_client.LogsSearchClient( self.auth_provider, 'logs-search', None )
Use 'text' input on non-touch devices Auditors: eater, cbhl
(function(Perseus) { var InputInteger = Perseus.Widget.extend({ initialize: function() { if (window.Modernizr && Modernizr.touch) { this.$input = $("<input type='number'>"); } else { this.$input = $("<input type='text'>"); } }, render: function() { this.$el.empty(); this.$el.append(this.$input); return $.when(this); }, focus: function() { this.$input.focus(); }, toJSON: function() { return { value: this.$input.val() }; }, set: function(options) { this.$input.val(options.value); }, simpleValidate: function(rubric) { return InputInteger.validate(this.toJSON(), rubric); } }); _.extend(InputInteger, { validate: function(state, rubric) { // For now, rubric is just like {value: "17"} // TODO(alpert): Smarter checking if (state.value === "") { return { type: "invalid", message: null }; } else if (state.value === rubric.value) { return { type: "points", earned: 1, total: 1, message: null }; } else { return { type: "points", earned: 0, total: 1, message: "Consider writing in the right answer, silly." }; } } }); // TODO(alpert): Editor Perseus.Widgets.register("input-integer", InputInteger); })(Perseus);
(function(Perseus) { var InputInteger = Perseus.Widget.extend({ initialize: function() { this.$input = $("<input type='number'>"); }, render: function() { this.$el.empty(); this.$el.append(this.$input); return $.when(this); }, focus: function() { this.$input.focus(); }, toJSON: function() { return { value: this.$input.val() }; }, set: function(options) { this.$input.val(options.value); }, simpleValidate: function(rubric) { return InputInteger.validate(this.toJSON(), rubric); } }); _.extend(InputInteger, { validate: function(state, rubric) { // For now, rubric is just like {value: "17"} // TODO(alpert): Smarter checking if (state.value === "") { return { type: "invalid", message: null }; } else if (state.value === rubric.value) { return { type: "points", earned: 1, total: 1, message: null }; } else { return { type: "points", earned: 0, total: 1, message: "Consider writing in the right answer, silly." }; } } }); // TODO(alpert): Editor Perseus.Widgets.register("input-integer", InputInteger); })(Perseus);
Clean up order of imports
#!/usr/bin/env python import os import sys import hashlib import hmac # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secret), payload, hashlib.sha1) computed_signature = '='.join(['sha1', computed_hash.hexdigest()]) return hmac.compare_digest(computed_signature, str(signature)) def lambda_handler(event, context): print 'Webhook received' verified = verify_signature(event['secret'], event['x_hub_signature'], event['payload']) print 'Signature verified: ' + str(verified) if verified: response = requests.post(event['jenkins_url'], headers={ 'Content-Type': 'application/json', 'X-GitHub-Delivery': event['x_github_delivery'], 'X-GitHub-Event': event['x_github_event'], 'X-Hub-Signature': event['x_hub_signature'] }, data=event['payload']) response.raise_for_status() else: raise requests.HTTPError('400 Client Error: Bad Request') if __name__ == "__main__": pass
#!/usr/bin/env python import os import sys import hashlib # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA import hmac # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secret), payload, hashlib.sha1) computed_signature = '='.join(['sha1', computed_hash.hexdigest()]) return hmac.compare_digest(computed_signature, str(signature)) def lambda_handler(event, context): print 'Webhook received' verified = verify_signature(event['secret'], event['x_hub_signature'], event['payload']) print 'Signature verified: ' + str(verified) if verified: response = requests.post(event['jenkins_url'], headers={ 'Content-Type': 'application/json', 'X-GitHub-Delivery': event['x_github_delivery'], 'X-GitHub-Event': event['x_github_event'], 'X-Hub-Signature': event['x_hub_signature'] }, data=event['payload']) response.raise_for_status() else: raise requests.HTTPError('400 Client Error: Bad Request') if __name__ == "__main__": pass
Fix a missed details -> field switchover
"use strict"; var m = require("mithril"), id = require("./id"), hide = require("./hide"), label = require("./label"), css = require("./types.css"); module.exports = function(args, view) { return { controller : function(options) { var ctrl = this; ctrl.id = id(options); // Decorate children w/ their selection status ctrl.selected = function(opts) { var field = opts.field, values = opts.data, matches; if(!values) { return; } matches = field.children.filter(function(opt) { if(!args.multiple) { return opt.value === values; } return values[opt.key] === opt.value; }); if(!args.multiple && matches.length) { matches.length = 1; } field.children = field.children.map(function(opt) { opt.selected = matches.indexOf(opt) > -1; return opt; }); }; ctrl.value = function(opts, key, value) { return opts.update( args.multiple ? opts.path.concat(key) : opts.path, value ); }; }, view : function(ctrl, options) { var hidden = hide(options); if(hidden) { return hidden; } ctrl.selected(options); return m("div", { class : options.class }, label(ctrl, options), view(ctrl, options) ); } }; };
"use strict"; var m = require("mithril"), id = require("./id"), hide = require("./hide"), label = require("./label"), css = require("./types.css"); module.exports = function(args, view) { return { controller : function(options) { var ctrl = this; ctrl.id = id(options); // Decorate children w/ their selection status ctrl.selected = function(opts) { var details = opts.details, values = opts.data, matches; if(!values) { return; } matches = details.children.filter(function(opt) { if(!args.multiple) { return opt.value === values; } return values[opt.key] === opt.value; }); if(!args.multiple && matches.length) { matches.length = 1; } details.children = details.children.map(function(opt) { opt.selected = matches.indexOf(opt) > -1; return opt; }); }; ctrl.value = function(opts, key, value) { return opts.update( args.multiple ? opts.path.concat(key) : opts.path, value ); }; }, view : function(ctrl, options) { var hidden = hide(options); if(hidden) { return hidden; } ctrl.selected(options); return m("div", { class : options.class }, label(ctrl, options), view(ctrl, options) ); } }; };
Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None.
from __future__ import with_statement import sys import threado import threading import Queue class ThreadPool(object): def __init__(self, idle_time=5.0): self.lock = threading.Lock() self.threads = list() self.idle_time = idle_time def run(self, func, *args, **keys): with self.lock: if self.threads: thread, queue = self.threads.pop() else: queue = Queue.Queue() thread = threading.Thread(target=self._thread, args=(queue,)) thread.setDaemon(True) channel = threado.Channel() queue.put((channel, func, args, keys)) if not thread.isAlive(): thread.start() return channel def _thread(self, queue): item = threading.currentThread(), queue while True: try: task = queue.get(True, self.idle_time) except Queue.Empty: with self.lock: if item not in self.threads: continue self.threads.remove(item) return if task is None: return channel, func, args, keys = task try: result = func(*args, **keys) except: self.threads.append(item) channel.rethrow() else: self.threads.append(item) channel.finish(result) thread_pool = ThreadPool() run = thread_pool.run
from __future__ import with_statement import threado import threading import Queue class ThreadPool(object): def __init__(self, idle_time=5.0): self.lock = threading.Lock() self.threads = list() self.idle_time = idle_time @threado.stream def run(inner, self, func, *args, **keys): with self.lock: if self.threads: thread, queue = self.threads.pop() else: queue = Queue.Queue() thread = threading.Thread(target=self._thread, args=(queue,)) thread.setDaemon(True) channel = threado.Channel() queue.put((channel, func, args, keys)) if not thread.isAlive(): thread.start() result = yield channel inner.finish(result) def _thread(self, queue): item = threading.currentThread(), queue while True: try: task = queue.get(True, self.idle_time) except Queue.Empty: with self.lock: if item not in self.threads: continue self.threads.remove(item) return if task is None: return channel, func, args, keys = task try: result = func(*args, **keys) except: self.threads.append(item) channel.rethrow() else: self.threads.append(item) channel.finish(result) thread_pool = ThreadPool() run = thread_pool.run
Add command to publish js file
<?php namespace Bsharp\Laralytics; use Illuminate\Translation\TranslationServiceProvider; /** * Class LaralyticsServiceProvider * @package Bsharp\Laralytics */ class LaralyticsServiceProvider extends TranslationServiceProvider { protected $defer = false; public function boot() { // Include Laralytics routes for API include __DIR__ . '/../publish/routes.php'; /** * Register publish config */ $this->publishes([ __DIR__ . '/../publish/config/laralytics.php' => config_path('laralytics.php') ], 'config'); /** * Register publish migrations */ $this->publishes([ __DIR__ . '/../publish/database/migrations/' => database_path('/migrations') ], 'migrations'); /** * register publish middleware */ $this->publishes([ __DIR__ . '/../publish/Http/Middleware/' => app_path('/Http/Middleware') ], 'middleware'); /** * register publish Eloquent model */ $this->publishes([ __DIR__ . '/../publish/Eloquent/' => app_path() ], 'eloquent'); /** * Register public js file */ $this->publishes([ __DIR__ . '/../publish/public/' => public_path('js') ], 'js'); } public function register() { $this->app->bind('laralytics', function () { return new Laralytics(); }); } }
<?php namespace Bsharp\Laralytics; use Illuminate\Translation\TranslationServiceProvider; /** * Class LaralyticsServiceProvider * @package Bsharp\Laralytics */ class LaralyticsServiceProvider extends TranslationServiceProvider { protected $defer = false; public function boot() { // Include Laralytics routes for API include __DIR__ . '/../publish/routes.php'; /** * Register publish config */ $this->publishes([ __DIR__ . '/../publish/config/laralytics.php' => config_path('laralytics.php') ], 'config'); /** * Register publish migrations */ $this->publishes([ __DIR__ . '/../publish/database/migrations/' => database_path('/migrations') ], 'migrations'); /** * register publish middleware */ $this->publishes([ __DIR__ . '/../publish/Http/Middleware/' => app_path('/Http/Middleware') ], 'middleware'); /** * register publish Eloquent model */ $this->publishes([ __DIR__ . '/../publish/Eloquent/' => app_path() ], 'eloquent'); } public function register() { $this->app->bind('laralytics', function () { return new Laralytics(); }); } }
Fix unittest for true headers..
from twisted.trial import unittest from ooni.utils.trueheaders import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
from twisted.trial import unittest from ooni.utils.txagentwithsocks import TrueHeaders dummy_headers_dict = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'] } dummy_headers_dict2 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header3': ['ValueA', 'ValueB'], } dummy_headers_dict3 = { 'Header1': ['Value1', 'Value2'], 'Header2': ['ValueA', 'ValueB'], 'Header4': ['ValueA', 'ValueB'], } class TestTrueHeaders(unittest.TestCase): def test_names_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set()) def test_names_not_match(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3'])) th = TrueHeaders(dummy_headers_dict3) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4'])) def test_names_match_expect_ignore(self): th = TrueHeaders(dummy_headers_dict) self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
Add off as a noop function to touch editor. Closes #3107
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop, off: noop }; return TouchEditor; }; export default createTouchEditor;
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop }; return TouchEditor; }; export default createTouchEditor;
Add PropBase.flatten() support for flattening lists
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) elif isinstance(v, list): # Make lists have keys like 'foo.bar.x' for x, item in enumerate(v): key = '{2}{0}{1}'.format(sep, x, new_key) items.append((key, item)) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
Add trailing comma in array for consistency
<?php namespace OpenDominion\Factories; use Carbon\Carbon; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundFactory { // todo: move to config somewhere? const ROUND_DURATION_IN_DAYS = 50; /** * Creates and returns a new Round in a RoundLeague. * * @param RoundLeague $league * @param Carbon $startDate * * @return Round */ public function create(RoundLeague $league, Carbon $startDate, int $realmSize, int $packSize): Round { $number = ($this->getLastRoundNumber($league) + 1); return Round::create([ 'round_league_id' => $league->id, 'number' => $number, 'name' => "Beta Round {$number}", // todo 'start_date' => $startDate, 'end_date' => (clone $startDate)->addDays(static::ROUND_DURATION_IN_DAYS), 'realm_size' => $realmSize, 'pack_size' => $packSize, ]); } /** * Returns the last round number in a round league. * * @param RoundLeague $league * @return int */ protected function getLastRoundNumber(RoundLeague $league): int { $round = Round::where('round_league_id', $league->id) ->orderBy('number', 'desc') ->first(); if ($round) { return $round->number; } return 0; } }
<?php namespace OpenDominion\Factories; use Carbon\Carbon; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundFactory { // todo: move to config somewhere? const ROUND_DURATION_IN_DAYS = 50; /** * Creates and returns a new Round in a RoundLeague. * * @param RoundLeague $league * @param Carbon $startDate * * @return Round */ public function create(RoundLeague $league, Carbon $startDate, int $realmSize, int $packSize): Round { $number = ($this->getLastRoundNumber($league) + 1); return Round::create([ 'round_league_id' => $league->id, 'number' => $number, 'name' => "Beta Round {$number}", // todo 'start_date' => $startDate, 'end_date' => (clone $startDate)->addDays(static::ROUND_DURATION_IN_DAYS), 'realm_size' => $realmSize, 'pack_size' => $packSize ]); } /** * Returns the last round number in a round league. * * @param RoundLeague $league * @return int */ protected function getLastRoundNumber(RoundLeague $league): int { $round = Round::where('round_league_id', $league->id) ->orderBy('number', 'desc') ->first(); if ($round) { return $round->number; } return 0; } }
Include display metadata in mime bundle
from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) class {{cookiecutter.mime_short_name}}(JSON): """A display class for displaying {{cookiecutter.mime_short_name}} visualizations in the Jupyter Notebook and IPython kernel. {{cookiecutter.mime_short_name}} expects a JSON-able dict, not serialized JSON strings. Scalar types (None, number, string) are not allowed, only dict containers. """ def _data_and_metadata(self): return self.data, self.metadata def _ipython_display_(self): bundle = { '{{cookiecutter.mime_type}}': self.data, 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' } metadata = { '{{cookiecutter.mime_type}}': self.metadata } display(bundle, metadata=metadata, raw=True)
from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) class {{cookiecutter.mime_short_name}}(JSON): @property def data(self): return self._data @data.setter def data(self, data): if isinstance(data, str): data = json.loads(data) self._data = data def _ipython_display_(self): bundle = { '{{cookiecutter.mime_type}}': self.data, 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' } display(bundle, raw=True)
Change restrict to a Element: <routeStrips></routeScripts>. Change replaceWith for de new DOM
/** * Created by Victor Avendano on 1/10/15. * [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeScripts', ['ngRoute']); mod.directive('routeScripts', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function (scope, element) { var html = '<script ng-src="{{jsUrl}}" ng-repeat="(routeCtrl, jsUrl) in routeScripts"></script>'; element.append($compile(html)(scope)); scope.routeScripts = {}; $rootScope.$on('$routeChangeStart', function (e, next, current) { if(current && current.$$route && current.$$route.js){ if(!Array.isArray(current.$$route.js)){ current.$$route.js = [current.$$route.js]; } angular.forEach(current.$$route.js, function(script){ delete scope.routeScripts[script]; }); } if(next && next.$$route && next.$$route.js){ if(!Array.isArray(next.$$route.js)){ next.$$route.js = [next.$$route.js]; } angular.forEach(next.$$route.js, function(script){ scope.routeScripts[script] = script; }); } }); } }; } ]); })();
/** * Created by Victor Avendano on 1/10/15. * [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeScripts', ['ngRoute']); mod.directive('routeScripts', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'A', link: function (scope, element) { var html = '<script ng-src="{{jsUrl}}" ng-repeat="(routeCtrl, jsUrl) in routeScripts"></script>'; element.append($compile(html)(scope)); scope.routeScripts = {}; $rootScope.$on('$routeChangeStart', function (e, next, current) { if(current && current.$$route && current.$$route.js){ if(!Array.isArray(current.$$route.js)){ current.$$route.js = [current.$$route.js]; } angular.forEach(current.$$route.js, function(script){ delete scope.routeScripts[script]; }); } if(next && next.$$route && next.$$route.js){ if(!Array.isArray(next.$$route.js)){ next.$$route.js = [next.$$route.js]; } angular.forEach(next.$$route.js, function(script){ scope.routeScripts[script] = script; }); } }); } }; } ]); })();
Update to allow the url to be passed into a constructor for the service (the service returns a constructor).
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = {}; function NGStomp(url) { this.stompClient = Stomp.client(url); } NGStomp.prototype.subscribe = function(queue, callback) { this.stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) } NGStomp.prototype.send = function(queue, headers, data) { this.stompClient.send(queue, headers, data); } NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { this.stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); } NGStomp.prototype.disconnect = function(callback) { this.stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } return function(url) { return new NGStomp(url); } });
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = Stomp.client('http://localhost:15674/stomp'); return { subscribe: function(queue, callback) { stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) }, send: function(queue, headers, data) { stompClient.send(queue, headers, data); }, connect: function(user, password, on_connect, on_error, vhost) { stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); }, disconnect: function(callback) { stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } } // function NGStomp(url, socketClass) { // Stomp.WebSocketClass = socketClass; // var stompClient = Stomp.client(url); // } });
Add RequestContext for object detail
from django import http from django.core.exceptions import ObjectDoesNotExist from django_databrowse.datastructures import EasyModel from django_databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response from django.template import RequestContext import urlparse class ObjectDetailPlugin(DatabrowsePlugin): def model_view(self, request, model_databrowse, url): # If the object ID wasn't provided, redirect to the model page, # Which is one level up. if url is None: return http.HttpResponseRedirect( urlparse.urljoin(request.path, '../') ) easy_model = EasyModel( model_databrowse.site, model_databrowse.model ) try: obj = easy_model.object_by_pk(url) except ObjectDoesNotExist, e: raise http.Http404('Id not found') except ValueError, e: raise http.Http404('Invalid format key provided') return render_to_response( 'databrowse/object_detail.html', { 'object': obj, 'root_url': model_databrowse.site.root_url }, context_instance=RequestContext(request) )
from django import http from django.core.exceptions import ObjectDoesNotExist from django_databrowse.datastructures import EasyModel from django_databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response import urlparse class ObjectDetailPlugin(DatabrowsePlugin): def model_view(self, request, model_databrowse, url): # If the object ID wasn't provided, redirect to the model page, # Which is one level up. if url is None: return http.HttpResponseRedirect( urlparse.urljoin(request.path, '../') ) easy_model = EasyModel( model_databrowse.site, model_databrowse.model ) try: obj = easy_model.object_by_pk(url) except ObjectDoesNotExist, e: raise http.Http404('Id not found') except ValueError, e: raise http.Http404('Invalid format key provided') return render_to_response( 'databrowse/object_detail.html', { 'object': obj, 'root_url': model_databrowse.site.root_url } )
Fix list of examples at ‘/examples.’
/* eslint-disable no-console */ import React from 'react'; import request from 'superagent'; import JsonFormatter from './JsonFormatter'; import AttributesKit from '../../src'; class VisualTesting extends React.Component { constructor(props) { super(props); this.state = { fixtures: [], }; } componentDidMount() { request .get('/fixtures') .set('Accept', 'application/json') .end((err, res) => { if (err) { return console.error(res.text); } this.setState({ fixtures: res.body }); }); } render() { const rows = this.state.fixtures.map((fixture) => { return ( <div className="visualTestingContainer" key={fixture.name}> <div className="column"> <pre> {fixture.mson} </pre> </div> <div className="column"> <JsonFormatter element={fixture.parsed[0]} /> </div> <div className="column"> <AttributesKit.Attributes element={fixture.parsed[0]} /> </div> </div> ); }); return ( <div className="playgrund-app"> {rows} </div> ); } } export default VisualTesting;
/* eslint-disable no-console */ import React from 'react'; import request from 'superagent'; import JsonFormatter from './JsonFormatter'; import AttributesKit from '../../src'; class VisualTesting extends React.Component { constructor(props) { super(props); this.state = { fixtures: [], }; } componentDidMount() { request .get('/fixtures') .set('Accept', 'application/json') .end((err, res) => { if (err) { return console.error(res.text); } this.setState({ fixtures: res.body }); }); } render() { const rows = this.state.fixtures.map((fixture) => { return ( <div className="visualTestingContainer" key={fixture.name}> <div className="column"> <pre> {fixture.mson} </pre> </div> <div className="column"> <JsonFormatter element={fixture.parsed} /> </div> <div className="column"> <AttributesKit.Attributes element={fixture.parsed} /> </div> </div> ); }); return ( <div className="playgrund-app"> {rows} </div> ); } } export default VisualTesting;
Make sure JS files from addExtraJS are loaded after in-page <script>s In production we were getting an error that suggested that tabs.js was being loaded before map.js. These are loaded by different mechanisms (warning: this is all awful): - map.js is loaded via {% javascript 'google-map' %} in the <body> which is replaced by a <script> tag that loads it directly - tabs.js is loaded from the 'both' case of yepnope (although in a slightly convoluted way, because of the hack to make django-pipeline work with yepnope) - it starts with addExtraJS I believe this is happening because the files that are loaded from 'both' don't wait for the document to be ready, so the <script> tag in the body might not have been loaded yet. This moves the loading of the extra JS into the 'complete' callback of yepnope, and wraps the body of that function in $(function() { }) so that it really is only run when the document's ready. n.b. This is just a quick fix because the rep locator page is broken on People's Assembly. I think the best way to fix this ultimately is to remove this tangled web of hacked-together delayed loading entirely, and replace it with something more coherent. Fixes #2137 Fixes #2138 Fixes #2139
/* * Test for mobile / desktop and load appropriate libs/scripts */ // this is not yet ideal... it reacts a bit slow if the cdn fails (function () { // create links to all the extra js needed var extra_js = []; for ( i=0; i<pombola_settings.extra_js.length; i++ ) { var extra = pombola_settings.extra_js[i], url; if (extra) { extra_js.push(extra); } } Modernizr.load( { test : Modernizr.mq('only all and (max-width: 640px)'), yep : [ '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', ].concat(pipeline_mobile_only), nope : [ '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', ].concat(pipeline_desktop_only), both: pipeline_desktop_and_mobile.concat( ['//www.google.com/jsapi']), complete: function () { $(function() { for (i=0; i<pombola_run_when_document_ready_array.length; i++) { $( pombola_run_when_document_ready_array[i] ); } Modernizr.load(extra_js.concat(pipeline_analytics)); }); } } ); })();
/* * Test for mobile / desktop and load appropriate libs/scripts */ // this is not yet ideal... it reacts a bit slow if the cdn fails (function () { // create links to all the extra js needed var extra_js = []; for ( i=0; i<pombola_settings.extra_js.length; i++ ) { var extra = pombola_settings.extra_js[i], url; if (extra) { extra_js.push(extra); } } Modernizr.load( { test : Modernizr.mq('only all and (max-width: 640px)'), yep : [ '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', ].concat(pipeline_mobile_only), nope : [ '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', ].concat(pipeline_desktop_only), both: pipeline_desktop_and_mobile.concat( ['//www.google.com/jsapi']).concat(extra_js), complete: function () { for (i=0; i<pombola_run_when_document_ready_array.length; i++) { $( pombola_run_when_document_ready_array[i] ); } // Now load all the optional bits that we didn't want slowing down the more important bits Modernizr.load(pipeline_analytics); } } ); })();
Remove debug output on default
//= require diaspora_jsxc // initialize jsxc xmpp client $(document).ready(function() { if (app.currentUser.authenticated()) { $.post('api/v1/tokens', null, function(data) { if (jsxc && data['token']) { var jid = app.currentUser.get('diaspora_id'); jsxc.init({ root: '/assets/diaspora_jsxc', checkFlash: false, logoutElement: $('.user-menu-item [data-method=delete]'), rosterAppend: 'body', otr: { debug: true, SEND_WHITESPACE_TAG: true, WHITESPACE_START_AKE: true }, autoLang: true, priority: { online: 1, chat: 1 }, displayRosterMinimized: function() { return true; }, xmpp: { url: $('script#jsxc').data('endpoint'), username: jid.replace(/@.*?$/g, ''), domain: jid.replace(/^.*?@/g, ''), jid: jid, password: data['token'], resource: 'diaspora-jsxc', overwrite: true, onlogin: true } }); jsxc.login(); } else { console.error('No token found! Authenticated!?'); } }, 'json'); } });
//= require diaspora_jsxc // initialize jsxc xmpp client $(document).ready(function() { if (app.currentUser.authenticated()) { $.post('api/v1/tokens', null, function(data) { if (jsxc && data['token']) { var jid = app.currentUser.get('diaspora_id'); jsxc.init({ root: '/assets/diaspora_jsxc', checkFlash: false, logoutElement: $('.user-menu-item [data-method=delete]'), rosterAppend: 'body', otr: { debug: true, SEND_WHITESPACE_TAG: true, WHITESPACE_START_AKE: true }, autoLang: true, priority: { online: 1, chat: 1 }, displayRosterMinimized: function() { return true; }, xmpp: { url: $('script#jsxc').data('endpoint'), username: jid.replace(/@.*?$/g, ''), domain: jid.replace(/^.*?@/g, ''), jid: jid, password: data['token'], resource: 'diaspora-jsxc', overwrite: true, onlogin: true } }); // TODO unset debug on default (testing version) jsxc.storage.setItem('debug', true); jsxc.login(); } else { console.error('No token found! Authenticated!?'); } }, 'json'); } });
Add task for Travis CI
/* jshint: node:true */ module.exports = function (grunt) { 'use strict'; grunt.initConfig({ phplint: { application: ["lib/*.php", "tests/**/*.php"] }, phpcs: { application: { src: 'lib/*.php' }, options: { standard: 'PSR1', showSniffCodes: true, verbose: true } }, phpunit: { application: { dir: 'tests/' }, options: { colors: true, coverage: true } }, phpcpd: { application: { dir: 'lib/' }, options: { quiet: true } }, phpmd: { application: { dir: 'lib/' }, options: { rulesets: 'codesize,unusedcode,naming,design' } } }); grunt.loadNpmTasks('grunt-phpcs'); grunt.loadNpmTasks('grunt-phplint'); grunt.loadNpmTasks('grunt-phpunit'); grunt.loadNpmTasks('grunt-phpcpd'); grunt.loadNpmTasks('grunt-phpmd'); grunt.registerTask("default", [ "phplint", "phpunit", "phpcpd" ]); grunt.registerTask('travis', [ "phplint", "phpunit", "phpcpd" ]); };
/* jshint: node:true */ module.exports = function (grunt) { 'use strict'; grunt.initConfig({ phplint: { application: ["lib/*.php", "tests/**/*.php"] }, phpcs: { application: { src: 'lib/*.php' }, options: { standard: 'PSR1', showSniffCodes: true, verbose: true } }, phpunit: { application: { dir: 'tests/' }, options: { colors: true, coverage: true } }, phpcpd: { application: { dir: 'lib/' }, options: { quiet: true } }, phpmd: { application: { dir: 'lib/' }, options: { rulesets: 'codesize,unusedcode,naming,design' } } }); grunt.loadNpmTasks('grunt-phpcs'); grunt.loadNpmTasks('grunt-phplint'); grunt.loadNpmTasks('grunt-phpunit'); grunt.loadNpmTasks('grunt-phpcpd'); grunt.loadNpmTasks('grunt-phpmd'); grunt.registerTask("default", [ "phplint", "phpunit", "phpcpd" ]); };
Ch18: Use GCBV queryset to get PostGetMixin obj.
from django.shortcuts import get_object_or_404 from .models import Post class PostGetMixin: date_field = 'pub_date' model = Post month_url_kwarg = 'month' year_url_kwarg = 'year' errors = { 'url_kwargs': "Generic view {} must be called with " "year, month, and slug.", 'not_exist': "No {} by that date and slug.", } def get_object(self, queryset=None): year = self.kwargs.get( self.year_url_kwarg) month = self.kwargs.get( self.month_url_kwarg) slug = self.kwargs.get( self.slug_url_kwarg) if (year is None or month is None or slug is None): raise AttributeError( self.errors['url_kwargs'].format( self.__class__.__name__)) date_field = self.date_field slug_field = self.get_slug_field() filter_dict = { date_field + '__year': year, date_field + '__month': month, slug_field: slug, } if queryset is None: queryset = self.get_queryset() queryset = queryset.filter(**filter_dict) try: obj = queryset.get() except queryset.model.DoesNotExist: raise Http404( self.errors['not_exist'].format( queryset.model ._meta.verbose_name)) return obj
from django.shortcuts import get_object_or_404 from .models import Post class PostGetMixin: date_field = 'pub_date' month_url_kwarg = 'month' year_url_kwarg = 'year' errors = { 'url_kwargs': "Generic view {} must be called with " "year, month, and slug.", } def get_object(self, queryset=None): year = self.kwargs.get( self.year_url_kwarg) month = self.kwargs.get( self.month_url_kwarg) slug = self.kwargs.get( self.slug_url_kwarg) if (year is None or month is None or slug is None): raise AttributeError( self.errors['url_kwargs'].format( self.__class__.__name__)) date_field = self.date_field slug_field = self.get_slug_field() filter_dict = { date_field + '__year': year, date_field + '__month': month, slug_field: slug, } return get_object_or_404( Post, **filter_dict)
Send the gecos input from USER through the sanitization as well
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.setUsername(data["ident"]) user.setRealname(data["gecos"]) if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } }
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.setUsername(data["ident"]) user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } }
Put screenshot folder creation recursively Not recursive by default : `http://php.net/manual/fr/function.mkdir.php`
<?php namespace emuse\BehatHTMLFormatter\Context; use Behat\MinkExtension\Context\RawMinkContext; class ScreenshotContext extends RawMinkContext { private $currentScenario; private $screenshotDir; public function __construct($screenshotDir) { $this->screenshotDir = $screenshotDir; } /** * @BeforeScenario * * @param BeforeScenarioScope $scope */ public function setUpTestEnvironment($scope) { $this->currentScenario = $scope->getScenario(); } /** * @AfterStep * * @param AfterStepScope $scope */ public function afterStep($scope) { // if test is passed, skip taking screenshot if ($scope->getTestResult()->isPassed()) { return; } // create filename string $featureFolder = preg_replace('/\W/', '', $scope->getFeature()->getTitle()); $scenarioName = $this->currentScenario->getTitle(); $fileName = preg_replace('/\W/', '', $scenarioName).'.png'; // create screenshots directory if it doesn't exist if (!file_exists($this->screenshotDir.'/'.$featureFolder)) { mkdir($this->screenshotDir.'/'.$featureFolder, 0777, true); } $this->saveScreenshot($fileName, $this->screenshotDir.'/'.$featureFolder.'/'); } }
<?php namespace emuse\BehatHTMLFormatter\Context; use Behat\MinkExtension\Context\RawMinkContext; class ScreenshotContext extends RawMinkContext { private $currentScenario; private $screenshotDir; public function __construct($screenshotDir) { $this->screenshotDir = $screenshotDir; } /** * @BeforeScenario * * @param BeforeScenarioScope $scope */ public function setUpTestEnvironment($scope) { $this->currentScenario = $scope->getScenario(); } /** * @AfterStep * * @param AfterStepScope $scope */ public function afterStep($scope) { // if test is passed, skip taking screenshot if ($scope->getTestResult()->isPassed()) { return; } // create filename string $featureFolder = preg_replace('/\W/', '', $scope->getFeature()->getTitle()); $scenarioName = $this->currentScenario->getTitle(); $fileName = preg_replace('/\W/', '', $scenarioName).'.png'; // create screenshots directory if it doesn't exist if (!file_exists($this->screenshotDir.'/'.$featureFolder)) { mkdir($this->screenshotDir.'/'.$featureFolder); } $this->saveScreenshot($fileName, $this->screenshotDir.'/'.$featureFolder.'/'); } }
Use the mock discovery module
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose sts.syncproto.pox_syncer ''' '''openflow.mock_discovery forwarding.l2_multi ''' '''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [ControllerConfig(command_line, cwd="pox", sync="tcp:localhost:18899")] topology_class = MeshTopology topology_params = "num_switches=2" dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=True) control_flow = Fuzzer(simulation_config, check_interval=80, halt_on_violation=False, input_logger=InputLogger(), invariant_check=InvariantChecker.check_loops, mock_link_discovery=True) #control_flow = Interactive(simulation_config, input_logger=InputLogger())
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose sts.syncproto.pox_syncer ''' '''openflow.discovery forwarding.l2_multi ''' '''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [ControllerConfig(command_line, cwd="pox", sync="tcp:localhost:18899")] topology_class = MeshTopology topology_params = "num_switches=2" dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=True) control_flow = Fuzzer(simulation_config, check_interval=80, halt_on_violation=False, input_logger=InputLogger(), invariant_check=InvariantChecker.check_loops) #control_flow = Interactive(simulation_config, input_logger=InputLogger())
Decrease scipy version to 0.17 (for RTD)
# -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as rdm: README = rdm.read() setup( name='stagpy', use_scm_version=True, description='Tool for StagYY output files processing', long_description=README, url='https://github.com/StagPython/StagPy', author='Martina Ulvrova, Adrien Morison, Stéphane Labrosse', author_email='[email protected]', license='GPLv2', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages = ['stagpy'], entry_points = { 'console_scripts': ['stagpy = stagpy.__main__:main'] }, setup_requires=['setuptools_scm'], install_requires = [ 'numpy>=1.12', 'scipy>=0.17', 'f90nml>=0.21', 'pandas>=0.20', 'matplotlib>=2.0', 'seaborn>=0.7.1', 'argcomplete>=1.8', 'setuptools_scm>=1.15', ], )
# -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as rdm: README = rdm.read() setup( name='stagpy', use_scm_version=True, description='Tool for StagYY output files processing', long_description=README, url='https://github.com/StagPython/StagPy', author='Martina Ulvrova, Adrien Morison, Stéphane Labrosse', author_email='[email protected]', license='GPLv2', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages = ['stagpy'], entry_points = { 'console_scripts': ['stagpy = stagpy.__main__:main'] }, setup_requires=['setuptools_scm'], install_requires = [ 'numpy>=1.12', 'scipy>=0.19', 'f90nml>=0.21', 'pandas>=0.20', 'matplotlib>=2.0', 'seaborn>=0.7.1', 'argcomplete>=1.8', 'setuptools_scm>=1.15', ], )
Remove po files from gh-pages
module.exports = { all: { files: [ { expand: true, src: [ 'index.html', '404.html', 'sitemap.xml', 'robots.txt' ], dest: global.dist }, { expand: true, cwd: 'src/download/', src: ['**'], dest: global.dist + '/download/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: global.dist + '/images/', }, { expand: true, cwd: 'src/javascript/autogenerated/', src: ['**'], dest: global.dist + '/js/texts/' }, { expand: true, cwd: 'src/javascript/lib/ico/', src: ['**'], dest: global.dist + '/js/ico/' }, { expand: true, cwd: 'src/javascript/lib/pushwooshSDK/', src: ['**'], dest: global.dist }, /* serves pushwoosh sdks from root */ { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: global.dist + '/css/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: global.dist + '/css/images' }, ] } };
module.exports = { all: { files: [ { expand: true, src: [ 'index.html', '404.html', 'sitemap.xml', 'robots.txt' ], dest: global.dist }, { expand: true, cwd: 'src/config/', src: ['**'], dest: global.dist + '/config/' }, { expand: true, cwd: 'src/download/', src: ['**'], dest: global.dist + '/download/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: global.dist + '/images/', }, { expand: true, cwd: 'src/javascript/autogenerated/', src: ['**'], dest: global.dist + '/js/texts/' }, { expand: true, cwd: 'src/javascript/lib/ico/', src: ['**'], dest: global.dist + '/js/ico/' }, { expand: true, cwd: 'src/javascript/lib/pushwooshSDK/', src: ['**'], dest: global.dist }, /* serves pushwoosh sdks from root */ { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: global.dist + '/css/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: global.dist + '/css/images' }, ] } };
Return store assets as JSON
<?php /** * eTinyMCE backend controller. * * @package Rootd_Tinymce * @author Rick Buczynski <[email protected]> * @copyright 2014 Rick Buczynski. All Rights Reserved. */ class Rootd_Tinymce_Adminhtml_BackendController extends Mage_Adminhtml_Controller_Action { // temporary protected $_publicActions = array('loadstoreassets'); /** * Load store assets for applying to TinyMCE instance. * * @return void */ public function loadstoreassetsAction() { $assets = array(); if ( ($storeId = $this->getRequest()->getParam('id')) ) { $emulator = Mage::getSingleton('core/app_emulation'); $initialEnvironment = $emulator->startEnvironmentEmulation($storeId); $this->loadLayout(); $headBlock = $this->getLayout()->getBlock('head'); $items = $headBlock->getData('items'); foreach ($items as $key => $item) { $type = end( ( explode('.', basename($item['name'])) ) ); if ( empty($item['if']) && strcasecmp($type, 'css') == 0 ) { $css[$key] = $item; } } $headBlock->setData('items', $css); // Closest we can get without a lot of re-writes is to parse the final HTML $html = $headBlock->getCssJsHtml(); preg_match_all('/href="([^"]*)"/', $html, $matches); $assets = end($matches); $emulator->stopEnvironmentEmulation($initialEnvironment); } $this->getResponse() ->setHeader('Content-Type', 'application/json') ->setBody(Mage::helper('core')->jsonEncode($assets)) ->sendResponse(); exit; } }
<?php /** * eTinyMCE backend controller. * * @package Rootd_Tinymce * @author Rick Buczynski <[email protected]> * @copyright 2014 Rick Buczynski. All Rights Reserved. */ class Rootd_Tinymce_Adminhtml_BackendController extends Mage_Adminhtml_Controller_Action { // temporary protected $_publicActions = array('loadstoreassets'); /** * Load store assets for applying to TinyMCE instance. * * @return void */ public function loadstoreassetsAction() { $output = ''; if ( ($storeId = $this->getRequest()->getParam('id')) ) { $emulator = Mage::getSingleton('core/app_emulation'); $initialEnvironment = $emulator->startEnvironmentEmulation($storeId); $this->loadLayout(); // Simpler to render and parse the head than to re-write that block $output = $this->getLayout() ->getBlock('head') ->getCssJsHtml(); $emulator->stopEnvironmentEmulation($initialEnvironment); } $this->getResponse() ->setBody($output) ->sendResponse(); } }
Fix exception in propel subscriber
<?php namespace Knp\Component\Pager\Event\Subscriber\Sortable; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Knp\Component\Pager\Event\ItemsEvent; class PropelQuerySubscriber implements EventSubscriberInterface { public function items(ItemsEvent $event) { $query = $event->target; if ($query instanceof \ModelCriteria) { if (isset($_GET[$event->options['sortFieldParameterName']])) { $part = $_GET[$event->options['sortFieldParameterName']]; $directionParam = $event->options['sortDirectionParameterName']; $direction = (isset($_GET[$directionParam]) && strtolower($_GET[$directionParam]) === 'asc') ? 'asc' : 'desc'; if (isset($event->options['sortFieldWhitelist'])) { if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) { throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist"); } } $query->orderBy($part, $direction); } } } public static function getSubscribedEvents() { return array( 'knp_pager.items' => array('items', 1) ); } }
<?php namespace Knp\Component\Pager\Event\Subscriber\Sortable; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Knp\Component\Pager\Event\ItemsEvent; class PropelQuerySubscriber implements EventSubscriberInterface { public function items(ItemsEvent $event) { $query = $event->target; if ($query instanceof \ModelCriteria) { if (isset($_GET[$event->options['sortFieldParameterName']])) { $direction = strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc'; $part = $_GET[$event->options['sortFieldParameterName']]; if (isset($event->options['sortFieldWhitelist'])) { if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) { throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist"); } } $query->orderBy($part, $direction); } } } public static function getSubscribedEvents() { return array( 'knp_pager.items' => array('items', 1) ); } }
Update naming convention to fix sorting bug
(function(){ "use strict" $(document).ready(init); function init(){ $(".sort").on('click', sortActivities); $(".user-activities").on('click', ".card", showDescription); } function sortActivities() { var type = $(this).text().toLowerCase(), $activities = $(".user-activity"), orderedByDateActivities = []; if (type == "name") { orderedByDateActivities = $activities.sort(function(a,b){ return $(a).find(".user-activity__name").text().trim() > $(b).find(".user-activity__name").text().trim(); }); $(".user-activities").empty().append(orderedByDateActivities); } else if (type == "date") { orderedByDateActivities = $activities.sort(function(a,b){ return new Date($(a).find(".user-activity__date").text()) > new Date($(b).find(".user-activity__date").text()); }); $(".user-activities").empty().append(orderedByDateActivities); } else if (type == "venue") { orderedByDateActivities = $activities.sort(function(a,b){ return $(a).find(".user-activity__venue-name").text() > $(b).find(".user-activity__venue-name").text(); }); $(".user-activities").empty().append(orderedByDateActivities); } } function showDescription() { var selectedActvity = $(this).closest('.user-activity'); var description = selectedActvity.find('.activity__description').toggleClass("hidden"); } })();
(function(){ "use strict" $(document).ready(init); function init(){ $(".sort").on('click', sortActivities); $(".user-activities").on('click', ".card", showDescription); } function sortActivities() { var type = $(this).text().toLowerCase(), $activities = $(".user-activity"), orderedByDateActivities = []; if (type == "name") { orderedByDateActivities = $activities.sort(function(a,b){ return $(a).find(".activity__name").text() > $(b).find(".activity__name").text(); }); $(".user-activities").empty().append(orderedByDateActivities); } else if (type == "date") { orderedByDateActivities = $activities.sort(function(a,b){ return (new Date($(a).find(".activity__date").text())) > (new Date($(b).find(".activity__date").text())); }); $(".user-activities").empty().append(orderedByDateActivities); } else if (type == "venue") { orderedByDateActivities = $activities.sort(function(a,b){ return $(a).find(".activity__venue-name").text() > $(b).find(".activity__venue-name").text(); }); $(".user-activities").empty().append(orderedByDateActivities); } } function showDescription() { var selectedActvity = $(this).closest('.user-activity'); var description = selectedActvity.find('.activity__description').toggleClass("hidden"); } })();
Add `async.parallel` option to run tests in parallel instead of in series
/* * grunt-casperjs * https://github.com/ronaldlokers/grunt-casperjs * * Copyright (c) 2013 Ronald Lokers * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var casperjs = require('./lib/casperjs').init(grunt).casperjs; grunt.registerMultiTask('casperjs', 'Run CasperJs tests.', function() { // Merge task-specific and/or target-specific options with these defaults. var done = this.async(), filepaths = [], options = grunt.util._.defaults(this.options(), {async: {}}), asyncLoop = options.async.parallel ? 'forEach' : 'forEachSeries'; // Get rid of the async options since they're unrelated to casper/phantom delete options.async; // Iterate over all specified file groups. this.files.forEach(function(file) { // Concat specified files. file.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { filepaths.push(filepath); return true; } }); }); grunt.util.async[asyncLoop]( filepaths, function(filepath, callback) { casperjs(filepath, options, function(err) { if (err) { grunt.warn(err); } callback(); }); }, done); }); };
/* * grunt-casperjs * https://github.com/ronaldlokers/grunt-casperjs * * Copyright (c) 2013 Ronald Lokers * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var casperjs = require('./lib/casperjs').init(grunt).casperjs; grunt.registerMultiTask('casperjs', 'Run CasperJs tests.', function() { // Merge task-specific and/or target-specific options with these defaults. var done = this.async(), filepaths = [], options = this.options(); // Iterate over all specified file groups. this.files.forEach(function(file) { // Concat specified files. file.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { filepaths.push(filepath); return true; } }); }); grunt.util.async.forEachSeries( filepaths, function(filepath, callback) { casperjs(filepath, options, function(err) { if (err) { grunt.warn(err); } callback(); }); }, done); }); };
Use name 'default color' for "global" color setting
import VisualizationComponent from '../core/VisualizationComponent'; import vcharts from '../external/vcharts/src'; export default class Scatter extends VisualizationComponent { static get options () { return [ {name: 'data', type: 'table'}, {name: 'x', type: 'string'}, {name: 'y', type: 'string'}, {name: 'color', type: 'string'} ]; } constructor (el, data, options) { super(el); this.data = data; this.options = Object.assign({}, options); this.options.x = this.options.x || 'x'; this.options.y = this.options.y || 'y'; this.options.defaultColor = this.options.defaultColor || 'steelblue'; this.chart = vcharts.chart('xy', { el, series: [ { name: 'values' } ] }); window.onresize = () => this.render(); } render () { this.chart.update({ series: [{ name: 'values', values: this.data, x: this.options.x, y: this.options.y, color: this.options.color }], xAxis: { title: this.options.x }, yAxis: { title: this.options.y }, legend: false }); } }
import VisualizationComponent from '../core/VisualizationComponent'; import vcharts from '../external/vcharts/src'; export default class Scatter extends VisualizationComponent { static get options () { return [ {name: 'data', type: 'table'}, {name: 'x', type: 'string'}, {name: 'y', type: 'string'}, {name: 'color', type: 'string'} ]; } constructor (el, data, options) { super(el); this.data = data; this.options = Object.assign({}, options); this.options.x = this.options.x || 'x'; this.options.y = this.options.y || 'y'; this.options.color = this.options.color || 'steelblue'; this.chart = vcharts.chart('xy', { el, series: [ { name: 'values' } ] }); window.onresize = () => this.render(); } render () { this.chart.update({ series: [{ name: 'values', values: this.data, x: this.options.x, y: this.options.y, color: this.options.color }], xAxis: { title: this.options.x }, yAxis: { title: this.options.y }, legend: false }); } }
Use open mode syntax on example file
from __future__ import print_function import os import glob import pyingest.parsers.aps as aps import pyingest.parsers.arxiv as arxiv import pyingest.serializers.classic import traceback import json import xmltodict from datetime import datetime import sys input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' if sys.version_info > (3,): open_mode = 'r' else: open_mode = 'rU' with open(input_list, open_mode) as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.', '/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) for f in testfile: fnord = f[92:] if os.path.isfile(f): print("found! ", fnord) with open(f, open_mode) as fp: parser = aps.APSJATSParser() document = parser.parse(fp) serializer = pyingest.serializers.classic.Tagged() outputfp = open('aps.tag', 'a') serializer.write(document, outputfp) outputfp.close() #except: # print "ERROR!\n%s\n"%f # traceback.print_exc() # pass else: print("not found :( ", fnord)
from __future__ import print_function import os import glob import pyingest.parsers.aps as aps import pyingest.parsers.arxiv as arxiv import pyingest.serializers.classic import traceback import json import xmltodict from datetime import datetime input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' with open(input_list,'rU') as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.','/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) for f in testfile: fnord = f[92:] if os.path.isfile(f): print("found! ",fnord) with open(f, 'rU') as fp: parser = aps.APSJATSParser() document = parser.parse(fp) serializer = pyingest.serializers.classic.Tagged() outputfp = open('aps.tag', 'a') serializer.write(document, outputfp) outputfp.close() #except: # print "ERROR!\n%s\n"%f # traceback.print_exc() # pass else: print("not found :( ", fnord)
Use correct database name instead of None when not supplied.
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueError('Only tcp scheme supported for postgres') host, port = pg_url.netloc.split(':') uri = 'postgres://{user}:{password}@{host}:{port}/{database}'.format( user=os.environ.get('PG_ENV_POSTGRES_USER', 'postgres'), password=os.environ.get('PG_ENV_POSTGRES_PASSWORD', ''), host=host, port=port, database=os.environ.get('PG_ENV_POSTGRES_DB', 'postgres')) config['SQLALCHEMY_DATABASE_URI'] = uri if 'REDIS_PORT' in os.environ: redis_url = urlparse(os.environ['REDIS_PORT']) if not redis_url.scheme == 'tcp': raise ValueError('Only tcp scheme supported for redis') host, port = redis_url.netloc.split(':') uri = 'redis://{host}:{port}/0'.format(host=host, port=port, ) config['REDIS_URL'] = uri config['REDIS_HOST'] = host config['REDIS_PORT'] = int(port)
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueError('Only tcp scheme supported for postgres') host, port = pg_url.netloc.split(':') uri = 'postgres://{user}:{password}@{host}:{port}/{database}'.format( user=os.environ.get('PG_ENV_POSTGRES_USER', 'postgres'), password=os.environ.get('PG_ENV_POSTGRES_PASSWORD', ''), host=host, port=port, database=os.environ.get('PG_ENV_POSTGRES_DB')) config['SQLALCHEMY_DATABASE_URI'] = uri if 'REDIS_PORT' in os.environ: redis_url = urlparse(os.environ['REDIS_PORT']) if not redis_url.scheme == 'tcp': raise ValueError('Only tcp scheme supported for redis') host, port = redis_url.netloc.split(':') uri = 'redis://{host}:{port}/0'.format(host=host, port=port, ) config['REDIS_URL'] = uri config['REDIS_HOST'] = host config['REDIS_PORT'] = int(port)
Remove now useless test for initial sites value in form
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Add a script to show per-residue score from a PDB file.
#!/usr/bin/env python2 from setuptools import setup, find_packages # Uploading to PyPI # ================= # The first time only: # $ python setup.py register -r pypi # # Every version bump: # $ git tag <version>; git push --tags # $ python setup.py sdist upload -r pypi version = '0.4.1' setup( name='klab', version=version, author='Kortemme Lab, UCSF', author_email='[email protected]', url='https://github.com/Kortemme-Lab/klab', download_url='https://github.com/Kortemme-Lab/klab/tarball/'+version, license='MIT', description="A collection of utilities used by our lab for computational biophysics", long_description=open('README.rst').read(), keywords=['utilities', 'library', 'biophysics'], classifiers=[ "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 3 - Alpha", 'Programming Language :: Python :: 2', ], packages=find_packages(), package_data={ 'klab.bio.fragments': [ 'make_fragments_QB3_cluster.pl', ], }, install_requires=[], entry_points={ 'console_scripts': [ 'klab_generate_fragments=klab.bio.fragments.generate_fragments:main', 'klab_per_residue_scores=klab.rosetta.per_residue_scores:main', ], }, )
#!/usr/bin/env python2 from setuptools import setup, find_packages # Uploading to PyPI # ================= # The first time only: # $ python setup.py register -r pypi # # Every version bump: # $ git tag <version>; git push --tags # $ python setup.py sdist upload -r pypi version = '0.4.1' setup( name='klab', version=version, author='Kortemme Lab, UCSF', author_email='[email protected]', url='https://github.com/Kortemme-Lab/klab', download_url='https://github.com/Kortemme-Lab/klab/tarball/'+version, license='MIT', description="A collection of utilities used by our lab for computational biophysics", long_description=open('README.rst').read(), keywords=['utilities', 'library', 'biophysics'], classifiers=[ "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 3 - Alpha", 'Programming Language :: Python :: 2', ], packages=find_packages(), package_data={ 'klab.bio.fragments': [ 'make_fragments_QB3_cluster.pl', ], }, install_requires=[], entry_points={ 'console_scripts': [ 'klab_generate_fragments=klab.bio.fragments.generate_fragments:main', ], }, )
Disable the save button when there's nothing to save
import React, { Component } from 'react' import styles from './ProjectButtons.styl' export default class extends Component { constructor() { super() this.state = { isSaving: false } } render() { const { isSaving } = this.state const { onCancelChanges, onSaveChanges, changesExist } = this.props return ( <div className={styles.container}> <button onClick={onCancelChanges} type="button" name="button" disabled={isSaving || !changesExist} className="btn" > Cancel </button> <button style={{ display: 'flex', alignItems: 'center', }} onClick={() => { this.setState({ isSaving: true }) onSaveChanges().then(() => { this.setState({ isSaving: false }) }) }} type="button" name="button" disabled={isSaving || !changesExist} className="btn btn-primary" > {isSaving ? 'Saving...' : 'Save'} <img src="/public/img/ripple.svg" style={{ marginLeft: '0.7rem', marginRight: '-0.6rem', width: isSaving ? '18px' : 0, }} /> </button> </div> ) } }
import React, { Component } from 'react' import styles from './ProjectButtons.styl' export default class extends Component { constructor() { super() this.state = { isSaving: false } } render() { const { isSaving } = this.state const { onCancelChanges, onSaveChanges, changesExist } = this.props return ( <div className={styles.container}> <button onClick={onCancelChanges} type="button" name="button" disabled={isSaving || !changesExist} className="btn" > Cancel </button> <button style={{ display: 'flex', alignItems: 'center', }} onClick={() => { this.setState({ isSaving: true }) onSaveChanges().then(() => { this.setState({ isSaving: false }) }) }} type="button" name="button" disabled={isSaving} className="btn btn-primary" > {isSaving ? 'Saving...' : 'Save'} <img src="/public/img/ripple.svg" style={{ marginLeft: '0.7rem', marginRight: '-0.6rem', width: isSaving ? '18px' : 0, }} /> </button> </div> ) } }
Remove stray debug log statement.
package com.openxc.remote.sources; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public abstract class JsonVehicleDataSource extends AbstractVehicleDataSource { private static final String TAG = "JsonVehicleDataSource"; public JsonVehicleDataSource() { super(); } public JsonVehicleDataSource(VehicleDataSourceCallbackInterface callback) { super(callback); } protected void parseJson(String json) { final JSONObject message; try { message = new JSONObject(json); } catch(JSONException e) { Log.i(TAG, "Couldn't decode JSON from: " + json); return; } try { handleMessage(message.getString("name"), message.getDouble("value")); return; } catch(JSONException e) { } try { handleMessage(message.getString("name"), message.getString("value")); } catch(JSONException e) { Log.w(TAG, "JSON value wasn't a double or string -- couldn't parse", e); } } }
package com.openxc.remote.sources; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public abstract class JsonVehicleDataSource extends AbstractVehicleDataSource { private static final String TAG = "JsonVehicleDataSource"; public JsonVehicleDataSource() { super(); } public JsonVehicleDataSource(VehicleDataSourceCallbackInterface callback) { super(callback); } protected void parseJson(String json) { final JSONObject message; try { message = new JSONObject(json); } catch(JSONException e) { Log.i(TAG, "Couldn't decode JSON from: " + json); return; } try { Log.d("FRING", message.toString()); handleMessage(message.getString("name"), message.getDouble("value")); return; } catch(JSONException e) { } try { handleMessage(message.getString("name"), message.getString("value")); } catch(JSONException e) { Log.w(TAG, "JSON value wasn't a double or string -- couldn't parse", e); } } }
Remove Response::HTTP_BAD_REQUEST for symfony 2.3 compatibility
<?php /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { /** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (! $this->isJsonRequest($request)) { return; } if (! $this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', 400); $event->setResponse($response); } } private function isJsonRequest(Request $request) { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request) { $data = json_decode($request->getContent(), true); if (json_last_error() !== JSON_ERROR_NONE) { return false; } if ($data === null) { return true; } $request->request->replace($data); return true; } }
<?php /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { /** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (! $this->isJsonRequest($request)) { return; } if (! $this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', Response::HTTP_BAD_REQUEST); $event->setResponse($response); } } private function isJsonRequest(Request $request) { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request) { $data = json_decode($request->getContent(), true); if (json_last_error() !== JSON_ERROR_NONE) { return false; } if ($data === null) { return true; } $request->request->replace($data); return true; } }
Fix trailing line style violation
from six.moves import configparser def parse_mysql_cnf(dbinfo): """ Attempt to parse mysql database config file for connection settings. Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs so we have to emulate the behaviour Settings that are missing will return '' returns (user, password, database_name, database_host, database_port) """ read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file') if read_default_file: config = configparser.RawConfigParser({ 'user': '', 'password': '', 'database': '', 'host': '', 'port': '', 'socket': '', }) import os config.read(os.path.expanduser(read_default_file)) try: user = config.get('client', 'user') password = config.get('client', 'password') database_name = config.get('client', 'database') database_host = config.get('client', 'host') database_port = config.get('client', 'port') socket = config.get('client', 'socket') if database_host == 'localhost' and socket: # mysql actually uses a socket if host is localhost database_host = socket return user, password, database_name, database_host, database_port except configparser.NoSectionError: pass return '', '', '', '', ''
from six.moves import configparser def parse_mysql_cnf(dbinfo): """ Attempt to parse mysql database config file for connection settings. Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs so we have to emulate the behaviour Settings that are missing will return '' returns (user, password, database_name, database_host, database_port) """ read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file') if read_default_file: config = configparser.RawConfigParser({ 'user': '', 'password': '', 'database': '', 'host': '', 'port': '', 'socket': '', }) import os config.read(os.path.expanduser(read_default_file)) try: user = config.get('client', 'user') password = config.get('client', 'password') database_name = config.get('client', 'database') database_host = config.get('client', 'host') database_port = config.get('client', 'port') socket = config.get('client', 'socket') if database_host == 'localhost' and socket: # mysql actually uses a socket if host is localhost database_host = socket return user, password, database_name, database_host, database_port except configparser.NoSectionError: pass return '', '', '', '', ''
pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling. git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9
from django.conf import settings from django.db.models.loading import get_app from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from notification import backends from notification.message import message_to_text # favour django-mailer but fall back to django.core.mail try: mailer = get_app("mailer") from mailer import send_mail except ImproperlyConfigured: from django.core.mail import send_mail class EmailBackend(backends.BaseBackend): def can_send(self, user, notice_type): if should_send(user, notice_type, "1") and user.email: return True return False def deliver(self, recipients, notice_type, message): notices_url = u"http://%s%s" % ( unicode(Site.objects.get_current()), reverse("notification_notices"), ) subject = render_to_string("notification/notification_subject.txt", { "display": ugettext(notice_type.display), }) message_body = render_to_string("notification/notification_body.txt", { "message": message_to_text(message), "notices_url": notices_url, "contact_email": settings.CONTACT_EMAIL, }) send_mail(subject, message_body, settings.DEFAULT_FROM_EMAIL, recipients)
from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from notification import backends from notification.message import message_to_text # favour django-mailer but fall back to django.core.mail try: from mailer import send_mail except ImportError: from django.core.mail import send_mail class EmailBackend(backends.BaseBackend): def can_send(self, user, notice_type): if should_send(user, notice_type, "1") and user.email: return True return False def deliver(self, recipients, notice_type, message): notices_url = u"http://%s%s" % ( unicode(Site.objects.get_current()), reverse("notification_notices"), ) subject = render_to_string("notification/notification_subject.txt", { "display": ugettext(notice_type.display), }) message_body = render_to_string("notification/notification_body.txt", { "message": message_to_text(message), "notices_url": notices_url, "contact_email": settings.CONTACT_EMAIL, }) send_mail(subject, message_body, settings.DEFAULT_FROM_EMAIL, recipients)
Use RandomUsersRetriever when ENDPOINT_ID is not set
/* eslint-disable no-console */ import AccessTokenRetriever from './access-token-retriever'; import ConfigurationProvider from './configuration-provider'; import WebServer from './web-server'; import WindowsGraphUsersRetriever from './windows-graph-users-retriever'; import RandomUsersRetriever from './random-users-retriever'; export default class Main { constructor() { this.configuration = new ConfigurationProvider().getConfiguration(); this.directoryItems = []; this.isRefreshing = false; } start() { return this.refreshData() .then(() => new WebServer(this.directoryItems, () => this.refreshData()).start()) .catch(err => { console.error(err); process.exit(-1); // eslint-disable-line no-process-exit, no-magic-numbers }); } refreshData() { if (!this.configuration.endpointId) { console.log('process.env.ENDPOINT_ID is not set, using RandomUsersRetriever ...'); return new RandomUsersRetriever() .getUsers(100, 4) // eslint-disable-line no-magic-numbers .then(users => { this.directoryItems = users; }); } if (this.isRefreshing) { return Promise.resolve(true); } this.isRefreshing = true; return new AccessTokenRetriever() .getAccessToken( this.configuration.endpointId, this.configuration.clientId, this.configuration.clientSecret) .then(accessToken => new WindowsGraphUsersRetriever() .getUsers(this.configuration.endpointId, accessToken)) .then(users => { this.directoryItems = users; this.isRefreshing = false; }) .catch(x => { this.isRefreshing = false; return x; }); } }
/* eslint-disable no-console */ import AccessTokenRetriever from './access-token-retriever'; import ConfigurationProvider from './configuration-provider'; import WebServer from './web-server'; import WindowsGraphUsersRetriever from './windows-graph-users-retriever'; export default class Main { constructor() { this.configuration = new ConfigurationProvider().getConfiguration(); this.directoryItems = []; this.isRefreshing = false; } start() { return this.refreshData() .then(() => new WebServer(this.directoryItems, () => this.refreshData()).start()) .catch(err => { console.error(err); process.exit(-1); // eslint-disable-line no-process-exit, no-magic-numbers }); } refreshData() { if (this.isRefreshing) { return Promise.resolve(true); } this.isRefreshing = true; return new AccessTokenRetriever() .getAccessToken( this.configuration.endpointId, this.configuration.clientId, this.configuration.clientSecret) .then(accessToken => new WindowsGraphUsersRetriever() .getUsers(this.configuration.endpointId, accessToken)) .then(users => { this.directoryItems = users; this.isRefreshing = false; }) .catch(x => { this.isRefreshing = false; return x; }); } }
Fix bug where empty mapping was processed
<?php declare(strict_types=1); namespace Mihaeu\PhpDependencies\Formatters; use Mihaeu\PhpDependencies\Dependencies\Dependency; use Mihaeu\PhpDependencies\Dependencies\DependencySet; use Mihaeu\PhpDependencies\Dependencies\DependencyMap; class DependencyStructureMatrixBuilder { public function buildMatrix(DependencyMap $dependencies, \Closure $mappers) : array { $emptyDsm = $this->createEmptyDsm($dependencies->mapAllDependencies($mappers)); return $dependencies->reduce($emptyDsm, function (array $dsm, Dependency $from, Dependency $to) use ($mappers) : array { $from = $mappers($from)->toString(); $to = $mappers($to)->toString(); if ($from === $to || strlen($from) === 0 || strlen($to) === 0) { return $dsm; } $dsm[$from][$to] += 1; return $dsm; }); } /** * @param $dependencies * * @return array */ private function createEmptyDsm(DependencySet $dependencies) { return $dependencies->reduce([], function (array $combined, Dependency $dependency) use ($dependencies) { $combined[$dependency->toString()] = array_combine( array_values($dependencies->toArray()), // keys: dependency name array_pad([], $dependencies->count(), 0) // values: [0, 0, 0, ... , 0] ); return $combined; }); } }
<?php declare(strict_types=1); namespace Mihaeu\PhpDependencies\Formatters; use Mihaeu\PhpDependencies\Dependencies\Dependency; use Mihaeu\PhpDependencies\Dependencies\DependencySet; use Mihaeu\PhpDependencies\Dependencies\DependencyMap; class DependencyStructureMatrixBuilder { public function buildMatrix(DependencyMap $dependencies, \Closure $mappers) : array { $emptyDsm = $this->createEmptyDsm($dependencies->mapAllDependencies($mappers)); return $dependencies->reduce($emptyDsm, function (array $dsm, Dependency $from, Dependency $to) use ($mappers) : array { $dsm[$mappers($from)->toString()][$mappers($to)->toString()] += 1; return $dsm; }); } /** * @param $dependencies * * @return array */ private function createEmptyDsm(DependencySet $dependencies) { return $dependencies->reduce([], function (array $combined, Dependency $dependency) use ($dependencies) { $combined[$dependency->toString()] = array_combine( array_values($dependencies->toArray()), // keys: dependency name array_pad([], $dependencies->count(), 0) // values: [0, 0, 0, ... , 0] ); return $combined; }); } }
Fix hashcode generation for existing URLs
# -*- coding: utf-8 -*- import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, db_index=True, null=True) longurl = models.CharField(max_length=1024, unique=True, db_index=True, null=True) views = models.IntegerField(default=0) ip = models.GenericIPAddressField(null=True) data = models.DateTimeField(auto_now_add=True, null=True) def save(self, *args, **kwargs): if not self.pk: if URL.objects.count(): last = URL.objects.latest('id').pk + 1 alphabet = string.digits + string.ascii_lowercase base36 = '' while last != 0: last, i = divmod(last, len(alphabet)) base36 = alphabet[i] + base36 self.hashcode = base36 else: self.hashcode = '1' return super(URL, self).save(*args, **kwargs) def short_url(self, request): return ''.join([ request.scheme, '://', request.get_host(), '/', self.hashcode, ]) def __unicode__(self): return ' - '.join([self.hashcode, self.longurl])
# -*- coding: utf-8 -*- import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, db_index=True, null=True) longurl = models.CharField(max_length=1024, unique=True, db_index=True, null=True) views = models.IntegerField(default=0) ip = models.GenericIPAddressField(null=True) data = models.DateTimeField(auto_now_add=True, null=True) def save(self, *args, **kwargs): if URL.objects.count(): last = URL.objects.latest('id').pk + 1 alphabet = string.digits + string.ascii_lowercase base36 = '' while last != 0: last, i = divmod(last, len(alphabet)) base36 = alphabet[i] + base36 self.hashcode = base36 else: self.hashcode = '1' return super(URL, self).save(*args, **kwargs) def short_url(self, request): return ''.join([ request.scheme, '://', request.get_host(), '/', self.hashcode, ]) def __unicode__(self): return ' - '.join([self.hashcode, self.longurl])
Revert "Added a workaround for abstract models not being handled correctly." This reverts commit a3e44c187b5abfa6d9b360cecc5c1daa746134f5.
# -*- coding: utf-8 -*- from django.db.models import F, Q from django.core.management.base import NoArgsCommand from modeltranslation.settings import DEFAULT_LANGUAGE from modeltranslation.translator import translator from modeltranslation.utils import build_localized_fieldname class Command(NoArgsCommand): help = ('Updates the default translation fields of all or the specified' 'translated application using the value of the original field.') def handle(self, **options): verbosity = int(options['verbosity']) if verbosity > 0: self.stdout.write("Using default language: %s\n" % DEFAULT_LANGUAGE) for model, trans_opts in translator._registry.items(): if model._meta.abstract: continue if verbosity > 0: self.stdout.write("Updating data of model '%s'\n" % model) for fieldname in trans_opts.fields: def_lang_fieldname = build_localized_fieldname( fieldname, DEFAULT_LANGUAGE) # We'll only update fields which do not have an existing value q = Q(**{def_lang_fieldname: None}) field = model._meta.get_field(fieldname) if field.empty_strings_allowed: q |= Q(**{def_lang_fieldname: ""}) model.objects.filter(q).rewrite(False).update(**{def_lang_fieldname: F(fieldname)})
# -*- coding: utf-8 -*- from django.db.models import F, Q from django.core.management.base import NoArgsCommand from modeltranslation.settings import DEFAULT_LANGUAGE from modeltranslation.translator import translator from modeltranslation.utils import build_localized_fieldname class Command(NoArgsCommand): help = ('Updates the default translation fields of all or the specified' 'translated application using the value of the original field.') def handle(self, **options): verbosity = int(options['verbosity']) if verbosity > 0: self.stdout.write("Using default language: %s\n" % DEFAULT_LANGUAGE) for model, trans_opts in translator._registry.items(): if model._meta.abstract: continue if verbosity > 0: self.stdout.write("Updating data of model '%s'\n" % model) for fieldname in trans_opts.fields: def_lang_fieldname = build_localized_fieldname( fieldname, DEFAULT_LANGUAGE) # We'll only update fields which do not have an existing value q = Q(**{def_lang_fieldname: None}) field = model._meta.get_field(fieldname) if field.empty_strings_allowed: q |= Q(**{def_lang_fieldname: ""}) try: model.objects.filter(q).rewrite(False).update( **{def_lang_fieldname: F(fieldname)}) except AttributeError: # FIXME: Workaround for abstract models. See issue #123 for details. model.objects.filter(q).update(**{def_lang_fieldname: F(fieldname)})
Fix URL of locator records in packaged themes
<?php namespace Concrete\Core\Filesystem\FileLocator; use Concrete\Core\Package\PackageList; use Concrete\Core\Page\Theme\Theme; use Illuminate\Filesystem\Filesystem; class ThemeLocation extends AbstractLocation { protected $filesystem; protected $pkgHandle; protected $themeHandle; public function getCacheKey() { return array('theme', $this->themeHandle); } public function __construct(Theme $theme) { $this->themeHandle = $theme->getThemeHandle(); $this->pkgHandle = $theme->getPackageHandle(); } /** * @return mixed */ public function getThemeHandle() { return $this->themeHandle; } public function getPath() { if ($this->pkgHandle) { return DIR_PACKAGES . '/' . $this->pkgHandle . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } else { return DIR_APPLICATION . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } } public function getURL() { if ($this->pkgHandle) { return DIR_REL . '/' . DIRNAME_PACKAGES . '/' . $this->pkgHandle . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } else { return DIR_REL . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } } }
<?php namespace Concrete\Core\Filesystem\FileLocator; use Concrete\Core\Package\PackageList; use Concrete\Core\Page\Theme\Theme; use Illuminate\Filesystem\Filesystem; class ThemeLocation extends AbstractLocation { protected $filesystem; protected $pkgHandle; protected $themeHandle; public function getCacheKey() { return array('theme', $this->themeHandle); } public function __construct(Theme $theme) { $this->themeHandle = $theme->getThemeHandle(); $this->pkgHandle = $theme->getPackageHandle(); } /** * @return mixed */ public function getThemeHandle() { return $this->themeHandle; } public function getPath() { if ($this->pkgHandle) { return DIR_PACKAGES . '/' . $this->pkgHandle . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } else { return DIR_APPLICATION . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } } public function getURL() { if ($this->pkgHandle) { return DIR_REL . '/' . $this->pkgHandle . '/' . DIRNAME_THEMES . $this->themeHandle; } else { return DIR_REL . '/' . DIRNAME_THEMES . '/' . $this->themeHandle; } } }
Add color to asset.name in console output
const chalk = require('chalk'); function composeWebpackOutput(stats) { if (!stats.hasErrors() && !stats.hasWarnings()) { composeSuccessOutput(stats); return; } composeErrorOutput(stats); } function composeSuccessOutput(stats) { console.log(); const assets = Object .keys(stats.compilation.assets) .map(assetName => { return { name: assetName, size: stats.compilation.assets[assetName].size() }; }); assets.forEach(asset => { console.log(` ${chalk.bold.white(asset.name)} ${asset.size} bytes`); }); console.log(); console.log(`> Time: ${stats.endTime - stats.startTime}ms`); console.log(`> ${chalk.bold.green('SUCCESS!')}`); } function composeErrorOutput(stats) { stats.compilation.errors .map(error => formatErrorMessage(error.message)) .forEach(message => { console.log(); console.log(message); }); console.log(`> ${chalk.bold.red('FAILURE!')}`); } function formatErrorMessage(message) { message = message .replace('Module build failed: SyntaxError: ', '') .replace('Module not found: ', ''); const firstLine = message.split('\n')[0]; return message .replace(firstLine, ` ${chalk.bold.red(firstLine)}`) .replace(/\n/g, '\n '); } module.exports = composeWebpackOutput;
const chalk = require('chalk'); function composeWebpackOutput(stats) { if (!stats.hasErrors() && !stats.hasWarnings()) { composeSuccessOutput(stats); return; } composeErrorOutput(stats); } function composeSuccessOutput(stats) { console.log(); const assets = Object .keys(stats.compilation.assets) .map(assetName => { return { name: assetName, size: stats.compilation.assets[assetName].size() }; }); assets.forEach(asset => { console.log(` ${chalk.bold(asset.name)} ${asset.size} bytes`); }); console.log(); console.log(`> Time: ${stats.endTime - stats.startTime}ms`); console.log(`> ${chalk.bold.green('SUCCESS!')}`); } function composeErrorOutput(stats) { stats.compilation.errors .map(error => formatErrorMessage(error.message)) .forEach(message => { console.log(); console.log(message); }); console.log(`> ${chalk.bold.red('FAILURE!')}`); } function formatErrorMessage(message) { message = message .replace('Module build failed: SyntaxError: ', '') .replace('Module not found: ', ''); const firstLine = message.split('\n')[0]; return message .replace(firstLine, ` ${chalk.bold.red(firstLine)}`) .replace(/\n/g, '\n '); } module.exports = composeWebpackOutput;
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use Signed-off-by: Joonas Bergius <[email protected]>
from __future__ import unicode_literals import os import pdb from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session class Model(object): def __repr__(self): cols = self.__mapper__.c.keys() class_name = self.__class__.__name__ items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col in cols]) return '%s(%s)' % (class_name, items) def attrs_dict(self): keys = self.__mapper__.c.keys() attrs = {} for key in keys: attrs[key] = getattr(self, key) return attrs class SQLAlchemy(object): def __init__(self): self.session = self.create_session() self.Model = self.make_declarative_base() @property def engine(self): dburl = os.environ['DATABASE_URL'] return create_engine(dburl) def create_session(self): session = scoped_session(sessionmaker()) session.configure(bind=self.engine) return session def make_declarative_base(self): base = declarative_base(cls=Model) base.query = self.session.query_property() return base def drop_all(self): self.Model.metadata.drop_all(bind=self.engine) def create_all(self): self.Model.metadata.create_all(bind=self.engine) db = SQLAlchemy() all = [db] def rollback(*_): db.session.rollback()
from __future__ import unicode_literals import os import pdb from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session class Model(object): def __repr__(self): cols = self.__mapper__.c.keys() class_name = self.__class__.__name__ items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col in cols]) return '%s(%s)' % (class_name, items) def attrs_dict(self): keys = self.__mapper__.c.keys() attrs = {} for key in keys: attrs[key] = getattr(self, key) return attrs class SQLAlchemy(object): def __init__(self): self.session = self.create_session() self.Model = self.make_declarative_base() @property def engine(self): dburl = os.environ['DATABASE_URL'] return create_engine(dburl) def create_session(self): session = scoped_session(sessionmaker()) session.configure(bind=self.engine) return session def make_declarative_base(self): base = declarative_base(cls=Model) base.query = self.session.query_property() return base db = SQLAlchemy() all = [db] def rollback(*_): db.session.rollback()
Adjust for compatibility with Python 2.5
try: from collections import Mapping except ImportError: # compatibility with Python 2.5 Mapping = dict def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6} >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}} >>> c = merge(a, b) >>> from pprint import pprint; pprint(c) {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}} """ assert quacks_like_dict(a), quacks_like_dict(b) dst = a.copy() stack = [(dst, b)] while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) : stack.append((current_dst[key], current_src[key])) else: current_dst[key] = current_src[key] return dst
import collections def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, collections.Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6} >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}} >>> c = merge(a, b) >>> from pprint import pprint; pprint(c) {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}} """ assert quacks_like_dict(a), quacks_like_dict(b) dst = a.copy() stack = [(dst, b)] while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) : stack.append((current_dst[key], current_src[key])) else: current_dst[key] = current_src[key] return dst
Fix TMN specific site param
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; // The `pathTo()` function is written in ES3 so it's serializable and able to // run in all JavaScript environments. module.exports = function pathTo(routeMap) { return function (routeName, context) { var route = routeMap[routeName], path, keys, i, len, key, param, regex; if (!route) { return ''; } path = route.path; keys = route.keys; if (context && (len = keys.length)) { for (i = 0; i < len; i += 1) { key = keys[i]; param = key.name || key; regex = new RegExp('[:*]' + param + '\\b'); path = path.replace(regex, context[param]); } } // TMN Specific // apply site option if not specified. if(!context.site){ try{ var isServer = typeof window === "undefined"; if(isServer){ context.site = global.appConfig.app.sport; } else { context.site = window.TMNState.site; } } catch(e){ console.error("Failed to apply missing site param to pathTo", e); } } // Replace missing params with empty strings. // pathTo is not correctly handling express optional parameters of the form /blogs/:id/:tag? // lop off the ? off the end of the result return path.replace(/([:*])([\w\-]+)?/g, '').replace(/[?]$/, ''); }; };
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; // The `pathTo()` function is written in ES3 so it's serializable and able to // run in all JavaScript environments. module.exports = function pathTo(routeMap) { return function (routeName, context) { var route = routeMap[routeName], path, keys, i, len, key, param, regex; if (!route) { return ''; } path = route.path; keys = route.keys; if (context && (len = keys.length)) { for (i = 0; i < len; i += 1) { key = keys[i]; param = key.name || key; regex = new RegExp('[:*]' + param + '\\b'); path = path.replace(regex, context[param]); } } // TMN Specific if(!context.site && window && window.TMNState && window.TMNState.site){ context.site = window.TMNState.site; } // Replace missing params with empty strings. // pathTo is not correctly handling express optional parameters of the form /blogs/:id/:tag? // lop off the ? off the end of the result return path.replace(/([:*])([\w\-]+)?/g, '').replace(/[?]$/, ''); }; };
Move this to the bottom...
from django.contrib import admin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() super(ContributorMixin, self).save_model(request, obj, form, change) class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': (('username', 'password'),)}), ('Personal Information', {'fields': (('name', 'email'),)}), ('Important Dates', { 'classes': ('grp-collapse grp-open',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-open',), 'fields': (('is_active', 'is_staff', 'is_superuser'),) }), ('OAuth', { 'classes': ('grp-collapse grp-closed',), 'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration')) }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
from django.contrib import admin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): super(ContributorMixin, self).save_model(request, obj, form, change) if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': (('username', 'password'),)}), ('Personal Information', {'fields': (('name', 'email'),)}), ('Important Dates', { 'classes': ('grp-collapse grp-open',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-open',), 'fields': (('is_active', 'is_staff', 'is_superuser'),) }), ('OAuth', { 'classes': ('grp-collapse grp-closed',), 'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration')) }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
Document class changed for recent model changes.
package de.fh_bielefeld.newsboard.model; import java.util.OptionalDouble; import java.util.OptionalInt; /** * Domain class representing a classification of a document or sentence. * * @author Felix Meyer, Lukas Taake */ public class Classification { private OptionalInt sentenceId = OptionalInt.empty(); private ExternModule externModule; private double value; private OptionalDouble confidence = OptionalDouble.empty(); public OptionalInt getSentenceId() { return sentenceId; } public void setSentenceId(int sentenceId) { this.sentenceId = OptionalInt.of(sentenceId); } public ExternModule getExternModule() { return externModule; } public void setExternModule(ExternModule externModule) { this.externModule = externModule; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public OptionalDouble getConfidence() { return confidence; } public void setConfidence(double confidence) { this.confidence = OptionalDouble.of(confidence); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Classification)) { return false; } Classification that = (Classification) obj; return this.sentenceId.equals(that.sentenceId) && this.externModule.equals(that.externModule); } }
package de.fh_bielefeld.newsboard.model; import java.util.OptionalDouble; import java.util.OptionalInt; /** * Domain class representing a classification of a document or sentence. * * @author Felix Meyer, Lukas Taake */ public class Classification { private OptionalInt sentenceId = OptionalInt.empty(); private OptionalInt documentId = OptionalInt.empty(); private ExternModule externModule; private double value; private OptionalDouble confidence = OptionalDouble.empty(); public OptionalInt getSentenceId() { return sentenceId; } public void setSentenceId(int sentenceId) { this.sentenceId = OptionalInt.of(sentenceId); } public OptionalInt getDocumentId() { return documentId; } public void setDocumentId(int documentId) { this.documentId = OptionalInt.of(documentId); } public ExternModule getExternModule() { return externModule; } public void setExternModule(ExternModule externModule) { this.externModule = externModule; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public OptionalDouble getConfidence() { return confidence; } public void setConfidence(double confidence) { this.confidence = OptionalDouble.of(confidence); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Classification)) { return false; } Classification that = (Classification) obj; return this.documentId.equals(that.documentId) && this.sentenceId.equals(that.sentenceId) && this.externModule.equals(that.externModule); } }
Revert "fixxed controller for login" This reverts commit d3fccddb534ffee732125af1284c0f00708422ae.
var app = angular.module("adminApp", ["ngRoute"]); app.config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'pages/login.html', controller: 'login.Controller.js', controllerAs: 'vm', }) .when('/dashboard', { templateUrl: 'pages/dashboard.html' }) .when('/orders', { templateUrl: 'pages/orders.html' }) .when('/stock', { templateUrl: 'pages/stock.html', controller: 'itemCtrl' }) .when('/main', { templateUrl: 'pages/dashboard.html', controller: 'mainController' }) .when('/newItem', { templateUrl: 'pages/new_item.html' }) .when('/statistics', { templateUrl: 'pages/statistics.html' }) .when('/users', { templateUrl: 'pages/users.html' }) .otherwise({ redirectTo: 'pages/dashboard.html' }); });
var app = angular.module("adminApp", ["ngRoute"]); app.config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'pages/login.html', controller: 'signInController' }) .when('/dashboard', { templateUrl: 'pages/dashboard.html' }) .when('/orders', { templateUrl: 'pages/orders.html' }) .when('/stock', { templateUrl: 'pages/stock.html', controller: 'itemCtrl' }) .when('/main', { templateUrl: 'pages/dashboard.html', controller: 'mainController' }) .when('/newItem', { templateUrl: 'pages/new_item.html' }) .when('/statistics', { templateUrl: 'pages/statistics.html' }) .when('/users', { templateUrl: 'pages/users.html' }) .otherwise({ redirectTo: 'pages/dashboard.html' }); });
Fix webpack server for uri containing /
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', inject: 'body' }); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index.js', devtool: 'source-map', output: { path: path.resolve('dist'), filename: 'app.js', publicPath: '/', }, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader', include: /flexboxgrid/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?sourceMap!sass-loader?sourceMap' }) }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, // sassLoader: { // includePaths: [ 'src/styles' ] // }, devServer: { historyApiFallback: true, }, plugins: [ HtmlWebpackPluginConfig, new ExtractTextPlugin({ filename: 'public/style.css', allChunks: true }) ] };
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', inject: 'body' }); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index.js', devtool: 'source-map', output: { path: path.resolve('dist'), filename: 'app.js' }, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader', include: /flexboxgrid/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?sourceMap!sass-loader?sourceMap' }) }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, // sassLoader: { // includePaths: [ 'src/styles' ] // }, devServer: { historyApiFallback: true, }, plugins: [ HtmlWebpackPluginConfig, new ExtractTextPlugin({ filename: 'public/style.css', allChunks: true }) ] };
LILY-2266: Allow clearing of social media fields with inline editing
angular.module('app.directives').directive('editableLink', editableLink); function editableLink() { return { restrict: 'E', scope: { viewModel: '=', type: '@', field: '@', object: '=?', socialMediaName: '@?', }, templateUrl: 'base/directives/editable_link.html', controller: EditableLinkController, controllerAs: 'el', transclude: true, bindToController: true, }; } EditableLinkController.$inject = []; function EditableLinkController() { var el = this; el.updateViewModel = updateViewModel; activate(); ///// function activate() { if (!el.object) { if (!el.socialMediaName) { el.object = el.viewModel[el.type.toLowerCase()]; } } } function updateViewModel($data) { var patchPromise; var args = {}; if (el.object) { args = { id: el.object.id, }; } args[el.field] = $data; if (el.socialMediaName) { if ($data) { args.name = el.socialMediaName; } else { args.is_deleted = true; } patchPromise = el.viewModel.updateModel(args, el.socialMediaName); } else { patchPromise = el.viewModel.updateModel(args).$promise; } return patchPromise; } }
angular.module('app.directives').directive('editableLink', editableLink); function editableLink() { return { restrict: 'E', scope: { viewModel: '=', type: '@', field: '@', object: '=?', socialMediaName: '@?', }, templateUrl: 'base/directives/editable_link.html', controller: EditableLinkController, controllerAs: 'el', transclude: true, bindToController: true, }; } EditableLinkController.$inject = []; function EditableLinkController() { var el = this; el.updateViewModel = updateViewModel; activate(); ///// function activate() { if (!el.object) { if (!el.socialMediaName) { el.object = el.viewModel[el.type.toLowerCase()]; } } } function updateViewModel($data) { var patchPromise; var args = {}; if (el.object) { args = { id: el.object.id, }; } args[el.field] = $data; if (el.socialMediaName) { args.name = el.socialMediaName; patchPromise = el.viewModel.updateModel(args, el.socialMediaName); } else { patchPromise = el.viewModel.updateModel(args).$promise; } return patchPromise; } }
Use long array syntax to support PHP 5.x.
<?php namespace Vikpe; class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase { const TEST_FILES_DIR = __DIR__.'/file/'; private function getTestFileContents($filename) { return file_get_contents(self::TEST_FILES_DIR.$filename); } public function assertHtmlStringEqualsHtmlString($expect, $actual) { $expectedDom = new \DOMDocument(); $expectedDom->loadHtml($expect); $expectedDom->preserveWhiteSpace = false; $actualDom = new \DOMDocument(); $actualDom->loadHTML($actual); $actualDom->preserveWhiteSpace = false; $this->assertEquals( $expectedDom->saveHTML(), $actualDom->saveHTML() ); } /** * @dataProvider normalizeDataProvider */ public function testNormalizeSimpleHtmlStrings($html, $expect) { $actual = HtmlHeadingNormalizer::normalize($html); $this->assertEquals($expect, $actual); } public function normalizeDataProvider() { return array( array('', ''), array('<p>foo</p>', '<p>foo</p>'), ); } public function testNormalizePromoteHtmlDocument() { $inputHtml = $this->getTestFileContents('document.base1.html'); $normalizedHtml = HtmlHeadingNormalizer::normalize($inputHtml, 3); $expectedHtml = $this->getTestFileContents('document.base1.promote3.html'); $this->assertHtmlStringEqualsHtmlString($expectedHtml, $normalizedHtml); } }
<?php namespace Vikpe; class HtmlHeadingNormalizerTest extends \PHPUnit_Framework_TestCase { const TEST_FILES_DIR = __DIR__.'/file/'; private function getTestFileContents($filename) { return file_get_contents(self::TEST_FILES_DIR.$filename); } public function assertHtmlStringEqualsHtmlString($expect, $actual) { $expectedDom = new \DOMDocument(); $expectedDom->loadHtml($expect); $expectedDom->preserveWhiteSpace = false; $actualDom = new \DOMDocument(); $actualDom->loadHTML($actual); $actualDom->preserveWhiteSpace = false; $this->assertEquals( $expectedDom->saveHTML(), $actualDom->saveHTML() ); } /** * @dataProvider normalizeDataProvider */ public function testNormalizeSimpleHtmlStrings($html, $expect) { $actual = HtmlHeadingNormalizer::normalize($html); $this->assertEquals($expect, $actual); } public function normalizeDataProvider() { return [ ['', ''], ['<p>foo</p>', '<p>foo</p>'], ]; } public function testNormalizePromoteHtmlDocument() { $inputHtml = $this->getTestFileContents('document.base1.html'); $normalizedHtml = HtmlHeadingNormalizer::normalize($inputHtml, 3); $expectedHtml = $this->getTestFileContents('document.base1.promote3.html'); $this->assertHtmlStringEqualsHtmlString($expectedHtml, $normalizedHtml); } }
spec-helper: Add support for function call attribute (&)
window.m = angular.mock.module; window.compileHtml = function(htmlStr, data, parentElement = null) { data = data || {}; var $scope; inject(function($compile, $rootScope) { parentElement = parentElement || document.body; angular.element(parentElement).html(htmlStr); $scope = $rootScope.$new(); angular.extend($scope, data); $compile(parentElement)($scope); $scope.$digest(); }); return $scope; } window.compileDirective = function(directive, attr, parentElement = null) { let attributes = ''; for (let key in attr) { let kebab = _.kebabCase(key); if (key.startsWith('@')) { attributes += ` ${kebab}="{{ data['${key}'] }}"`; } else if (key.startsWith('&')) { attributes += ` ${kebab}="data['${key}']()"`; } else { attributes += ` ${kebab}="data.${key}"`; } } let scope = compileHtml(`<${directive} ${attributes}></${directive}>`, {data: attr}, parentElement); scope.$digest(); return scope; } function angularEquality(first, second) { return angular.equals(first, second); } window.useAngularEquality = function() { beforeEach(function() { jasmine.addCustomEqualityTester(angularEquality); }); } window.waitForPromise = function() { setInterval(()=>{ inject(function($rootScope) { $rootScope.$apply(); }); },0) }
window.m = angular.mock.module; window.compileHtml = function(htmlStr, data, parentElement = null) { data = data || {}; var $scope; inject(function($compile, $rootScope) { parentElement = parentElement || document.body; angular.element(parentElement).html(htmlStr); $scope = $rootScope.$new(); angular.extend($scope, data); $compile(parentElement)($scope); $scope.$digest(); }); return $scope; } window.compileDirective = function(directive, attr, parentElement = null) { let attributes = ''; for (let key in attr) { let kebab = _.kebabCase(key); if (key.startsWith('@')) { attributes += ` ${kebab}="{{ data['${key}'] }}"`; } else { attributes += ` ${kebab}="data.${key}"`; } } let scope = compileHtml(`<${directive} ${attributes}></${directive}>`, {data: attr}, parentElement); scope.$digest(); return scope; } function angularEquality(first, second) { return angular.equals(first, second); } window.useAngularEquality = function() { beforeEach(function() { jasmine.addCustomEqualityTester(angularEquality); }); } window.waitForPromise = function() { setInterval(()=>{ inject(function($rootScope) { $rootScope.$apply(); }); },0) }
Support adding hosts by DNS
import socket from django.core.management.base import BaseCommand, CommandError from django.db.utils import IntegrityError from iptools import validate_ip, validate_cidr, IpRange from hostmonitor.models import Host def resolve_dns(name): return set([x[4][0] for x in socket.getaddrinfo(name, 80)]) class Command(BaseCommand): args = '<target target ...>' help = 'Add the specified hosts or CIDR networks (not network/broadcast)' def add_host(self, ip): h = Host(ip=ip) self.stdout.write("%s adding\n" % ip) try: h.save() except IntegrityError, e: self.stderr.write("%s ERROR, already exists, ignoring\n" % ip) def handle(self, *args, **options): for target in args: if validate_ip(target): self.add_host(target) elif validate_cidr(target): hosts = list(IpRange(target)) print hosts for host in hosts[1:-1]: self.add_host(host) else: hosts = resolve_dns(target) for host in hosts: self.add_host(host) # try: # poll = Poll.objects.get(pk=int(poll_id)) # except Poll.DoesNotExist: # raise CommandError('Poll "%s" does not exist' % poll_id) # # poll.opened = False # poll.save() # # self.stdout.write('Successfully closed poll "%s"\n' % poll_id)
from iptools import validate_ip, validate_cidr, IpRange from django.core.management.base import BaseCommand, CommandError from hostmonitor.models import Host class Command(BaseCommand): args = '<target target ...>' help = 'Add the specified hosts or CIDR networks (not network/broadcast)' def add_host(self, ip): h = Host(ip=ip) self.stdout.write("Adding host %s\n" % ip) h.save() def handle(self, *args, **options): for target in args: if validate_ip(target): self.add_host(target) elif validate_cidr(target): hosts = list(IpRange(target)) print hosts for i in hosts[1:-1]: self.add_host(i) else: self.stderr.write("Invalid host: %s\n" % target) # try: # poll = Poll.objects.get(pk=int(poll_id)) # except Poll.DoesNotExist: # raise CommandError('Poll "%s" does not exist' % poll_id) # # poll.opened = False # poll.save() # # self.stdout.write('Successfully closed poll "%s"\n' % poll_id)
Copy only the participants list instead of using .extend()
'use strict'; angular.module('Teem') .directive('participate', function() { return { controller: [ '$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc', function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) { $scope.participateCopyOn = $attrs.participateCopyOn; $scope.participateCopyOff = $attrs.participateCopyOff; $element.on('click', function($event) { SessionSvc.loginRequired($scope, function() { if ($scope.community.toggleParticipant) { $timeout(function() { $scope.community.toggleParticipant(); }); } else { CommunitiesSvc.find($scope.community.id).then(function(community) { $timeout(function() { community.toggleParticipant(); $scope.community.participants = community.participants; }); }); } }); $event.stopPropagation(); }); }], templateUrl: 'participate.html' }; });
'use strict'; angular.module('Teem') .directive('participate', function() { return { controller: [ '$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc', function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) { $scope.participateCopyOn = $attrs.participateCopyOn; $scope.participateCopyOff = $attrs.participateCopyOff; $element.on('click', function($event) { SessionSvc.loginRequired($scope, function() { if ($scope.community.toggleParticipant) { $timeout(function() { $scope.community.toggleParticipant(); }); } else { CommunitiesSvc.find($scope.community.id).then(function(community) { $timeout(function() { community.toggleParticipant(); angular.extend($scope.community, community); }); }); } }); $event.stopPropagation(); }); }], templateUrl: 'participate.html' }; });
Allow null published_at, fix Validation message
<?php namespace Metrique\Building\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'path' => 'Path', 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id ), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'string', 'url' ], 'meta' => [ 'required', 'json', ], 'params' => [ 'required', 'json', ], 'published_at' => [ 'nullable', 'date', ], ]; } }
<?php namespace Metrique\Building\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Metrique\Building\Rules\AbsoluteUrlPathRule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'published_at' => 'published date', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'path' => [ 'required', 'string', new AbsoluteUrlPathRule, Rule::unique( 'pages', 'path' )->ignore( optional($this->page)->id ), ], 'title' => [ 'required', 'string', ], 'description' => [ 'required', 'string', ], 'image' => [ 'string', 'url' ], 'meta' => [ 'required', 'json', ], 'params' => [ 'required', 'json', ], 'published_at' => [ 'date', ], ]; } }
Bump version to fix build
from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pyvault', version='1.8.1', description='Python password manager', long_description=long_description, author='Gabriel Bordeaux', author_email='[email protected]', url='https://github.com/gabfl/vault', license='MIT', packages=['vault', 'vault.lib'], package_dir={'vault': 'src'}, install_requires=['pycryptodome', 'pyperclip', 'tabulate', 'argparse', 'passwordgenerator'], # external dependencies entry_points={ 'console_scripts': [ 'vault = vault.vault:main', ], }, classifiers=[ # see https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Topic :: Security', 'Topic :: Security :: Cryptography', 'License :: OSI Approved :: MIT License', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Natural Language :: English', #'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python', 'Development Status :: 4 - Beta', #'Development Status :: 5 - Production/Stable', ], )
from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pyvault', version='1.8', description='Python password manager', long_description=long_description, author='Gabriel Bordeaux', author_email='[email protected]', url='https://github.com/gabfl/vault', license='MIT', packages=['vault', 'vault.lib'], package_dir={'vault': 'src'}, install_requires=['pycryptodome', 'pyperclip', 'tabulate', 'argparse', 'passwordgenerator'], # external dependencies entry_points={ 'console_scripts': [ 'vault = vault.vault:main', ], }, classifiers=[ # see https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Topic :: Security', 'Topic :: Security :: Cryptography', 'License :: OSI Approved :: MIT License', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Natural Language :: English', #'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python', 'Development Status :: 4 - Beta', #'Development Status :: 5 - Production/Stable', ], )
Add more rules in the documentation router.
<?php use Hoa\Router; $router = new Router\Http(); $router ->get( 'c', '(?<vendor>)/(?<chapter>)\.html' ) ->get( 'hack', '(?<chapter>)\.html' ) ->get( 'full', '/(?<vendor>)/(?<chapter>)\.html' ) ->_get( 'literature', 'http://hoa-project.net/Literature\.html' ) ->_get( 'learn', 'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html' ) ->get( '_resource', 'http://static.hoa-project.net/(?<resource>)' ) ->_get( 'central_resource', 'http://central.hoa-project.net/Resource/(?<path>)' ) ->_get( 'board', 'https://waffle.io/hoaproject/(?<repository>)' ) ->_get( 'git', 'http://git.hoa-project.net/(?<repository>).git/' ) ->_get( 'github', 'https://github.com/hoaproject/(?<repository>)' ) ->_get( 'research', 'http://hoa-project.net/Literature/Research/(?<article>[\w\d]+)\.pdf', 'Literature\Research' ) ->_get( 'event', 'http://hoa-project.net/Event/(?<event>\w+)\.html', 'Generic' ) ->_get( 'keynote', 'http://keynote.hoa-project.net/(?<keynote>)' );
<?php use Hoa\Router; $router = new Router\Http(); $router ->get( 'c', '(?<vendor>)/(?<chapter>)\.html' ) ->get( 'hack', '(?<chapter>)\.html' ) ->get( 'full', '/(?<vendor>)/(?<chapter>)\.html' ) ->_get( 'literature', 'http://hoa-project.net/Literature\.html' ) ->_get( 'learn', 'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html' ) ->get( '_resource', 'http://static.hoa-project.net/(?<resource>)' ) ->_get( 'central_resource', 'http://central.hoa-project.net/Resource/(?<path>)' ) ->_get( 'board', 'https://waffle.io/hoaproject/(?<repository>)' ) ->_get( 'git', 'http://git.hoa-project.net/(?<repository>).git/' ) ->_get( 'github', 'https://github.com/hoaproject/(?<repository>)' );
Handle playback of multiple tracks
define([ 'libs/bean', 'libs/bonzo', 'libs/qwery', 'utils/loadJSON', 'sc' ], function( bean, bonzo, qwery, loadJSON ) { var sound; return { init: function() { loadJSON('/soundcloud-keys.json', function(data) { SC.initialize({ client_id: data.id }); }); this.bindEvents(); }, bindEvents: function() { bean.on(document.body, 'click', '.track', function(e) { this.playTrack(e.currentTarget.dataset.trackId); }.bind(this)); }, playTrack: function(trackId) { el = bonzo(qwery('#track-' + trackId)); current = bonzo(qwery('.is-playing')); if (sound) { // Check if it's the same track if (sound.url.split('/')[4] == trackId) { if (el.hasClass('is-playing')) { sound.pause(); el.removeClass('is-playing'); } else { sound.play(); el.addClass('is-playing'); } // If not, destory old track and start again } else { sound.stop(); current.removeClass('is-playing'); sound = undefined; this.playTrack(trackId); } // First time playing of new track } else { SC.stream('/tracks/' + trackId, function(obj){ obj.play(); sound = obj; el.addClass('is-playing'); }); } } } });
define([ 'libs/bean', 'libs/bonzo', 'libs/qwery', 'utils/loadJSON', 'sc' ], function( bean, bonzo, qwery, loadJSON ) { var sound; return { init: function() { loadJSON('/soundcloud-keys.json', function(data) { SC.initialize({ client_id: data.id }); }); this.bindEvents(); }, bindEvents: function() { bean.on(document.body, 'click', '.track', function(e) { this.playTrack(e.currentTarget.dataset.trackId); }.bind(this)); }, playTrack: function(trackId) { el = qwery('#track-' + trackId); if (sound) { if (bonzo(el).hasClass('is-playing')) { sound.pause(); bonzo(el).removeClass('is-playing'); } else { sound.play(); bonzo(el).addClass('is-playing'); } } else { SC.stream('/tracks/' + trackId, function(obj){ obj.play(); sound = obj; bonzo(el).addClass('is-playing'); }); } } } });
Add status fallback when an error does not expose one
"use strict"; function createDefaultFormatter() { return function defaultFormatter(ctx, errors) { ctx.body = {}; if (errors && errors.length) { ctx.status = 500; if (errors.length === 1) { ctx.status = errors[0].status || ctx.status; } ctx.body['ok'] = 0; ctx.body['status'] = ctx.status; ctx.body['errors'] = errors.map((error) => { return error.message; }); } else { ctx.body['ok'] = 1; } ctx.body['status'] = ctx.status; if (ctx.result != null) { ctx.body['result'] = ctx.result; } } } module.exports = function (options) { options = options || {}; const fn = options.formatter || createDefaultFormatter(); return function formatter(ctx, next) { const self = this; return next().then(function () { fn(ctx); }).catch(function (err) { var errors; if (Array.isArray(err)) { errors = err; } else { errors = [ err ]; } fn(ctx, errors); for (var i = 0; i < errors.length; i++) { ctx.app.emit('error', errors[i], self); } }); } }; module.exports.defaultFormatter = createDefaultFormatter;
"use strict"; function createDefaultFormatter() { return function defaultFormatter(ctx, errors) { ctx.body = {}; if (errors && errors.length) { ctx.status = 500; if (errors.length === 1) { ctx.status = errors[0].status; } ctx.body['ok'] = 0; ctx.body['status'] = ctx.status; ctx.body['errors'] = errors.map((error) => { return error.message; }); } else { ctx.body['ok'] = 1; } ctx.body['status'] = ctx.status; if (ctx.result != null) { ctx.body['result'] = ctx.result; } } } module.exports = function (options) { options = options || {}; const fn = options.formatter || createDefaultFormatter(); return function formatter(ctx, next) { const self = this; return next().then(function () { fn(ctx); }).catch(function (err) { var errors; if (Array.isArray(err)) { errors = err; } else { errors = [ err ]; } fn(ctx, errors); for (var i = 0; i < errors.length; i++) { ctx.app.emit('error', errors[i], self); } }); } }; module.exports.defaultFormatter = createDefaultFormatter;
Use correct m2m join table name in LatestCommentsFeed git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
Fix arrays and add path support
/** * @file * Text reporter */ var Colors = require('colors/safe'); var _ = require('lodash'); /** * Text reporter * @param {Object} validationData * @param {Object} [options] * @param {Boolean} options.noColors * @returns {String} */ module.exports = function textReporter(validationData, options) { options = options || {}; function mapItem(item) { return [ item.line ? 'At line: ' + item.line + ', column: ' + item.column : 'At path: ' + item.path, item.type, item.text ].join('\t'); } function prepareString(str, color) { return options.noColors ? str : Colors[color](str); } return _([ prepareString('Validation results', 'magenta'), prepareString('Feed:', 'green'), validationData.feedXml, '', validationData.errors.length ? [ prepareString('Errors:', 'red'), _.map(validationData.errors, mapItem).join('\n'), '' ] : null, validationData.warnings.length ? [ prepareString('Warnings:', 'blue'), _.map(validationData.warnings, mapItem).join('\n'), '' ] : null, validationData.info.length ? [ prepareString('Info:', 'yellow'), _.map(validationData.info, mapItem).join('\n'), '' ] : null, validationData.isValid ? prepareString('All correct', 'green') : null ]) .flatten() .filter(function (item) { return item !== null; }) .run() .join('\n'); };
/** * @file * Text reporter */ var Colors = require('colors/safe'); var _ = require('lodash'); /** * Text reporter * @param {Object} validationData * @param {Object} [options] * @param {Boolean} options.noColors * @returns {String} */ module.exports = function textReporter(validationData, options) { options = options || {}; function mapItem(item) { return [ 'At line: ' + item.line + ', column: ' + item.column, item.type, item.text ].join('\t'); } function prepareString(str, color) { return options.noColors ? str : Colors[color](str); } return _([ prepareString('Validation results', 'magenta'), prepareString('Feed:', 'green'), validationData.feedXml, '', validationData.errors.length ? [ prepareString('Errors:', 'red'), _.map(validationData.errors, mapItem), '' ] : null, validationData.warnings.length ? [ prepareString('Warnings:', 'blue'), _.map(validationData.warnings, mapItem), '' ] : null, validationData.info.length ? [ prepareString('Info:', 'yellow'), _.map(validationData.info, mapItem), '' ] : null, validationData.isValid ? prepareString('All correct', 'green') : null ]) .flatten() .filter(function (item) { return item !== null; }) .run() .join('\n'); };
Convert everything to unicode strings before inserting to DB
#-*- coding: utf-8 -*- from email.MIMEBase import MIMEBase from django.core.mail.backends.base import BaseEmailBackend from database_email_backend.models import Email, Attachment class DatabaseEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): if not email_messages: return for message in email_messages: email = Email.objects.create( from_email = u'%s' % message.from_email, to_emails = u', '.join(message.to), cc_emails = u', '.join(message.cc), bcc_emails = u', '.join(message.bcc), all_recipients = u', '.join(message.recipients()), subject = u'%s' % message.subject, body = u'%s' % message.body, raw = u'%s' % message.message().as_string() ) for attachment in message.attachments: if isinstance(attachment, tuple): filename, content, mimetype = attachment elif isinstance(attachment, MIMEBase): filename = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype = None else: continue Attachment.objects.create( email=email, filename=filename, content=content, mimetype=mimetype )
#-*- coding: utf-8 -*- from email.MIMEBase import MIMEBase from django.core.mail.backends.base import BaseEmailBackend from database_email_backend.models import Email, Attachment class DatabaseEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): if not email_messages: return for message in email_messages: email = Email.objects.create( from_email = message.from_email, to_emails = ', '.join(message.to), cc_emails = ', '.join(message.cc), bcc_emails = ', '.join(message.bcc), all_recipients = ', '.join(message.recipients()), subject = message.subject, body = message.body, raw = message.message().as_string() ) for attachment in message.attachments: if isinstance(attachment, tuple): filename, content, mimetype = attachment elif isinstance(attachment, MIMEBase): filename = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype = None else: continue Attachment.objects.create( email=email, filename=filename, content=content, mimetype=mimetype )
Add comments; and run task before watching
var gulp = require("gulp"); var sass = require("gulp-sass"); var nano = require('gulp-cssnano'); /* Build civil.css */ gulp.task("sass", function () { gulp.src("./sass/**/*.scss") .pipe(sass({ //outputStyle: "compressed", includePaths: ["./bower_components/bourbon/app/assets/stylesheets/"] })) .pipe(nano()) .pipe(gulp.dest("./dist")); }); gulp.task("sass:watch", ["sass"], function () { gulp.watch("./sass/**/*.scss", ["sass"]); }); /* Build docs */ gulp.task("sass:docs", function () { gulp.src("./docs/sass/**/*.scss") .pipe(sass({ //outputStyle: "compressed", includePaths: [ "./bower_components/bourbon/app/assets/stylesheets", "./sass"] })) .pipe(nano()) .pipe(gulp.dest("./docs/css")); }); gulp.task("sass:docs:watch", ["sass:docs"], function () { gulp.watch("./docs/sass/**/*.scss", ["sass:docs"]); }); /* Copy civil.css latest build for docs */ gulp.task("copy:docs", function () { gulp.src(["./dist/civil.css", "./dist/syntax.css"]) .pipe(gulp.dest("./docs/css")); gulp.src("dist/civil.js") .pipe(gulp.dest("./docs/js")); }); gulp.task("default", ["build", "docs"]); gulp.task("build", ["sass"]); gulp.task("docs", ["copy:docs", "sass:docs"]);
var gulp = require("gulp"); var sass = require("gulp-sass"); var nano = require('gulp-cssnano'); gulp.task("sass", function () { gulp.src("./sass/**/*.scss") .pipe(sass({ //outputStyle: "compressed", includePaths: ["./bower_components/bourbon/app/assets/stylesheets/"] })) .pipe(nano()) .pipe(gulp.dest("./dist")); }); gulp.task("sass:watch", function () { gulp.watch("./sass/**/*.scss", ["sass"]); }); gulp.task("sass:docs", function () { gulp.src("./docs/sass/**/*.scss") .pipe(sass({ //outputStyle: "compressed", includePaths: [ "./bower_components/bourbon/app/assets/stylesheets", "./sass"] })) .pipe(nano()) .pipe(gulp.dest("./docs/css")); }); gulp.task("sass:docs:watch", function () { gulp.watch("./docs/sass/**/*.scss", ["sass:docs"]); }); gulp.task("copy:docs", function () { gulp.src(["./dist/civil.css", "./dist/syntax.css"]) .pipe(gulp.dest("./docs/css")); gulp.src("dist/civil.js") .pipe(gulp.dest("./docs/js")); }); gulp.task("default", ["build", "docs"]); gulp.task("build", ["sass"]); gulp.task("docs", ["copy:docs", "sass:docs"]);
Attach metadata to the right function
define(['../is', '../array/last', '../functional'], function(is, last, functional) { var map = functional.map; var filter = functional.filter; var forEach = functional.forEach; function annotate() { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); var doc; var invariants; if(is.string(last(args))) { doc = args.pop(); } forEach(function(arg) { if(!is.fn(arg)) console.warn('Invariant' + arg + 'is not a function!'); }, args); invariants = args; var ret = function() { var curArgs = arguments; var info = map(function(arg, i) { var curArg = curArgs[i]; if(is.fn(arg)) { if(arg(curArg)) return { state: 'ok', arg: curArg }; else return { state: 'error', info: 'Parameter check failed!', arg: curArg }; } else { return { state: 'error', info: 'Parameter checker is not a function!', arg: curArg }; } }, args); var isOk = filter(function(k) { return k.state == 'ok'; }, info).length == info.length; if(isOk) return fn.apply(undefined, curArgs); else console.warn(info); }; ret._doc = doc; ret._invariants = invariants; return ret; } return annotate; });
define(['../is', '../array/last', '../functional'], function(is, last, functional) { var map = functional.map; var filter = functional.filter; var forEach = functional.forEach; function annotate() { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); if(is.string(last(args))) { fn._doc = args.pop(); } forEach(function(arg) { if(!is.fn(arg)) console.warn('Invariant' + arg + 'is not a function!'); }, args); fn._invariants = args; return function() { var curArgs = arguments; var info = map(function(arg, i) { var curArg = curArgs[i]; if(is.fn(arg)) { if(arg(curArg)) return { state: 'ok', arg: curArg }; else return { state: 'error', info: 'Parameter check failed!', arg: curArg }; } else { return { state: 'error', info: 'Parameter checker is not a function!', arg: curArg }; } }, args); var isOk = filter(function(k) { return k.state == 'ok'; }, info).length == info.length; if(isOk) return fn.apply(undefined, curArgs); else console.warn(info); }; } return annotate; });
Set grunt watch use default task to generate .min.js file
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';', sourceMap: true }, dist: { src: ['src/**/*.js'], dest: 'assets/<%= pkg.name %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n', sourceMap: true }, dist: { files: { 'assets/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { files: ['Gruntfile.js', 'src/**/*.js'], options: { // options here to override JSHint defaults trailing: true, globals: { browser: true, console: true } } }, watch: { files: ['<%= jshint.files %>'], tasks: ['default'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';', sourceMap: true }, dist: { src: ['src/**/*.js'], dest: 'assets/<%= pkg.name %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n', sourceMap: true }, dist: { files: { 'assets/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { files: ['Gruntfile.js', 'src/**/*.js'], options: { // options here to override JSHint defaults trailing: true, globals: { browser: true, console: true } } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'concat'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); };
Fix wrong module name in migrations
from django.utils.encoding import smart_str from kitsune.products.models import Product from taggit.models import Tag from kitsune.wiki.models import Document tags_to_migrate = { # source tag -> product 'firefox': ['firefox'], 'sync': ['firefox', 'mobile'], 'persona': ['firefox'], 'desktop': ['firefox'], 'fxhome': ['firefox', 'mobile'], 'firefox-10': ['firefox'], 'firefox-602': ['firefox'], 'firefox-50': ['firefox'], 'android': ['mobile'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the document and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the documents tagged with tag. for doc in Document.objects.filter(tags__slug=tag.slug): doc.products.add(product) print 'Added product "%s" to document "%s"' % ( smart_str(product.slug), smart_str(doc.title)) total_affected += 1 print 'Done! (%d)' % total_affected
from django.utils.encoding import smart_str from kitsune.products.models import Product from kitsune.taggit.models import Tag from kitsune.wiki.models import Document tags_to_migrate = { # source tag -> product 'firefox': ['firefox'], 'sync': ['firefox', 'mobile'], 'persona': ['firefox'], 'desktop': ['firefox'], 'fxhome': ['firefox', 'mobile'], 'firefox-10': ['firefox'], 'firefox-602': ['firefox'], 'firefox-50': ['firefox'], 'android': ['mobile'], 'mobile': ['mobile'] } def assert_equals(a, b): assert a == b, '%s != %s' % (a, b) def run(): # Get all the tags to migrate. tags = list(Tag.objects.filter(slug__in=tags_to_migrate.keys())) total_affected = 0 # For each tag, get the document and add a product for it. for tag in tags: for product_slug in tags_to_migrate[tag.slug]: product = Product.objects.get(slug=product_slug) # Assign the product to all the documents tagged with tag. for doc in Document.objects.filter(tags__slug=tag.slug): doc.products.add(product) print 'Added product "%s" to document "%s"' % ( smart_str(product.slug), smart_str(doc.title)) total_affected += 1 print 'Done! (%d)' % total_affected
Store roles and permissions in user session instead of reloading them each request
var model = require('./model'); var middleware = module.exports = {}; middleware.loadRoles = function (req, res, next) { if (req.user && !req.session.user) { model.role.model.find({'_id': { $in: req.user.roles }}, function (err, docs) { if (err) next(); var roles = []; var permissions = []; for (var d in docs) { var role = docs[d]; roles.push(role.name); if (role.permissions) { for (var permission in role.permissions) { if (permissions.indexOf(permission) !== 0) { permissions.push(permission); } } } } var user = { id: req.user._id, username: req.user.username, roles: roles, permissions: permissions } // add user info to session req.session.user = user; next(); }) } else { // remove user info from session req.session.user = null; next(); } };
var model = require('./model'); var middleware = module.exports = {}; middleware.loadRoles = function (req, res, next) { if (req.user) { model.role.model.find({'_id': { $in: req.user.roles }}, function (err, docs) { if (err) next(); var roles = []; var permissions = []; for (var d in docs) { var role = docs[d]; roles.push(role.name); if (role.permissions) { for (var permission in role.permissions) { if (permissions.indexOf(permission) !== 0) { permissions.push(permission); } } } } if (!req.bauhaus) req.bauhaus = {}; req.bauhaus.roles = roles; req.bauhaus.permissions = permissions; next(); }) } else { next(); } };
Fix match time not showing for fixtures
import React, { Component } from "react"; import { formatTime } from "../../common/util/date"; export default class extends Component { render() { const { match } = this.props; if (match.live || match.ended) { return ( <span className={match.live && "live"}> {match.ft && (!match.et || match.ps) && ( <span> {match.ft[0]}&nbsp;-&nbsp;{match.ft[1]} </span> )} {match.et && !match.ps && ( <span> {match.et[0]}&nbsp;-&nbsp;{match.et[1]} aet </span> )} {match.ps && ( <span> {" "} p.{match.ps[0]}-{match.ps[1]} </span> )} </span> ); } if (match.postponed) { return <abbr title="Postponed">PSTP</abbr>; } if (match.suspended) { return <abbr title="Suspended">SUSP</abbr>; } if (match.cancelled) { return <abbr title="Cencelled">CANC</abbr>; } if (match.date && match.time) { return <span>{formatTime(match.date, match.time)}</span>; } return null; } }
import React, { Component } from "react"; import { formatTime } from "../../common/util/date"; export default class extends Component { render() { const { match } = this.props; if (match.fixture) { return match.time && <span>{formatTime(match.date, match.time)}</span>; } if (match.live || match.ended) { return ( <span className={match.live && "live"}> {match.ft && (!match.et || match.ps) && ( <span> {match.ft[0]}&nbsp;-&nbsp;{match.ft[1]} </span> )} {match.et && !match.ps && ( <span> {match.et[0]}&nbsp;-&nbsp;{match.et[1]} aet </span> )} {match.ps && ( <span> {" "} p.{match.ps[0]}-{match.ps[1]} </span> )} </span> ); } if (match.postponed) { return <abbr title="Postponed">PSTP</abbr>; } if (match.suspended) { return <abbr title="Suspended">SUSP</abbr>; } if (match.cancelled) { return <abbr title="Cencelled">CANC</abbr>; } return null; } }