text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update to include User ID in result
''' This module extracts the student IDs from the collection certificates_generatedcertificate of the students who completed the course and achieved a certificate. The ids are then used to extract the usernames of the course completers Usage: python course_completers.py ''' from collections import defaultdict from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_user') collection = connection.get_access_to_collection() completers = collection['certificates_generatedcertificate'].find({'status' : 'downloadable'}) result = [] for document in completers: user_document = collection['auth_user'].find_one({"id" : document['user_id']}) result.append([user_document['id'],user_document['username'], document['name'], document['grade']]) output = CSV(result, ['User ID','Username', 'Name', 'Grade'], output_file='course_completers.csv') output.generate_csv()
''' This module extracts the student IDs from the collection certificates_generatedcertificate of the students who completed the course and achieved a certificate. The ids are then used to extract the usernames of the course completers Usage: python course_completers.py ''' from collections import defaultdict from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_user') collection = connection.get_access_to_collection() completers = collection['certificates_generatedcertificate'].find({'status' : 'downloadable'}) result = [] for document in completers: user_document = collection['auth_user'].find_one({"id" : document['user_id']}) result.append([user_document['username'], document['name'], document['grade']]) output = CSV(result, ['Username', 'Name', 'Grade'], output_file='course_completers.csv') output.generate_csv()
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
# -*- coding: utf-8 -*- from rest_framework import permissions from website.models import Node, NodeLog from api.nodes.permissions import ContributorOrPublic from api.base.utils import get_object_or_error class ContributorOrPublicForLogs(permissions.BasePermission): def has_object_permission(self, request, view, obj): assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj) if obj._backrefs.get('logged'): for node_id in obj._backrefs['logged']['node']['logs']: node = get_object_or_error(Node, node_id, display_name='node') if ContributorOrPublic().has_object_permission(request, view, node): return True if getattr(obj, 'node'): if ContributorOrPublic().has_object_permission(request, view, obj.node): return True return False
# -*- coding: utf-8 -*- from rest_framework import permissions from website.models import Node, NodeLog from api.nodes.permissions import ContributorOrPublic from api.base.utils import get_object_or_error class ContributorOrPublicForLogs(permissions.BasePermission): def has_object_permission(self, request, view, obj): assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj) for node_id in obj._backrefs['logged']['node']['logs']: node = get_object_or_error(Node, node_id, display_name='node') if ContributorOrPublic().has_object_permission(request, view, node): return True return False
Move strict inside for browser use don't want to leak stuff ...
/* global ftUtils, moment */ var app = angular.module('flowList', ['ui.grid']); app.controller('flowListCtrl', function($scope, $http) { 'use strict'; $http.get('/json/rawFlowsForLast/5/minutes') .success(function(data, status, headers, config) { var retList = []; data.hits.hits.forEach(function(element, index, array) { var flowRecord = { Src_Address: ftUtils.inet_ntoa(element._source.ipv4_src_addr), Dst_Address: ftUtils.inet_ntoa(element._source.ipv4_dst_addr), Packets: element._source.in_pkts, Bytes: element._source.in_bytes, Time: moment(element._source.timestamp).format('YYYY-MM-DD HH:mm:ss') }; retList.push(flowRecord); }); $scope.flows = retList; }) .error(function(data, status, headers) { console.warn('doh'); }); });
/* global ftUtils, moment */ 'use strict'; var app = angular.module('flowList', ['ui.grid']); app.controller('flowListCtrl', function($scope, $http) { $http.get('/json/rawFlowsForLast/5/minutes') .success(function(data, status, headers, config) { var retList = []; data.hits.hits.forEach(function(element, index, array) { var flowRecord = { Src_Address: ftUtils.inet_ntoa(element._source.ipv4_src_addr), Dst_Address: ftUtils.inet_ntoa(element._source.ipv4_dst_addr), Packets: element._source.in_pkts, Bytes: element._source.in_bytes, Time: moment(element._source.timestamp).format('YYYY-MM-DD HH:mm:ss') }; retList.push(flowRecord); }); $scope.flows = retList; }) .error(function(data, status, headers) { console.warn('doh'); }); });
Add flavour text for assembling burger
import Entity, { printMessage, action, time, state } from "Entity.js"; import { addItem, removeItem, isInInventory } from 'inventory.js'; export class Prep extends Entity { name() { return 'prep area'; } actions() { return [ action("Cut potatoes.", () => { printMessage("You cut the potato into wedges. You have changed their shape!"); addItem("potato wedges"); }), action("Get patty.", () => { printMessage("You grab a raw patty"); addItem("raw patty"); }), action("Assemble burger.", () => { printMessage("You make a burger from the grilled patty and a bun. Order up!"); removeItem("grilled patty") addItem("burger") }, () => isInInventory("grilled patty")) ]; } } export default new Prep();
import Entity, { printMessage, action, time, state } from "Entity.js"; import { addItem, removeItem, isInInventory } from 'inventory.js'; export class Prep extends Entity { name() { return 'prep area'; } actions() { return [ action("Cut potatoes.", () => { printMessage("You cut the potato into wedges. You have changed their shape!"); addItem("potato wedges"); }), action("Get patty.", () => { printMessage("You grab a raw patty"); addItem("raw patty"); }), action("Assemble burger.", () => { removeItem("grilled patty") addItem("burger") }, () => isInInventory("grilled patty")) ]; } } export default new Prep();
Remove options var Boot parent service with credentials Change url
<?php namespace PhpWatson\Sdk\Language\ToneAnalyser\V3; use PhpWatson\Sdk\Service; class ToneAnalyserService extends Service { /** * Base url for the service * * @var string */ protected $url = "https://gateway.watsonplatform.net/tone-analyzer/api"; /** * API service version * * @var string */ protected $version = 'v3'; /** * ToneAnalyserService constructor * * @param $username string The service api username * @param $password string The service api password */ public function __construct($username, $password) { parent::__construct($username, $password); } /** * Analyzes the tone of a piece of text * * @return mixed|\Psr\Http\Message\ResponseInterface */ public function plainText($textToAnalyse, $version='2016-05-19') { return $this->client->request('GET', $this->getMountedUrl().'/tone', ['query' => ['version' => $version, 'text' => $textToAnalyse]]); } }
<?php namespace PhpWatson\Sdk\Language\ToneAnalyser\V3; use PhpWatson\Sdk\Service; class ToneAnalyserService extends Service { /** * {@inheritdoc} */ protected $url = "https://watson-api-explorer.mybluemix.net/tone-analyzer/api"; /** * {@inheritdoc} */ protected $version = 'v3'; /** * {@inheritdoc} */ protected $options = []; /** * Analyzes the tone of a piece of text * * @return mixed|\Psr\Http\Message\ResponseInterface */ public function plainText($textToAnalyse, $version='2016-05-19') { return $this->client->request('GET', $this->getMountedUrl().'/tone', ['query' => ['version' => $version, 'text' => $textToAnalyse]]); } }
Patch binfile name only when needed in open_archive
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import contextlib from pkg_resources import iter_entry_points from ..opener import open_fs from ..opener._errors import Unsupported from ..path import basename @contextlib.contextmanager def open_archive(fs_url, archive): it = iter_entry_points('fs.archive.open_archive') entry_point = next((ep for ep in it if archive.endswith(ep.name)), None) if entry_point is None: raise Unsupported( 'unknown archive extension: {}'.format(archive)) archive_opener = entry_point.load() # if not isinstance(archive_fs, base.ArchiveFS): # raise TypeError('bad entry point') try: fs = open_fs(fs_url) binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w') if not hasattr(binfile, 'name'): binfile.name = basename(archive) archive_fs = archive_opener(binfile) yield archive_fs finally: archive_fs.close() binfile.close() if fs is not fs_url: # close the fs if we opened it fs.close()
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import contextlib from pkg_resources import iter_entry_points from ..opener import open_fs from ..opener._errors import Unsupported from ..path import basename @contextlib.contextmanager def open_archive(fs_url, archive): it = iter_entry_points('fs.archive.open_archive') entry_point = next((ep for ep in it if archive.endswith(ep.name)), None) if entry_point is None: raise Unsupported( 'unknown archive extension: {}'.format(archive)) archive_opener = entry_point.load() # if not isinstance(archive_fs, base.ArchiveFS): # raise TypeError('bad entry point') try: fs = open_fs(fs_url) binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w') binfile.name = basename(archive) archive_fs = archive_opener(binfile) yield archive_fs finally: archive_fs.close() binfile.close() if fs is not fs_url: # close the fs if we opened it fs.close()
Include exception when trying send_sms function.
#! /usr/bin/env python3 """sendsms.py: program for sending SMS.""" from sys import argv from googlevoice import Voice from googlevoice.util import LoginError # E-mail SMTP settings with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password: password = email_password.read().strip() # Google voice accaount for nicorellius.mail: (503) 850-8390 # USERNAME = 'nicorellius.mail@gmail.com' USERNAME = 'nicorellius.mail' PASSWORD = password def send(number, message): voice = Voice() try: voice.login(USERNAME, PASSWORD) except LoginError as e: print("Error logging into SMS server: {0}".format(str(e))) # number = input('Number to send message to: ') # message = input('Message text: ') try: voice.send_sms(number, message) except Exception as e: print('Phone number or message error, skipping SMS: {0}'.format(str(e))) print('Continuing without sending SMS...') # For testing this program can be run at the terminal with args if __name__ == '__main__': if len(argv) != 3: print('Incorrect number of arguments.') else: send(argv[1], argv[2])
#! /usr/bin/env python3 """sendsms.py: program for sending SMS.""" from sys import argv from googlevoice import Voice from googlevoice.util import LoginError # E-mail SMTP settings with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password: password = email_password.read().strip() def send(number, message): # (503) 850-8390 USERNAME = 'nicorellius.mail' PASSWORD = password voice = Voice() try: voice.login(USERNAME, PASSWORD) except LoginError as e: print("Error logging into SMS server: {0}".format(str(e))) # number = input('Number to send message to: ') # message = input('Message text: ') # try: voice.send_sms(number, message) # except Exception as e: # print('Phone number or message error, skipping SMS: {0}'.format(str(e))) # print('Continuing without sending SMS...') # For testing this program can be run at the terminal with args if __name__ == '__main__': if len(argv) != 3: print('Incorrect number of arguments.') else: send(argv[1], argv[2])
Fix bug in class Article, volume should be string type
from neomodel import (StructuredNode, StringProperty, IntegerProperty, ArrayProperty, RelationshipTo, RelationshipFrom) # Create your models here. class Article(StructuredNode): title = StringProperty() journal = StringProperty() year = IntegerProperty() volume = StringProperty() authors = RelationshipFrom('Author', 'AUTHORED') class Author(StructuredNode): name = StringProperty() articles = RelationshipTo('Article', 'AUTHORED') def __str__(self): # Call str function here since sometimes the object might not # found in the database... # Python sucks return "<Author: " + str(self.name) + ">" def __repr__(self): return "<Author: " + repr(self.name) + ">" def __hash__(self): """ We use name of the author as the hash value """ return hash(self.name) def __cmp__(self, other): return cmp(self.name, other.name) def toDict(self): return { "name": self.name }
from neomodel import (StructuredNode, StringProperty, IntegerProperty, ArrayProperty, RelationshipTo, RelationshipFrom) # Create your models here. class Article(StructuredNode): title = StringProperty() journal = StringProperty() year = IntegerProperty() volume = IntegerProperty() authors = RelationshipFrom('Author', 'AUTHORED') class Author(StructuredNode): name = StringProperty() articles = RelationshipTo('Article', 'AUTHORED') def __str__(self): # Call str function here since sometimes the object might not # found in the database... # Python sucks return "<Author: " + str(self.name) + ">" def __repr__(self): return "<Author: " + repr(self.name) + ">" def __hash__(self): """ We use name of the author as the hash value """ return hash(self.name) def __cmp__(self, other): return cmp(self.name, other.name) def toDict(self): return { "name": self.name }
Delete the inputs after send the message
var base_url_prod="http://147.83.7.157:8080" var App = angular.module('messages', []); App.controller('controller1', ['$scope', '$http', function($scope, $http) { var refresh = function() { $http.get(base_url_prod+'/messages/carlos').success(function (response) { console.log("Acabo de recibir los msg"); console.log(response); $scope.messages = response; }); } refresh(); $scope.sendMessage = function() { console.log("ANTES DE ENVIARLO AL SERVIDOR;") console.log($scope.message); $http.post(base_url_prod+'/addmessage', $scope.message).success(function(response) { console.log($scope.message); console.log("RESPUESTA"); console.log(response); $scope.message=""; refresh(); }); }; }]);
var base_url_prod="http://147.83.7.157:8080" var App = angular.module('messages', []); App.controller('controller1', ['$scope', '$http', function($scope, $http) { var refresh = function() { $http.get(base_url_prod+'/messages/carlos').success(function (response) { console.log("Acabo de recibir los msg"); console.log(response); $scope.messages = response; }); } refresh(); $scope.sendMessage = function() { console.log("ANTES DE ENVIARLO AL SERVIDOR;") console.log($scope.message); $http.post(base_url_prod+'/addmessage', $scope.message).success(function(response) { console.log($scope.message); console.log("RESPUESTA"); console.log(response); refresh(); }); }; }]);
:wrench: Tweak img alt in LoginContainer
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { get } from 'axios'; import FlintLogo from 'components/FlintLogo'; import './LoginContainer.scss'; export default class LoginContainer extends Component { static propTypes = { children: PropTypes.object.isRequired, } state = { siteLogo: null, isFetching: true } componentWillMount() { document.body.classList.add('body--grey'); } componentDidMount() { get('/admin/api/site').then(({ data }) => { this.setState({ siteLogo: data.siteLogo, isFetching: false }); }); } componentWillUnmount() { document.body.classList.remove('body--grey'); } render() { const { siteLogo, isFetching } = this.state; const { children } = this.props; if (isFetching) return null; return ( <div className="login"> {siteLogo ? <img className="login__img" src={`/public/assets/${siteLogo.filename}`} alt={siteLogo.filename} /> : <FlintLogo width={140} height={80} />} {children} <Link to="/fp" className="login__forgot">Forgot your password?</Link> {siteLogo && <FlintLogo poweredBy width={100} height={25} />} </div> ); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { get } from 'axios'; import FlintLogo from 'components/FlintLogo'; import './LoginContainer.scss'; export default class LoginContainer extends Component { static propTypes = { children: PropTypes.object.isRequired, } state = { siteLogo: null, isFetching: true } componentWillMount() { document.body.classList.add('body--grey'); } componentDidMount() { get('/admin/api/site').then(({ data }) => { this.setState({ siteLogo: data.siteLogo, isFetching: false }); }); } componentWillUnmount() { document.body.classList.remove('body--grey'); } render() { const { siteLogo, isFetching } = this.state; const { children } = this.props; if (isFetching) return null; return ( <div className="login"> {siteLogo ? <img className="login__img" src={`/public/assets/${siteLogo.filename}`} alt="Hello!" /> : <FlintLogo width={140} height={80} />} {children} <Link to="/fp" className="login__forgot">Forgot your password?</Link> {siteLogo && <FlintLogo poweredBy width={100} height={25} />} </div> ); } }
Improve mongo logging, so we only log unexpected disconnects. This cleans things up a bit so normal shutdown doesn't spew mongo disconnect errors.
'use strict'; var logger = require('./logger'), mongoose = require('mongoose'); // Log unexpected events. var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error']; events.forEach(function(event) { mongoose.connection.on(event, function(error) { var logEvent = true; if(event === 'disconnecting') { mongoose.expectedCloseInProgress = true; } if(mongoose.expectedCloseInProgress) { if(event === 'disconnecting' || event === 'disconnected' || event === 'close') { logEvent = false; } } if(event === 'close') { mongoose.expectedCloseInProgress = false; } if(logEvent) { logger.error('Mongo event: ' + event, error); } }); }); module.exports = function(callback) { var config = require('api-umbrella-config').global(); // Connect to mongo using mongoose. // // Note: For this application, we don't particularly need an ODM like // Mongoose, and the lower-level mongodb driver would meet our needs. // However, when using the standalone driver, we were experiencing // intermittent mongo connection drops in staging and production // environments. I can't figure out how to reproduce the original issue in a // testable way, so care should be taken if switching how mongo connects. See // here for more details: https://github.com/NREL/api-umbrella/issues/17 mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback); };
'use strict'; var logger = require('./logger'), mongoose = require('mongoose'); // Log unexpected events. var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error']; events.forEach(function(event) { mongoose.connection.on(event, function() { logger.warning('Mongo '+ event, arguments); }); }); module.exports = function(callback) { var config = require('api-umbrella-config').global(); // Connect to mongo using mongoose. // // Note: For this application, we don't particularly need an ODM like // Mongoose, and the lower-level mongodb driver would meet our needs. // However, when using the standalone driver, we were experiencing // intermittent mongo connection drops in staging and production // environments. I can't figure out how to reproduce the original issue in a // testable way, so care should be taken if switching how mongo connects. See // here for more details: https://github.com/NREL/api-umbrella/issues/17 mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback); };
Hide http warning on localhost
(function () { 'use strict'; /** * @ngdoc function * @name passmanApp.controller:MainCtrl * @description * # MainCtrl * Controller of the passmanApp */ angular.module('passmanApp') .controller('MainCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) { $scope.selectedVault = false; $scope.http_warning_hidden = true; if ($location.$$protocol === 'http' && $location.$$host !== 'localhost' && $location.$host !== '127.0.0.1') { $scope.using_http = true; $scope.http_warning_hidden = false; } $rootScope.setHttpWarning = function (state) { $scope.http_warning_hidden = state; }; $rootScope.$on('app_menu', function (evt, shown) { $scope.app_sidebar = shown; }); $rootScope.$on('logout', function () { $scope.selectedVault = false; }); }]); }());
(function () { 'use strict'; /** * @ngdoc function * @name passmanApp.controller:MainCtrl * @description * # MainCtrl * Controller of the passmanApp */ angular.module('passmanApp') .controller('MainCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) { $scope.selectedVault = false; $scope.http_warning_hidden = true; if ($location.$$protocol === 'http') { $scope.using_http = true; $scope.http_warning_hidden = false; } $rootScope.setHttpWarning = function (state) { $scope.http_warning_hidden = state; }; $rootScope.$on('app_menu', function (evt, shown) { $scope.app_sidebar = shown; }); $rootScope.$on('logout', function () { $scope.selectedVault = false; }); }]); }());
Add the submit function to the last button Etc..
var count = 1; $(document).ready(function() { var b = $(".bottom-arrow"); var u = $(".up-arrow"); b.click(function(e) { if ($(".slide" + (+count + 1)).length) { count++; goToByScroll("slide" + count); b.html('<span class="arrow-bounce">&#x25BC;</span>'); u.html('<span class="arrow-bounce">&#x25B2;</span>'); } else { $("#submitnarrative").submit; } if(!($(".slide" + (+count+1)).length)) { b.html('<span class="arrow-bounce">&#x276d;</span>'); } }); u.click(function(e) { if (count > 1) { count--; goToByScroll("slide" + count); b.html('<span class="arrow-bounce">&#x25BC;</span>'); u.html('<span class="arrow-bounce">&#x25B2;</span>'); } else { } if (count == 1){ u.html('<span class="arrow-bounce">&#x27b0;</span>'); } }); })
var count = 1; $(document).ready(function() { var b = $(".bottom-arrow"); var u = $(".up-arrow"); b.click(function(e) { if ($(".slide" + (+count + 1)).length) { count++; goToByScroll("slide" + count); b.html('<span class="arrow-bounce">&#x25BC;</span>'); u.html('<span class="arrow-bounce">&#x25B2;</span>'); } else { } if(!($(".slide" + (+count+1)).length)) { b.html('<span class="arrow-bounce">&#x276d;</span>'); } }); u.click(function(e) { if (count > 1) { count--; goToByScroll("slide" + count); b.html('<span class="arrow-bounce">&#x25BC;</span>'); u.html('<span class="arrow-bounce">&#x25B2;</span>'); } else { } if (count == 1){ u.html('<span class="arrow-bounce">&#x27b0;</span>'); } }); })
Add input_pattern instead of min_pattern_length Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.input_pattern = '[^. \t0-9]\.\w*' self.is_bytepos = True def get_complete_api(self, findstart): complete_api = self.vim.vars['deoplete#sources#go'] if complete_api == 'gocode': return self.vim.call('gocomplete#Complete', findstart, 0) elif complete_api == 'vim-go': return self.vim.call('go#complete#Complete', findstart, 0) else: return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'") def get_complete_position(self, context): return self.get_complete_api(1) def gather_candidates(self, context): return self.get_complete_api(0)
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.min_pattern_length = 0 self.is_bytepos = True def get_complete_api(self, findstart): complete_api = self.vim.vars['deoplete#sources#go'] if complete_api == 'gocode': return self.vim.call('gocomplete#Complete', findstart, 0) elif complete_api == 'vim-go': return self.vim.call('go#complete#Complete', findstart, 0) else: return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'") def get_complete_position(self, context): return self.get_complete_api(1) def gather_candidates(self, context): return self.get_complete_api(0)
Fix bug caused by giving post detail view a new name
from django.conf.urls import url, include from rest_framework import routers import service.authors.views import service.friendrequest.views import service.users.views import service.nodes.views import service.posts.views router = routers.DefaultRouter() router.register(r'users', service.users.views.UserViewSet) router.register(r'nodes', service.nodes.views.NodeViewSet) router.register(r'author', service.authors.views.AuthorViewSet, base_name="author") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^author/posts/', service.posts.views.AllPostsViewSet.as_view({"get": "list"}), name='all-posts-list'), url(r'^', include(router.urls)), url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^friendrequest/', service.friendrequest.views.friendrequest, name='friend-request'), url(r'^posts/', service.posts.views.PublicPostsList.as_view(), name='public-posts-list'), url(r'^posts/(?P<pk>[0-9a-z\\-]+)/', service.posts.views.AllPostsViewSet.as_view({"get": "retrieve"}), name='post-detail'), url(r'^author/(?P<pk>[0-9a-z\\-]+)/posts/', service.posts.views.AuthorPostsList.as_view(), name='author-posts-list'), ]
from django.conf.urls import url, include from rest_framework import routers import service.authors.views import service.friendrequest.views import service.users.views import service.nodes.views import service.posts.views router = routers.DefaultRouter() router.register(r'users', service.users.views.UserViewSet) router.register(r'nodes', service.nodes.views.NodeViewSet) router.register(r'author', service.authors.views.AuthorViewSet, base_name="author") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^author/posts/', service.posts.views.AllPostsViewSet.as_view({"get": "list"}), name='all-posts-list'), url(r'^', include(router.urls)), url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^friendrequest/', service.friendrequest.views.friendrequest, name='friend-request'), url(r'^posts/', service.posts.views.PublicPostsList.as_view(), name='public-posts-list'), url(r'^posts/(?P<pk>[0-9a-z\\-]+)/', service.posts.views.AllPostsViewSet.as_view({"get": "retrieve"}), name='all-posts-detail'), url(r'^author/(?P<pk>[0-9a-z\\-]+)/posts/', service.posts.views.AuthorPostsList.as_view(), name='author-posts-list'), ]
Remove shapes command until it's ready
import os from setuptools import find_packages, setup import sys PY2 = sys.version_info[0] == 2 # Get version with open(os.path.join('tilezilla', 'version.py')) as f: for line in f: if line.find('__version__') >= 0: version = line.split("=")[1].strip() version = version.strip('"').strip("'") continue install_requires = [ 'click', 'click_plugins', 'numpy', 'GDAL', 'rasterio', 'shapely', 'clover', 'beautifulsoup4', 'lxml', 'pyyaml', 'jsonschema', 'sqlalchemy', 'sqlalchemy-utils', ] if PY2: install_requires += ['futures'] entry_points = ''' [console_scripts] tilez=tilezilla.cli.main:cli [tilez.commands] ingest=tilezilla.cli.ingest:ingest spew=tilezilla.cli.spew:spew db=tilezilla.cli.db:db ''' setup( name='tilezilla', version=version, packages=find_packages(), package_data={'tilezilla': ['data/*']}, include_package_data=True, install_requires=install_requires, entry_points=entry_points )
import os from setuptools import find_packages, setup import sys PY2 = sys.version_info[0] == 2 # Get version with open(os.path.join('tilezilla', 'version.py')) as f: for line in f: if line.find('__version__') >= 0: version = line.split("=")[1].strip() version = version.strip('"').strip("'") continue install_requires = [ 'click', 'click_plugins', 'numpy', 'GDAL', 'rasterio', 'shapely', 'clover', 'beautifulsoup4', 'lxml', 'pyyaml', 'jsonschema', 'sqlalchemy', 'sqlalchemy-utils', ] if PY2: install_requires += ['futures'] entry_points = ''' [console_scripts] tilez=tilezilla.cli.main:cli [tilez.commands] ingest=tilezilla.cli.ingest:ingest spew=tilezilla.cli.spew:spew shapes=tilezilla.cli.info:shapes db=tilezilla.cli.db:db ''' setup( name='tilezilla', version=version, packages=find_packages(), package_data={'tilezilla': ['data/*']}, include_package_data=True, install_requires=install_requires, entry_points=entry_points )
Add improvement from eneff that makes program terminate more cleanly
// Code from my dotGo.eu 2014 presentation // // Copyright (c) 2014 John Graham-Cumming // // Implement a factory and a task. Call run() on your factory. package main import ( "bufio" "log" "os" "sync" ) type task interface { process() print() } type factory interface { make(line string) task } func run(f factory) { var wg sync.WaitGroup in := make(chan task) wg.Add(1) go func() { s := bufio.NewScanner(os.Stdin) for s.Scan() { in <- f.make(s.Text()) } if s.Err() != nil { log.Fatalf("Error reading STDIN: %s", s.Err()) } close(in) wg.Done() }() out := make(chan task) for i := 0; i < 1000; i++ { wg.Add(1) go func() { for t := range in { t.process() out <- t } wg.Done() }() } go func() { wg.Wait() close(out) }() for t := range out { t.print() } } func main() { // run(&myFactory{}) }
// Code from my dotGo.eu 2014 presentation // // Copyright (c) 2014 John Graham-Cumming // // Implement a factory and a task. Call run() on your factory. package main import ( "bufio" "log" "os" "sync" ) type task interface { process() print() } type factory interface { make(line string) task } func run(f factory) { var wg sync.WaitGroup in := make(chan task) wg.Add(1) go func() { s := bufio.NewScanner(os.Stdin) for s.Scan() { in <- f.make(s.Text()) } if s.Err() != nil { log.Fatalf("Error reading STDIN: %s", s.Err()) } close(in) wg.Done() }() out := make(chan task) go func() { for t := range out { t.print() } }() for i := 0; i < 1000; i++ { wg.Add(1) go func() { for t := range in { t.process() out <- t } wg.Done() }() } wg.Wait() close(out) } func main() { // run(&myFactory{}) }
Revert "Disable Django-CMS test on Django 1.10+" Django CMS tests should work now with Django 1.10 and 1.11 too, since the Django CMS version 3.4.5 supports them. This reverts commit fcfe2513fc8532dc2212a254da42d75048e76de7.
from django.contrib.auth.models import AnonymousUser from django.utils.crypto import get_random_string import pytest from cms import api from cms.page_rendering import render_page from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin from form_designer.models import FormDefinition, FormDefinitionField @pytest.mark.django_db def test_cms_plugin_renders_in_cms_page(rf): fd = FormDefinition.objects.create( mail_to='test@example.com', mail_subject='Someone sent you a greeting: {{ test }}' ) field = FormDefinitionField.objects.create( form_definition=fd, name='test', label=get_random_string(), field_class='django.forms.CharField', ) page = api.create_page("test", "page.html", "en") ph = page.get_placeholders()[0] api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd) request = rf.get("/") request.user = AnonymousUser() request.current_page = page response = render_page(request, page, "fi", "test") response.render() content = response.content.decode("utf8") assert field.label in content assert "<form" in content
import django from django.contrib.auth.models import AnonymousUser from django.utils.crypto import get_random_string import pytest from cms import api from cms.page_rendering import render_page from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin from form_designer.models import FormDefinition, FormDefinitionField @pytest.mark.django_db def test_cms_plugin_renders_in_cms_page(rf): if django.VERSION >= (1, 10): pytest.xfail('This test is broken in Django 1.10+') fd = FormDefinition.objects.create( mail_to='test@example.com', mail_subject='Someone sent you a greeting: {{ test }}' ) field = FormDefinitionField.objects.create( form_definition=fd, name='test', label=get_random_string(), field_class='django.forms.CharField', ) page = api.create_page("test", "page.html", "en") ph = page.get_placeholders()[0] api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd) request = rf.get("/") request.user = AnonymousUser() request.current_page = page response = render_page(request, page, "fi", "test") response.render() content = response.content.decode("utf8") assert field.label in content assert "<form" in content
Handle selectBy for profile items. PL-11101.
package com.amee.domain; import java.util.Date; public class ProfileItemsFilter extends LimitFilter { private Date startDate = new Date(); private Date endDate = null; /** * Setting this to 'start' will only include items which start during the query window. * Setting 'end' will include only items which end during the window. * The default behaviour is to include any item that intersects the query window. */ private String selectBy; // TODO: Handle mode (prorata) @Override public int getResultLimitDefault() { return 50; } @Override public int getResultLimitMax() { return 100; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { if (startDate != null) { this.startDate = startDate; } } public String getSelectBy() { return selectBy; } public void setSelectBy(String selectBy) { this.selectBy = selectBy; } }
package com.amee.domain; import java.util.Date; public class ProfileItemsFilter extends LimitFilter { private Date startDate = new Date(); private Date endDate = null; @Override public int getResultLimitDefault() { return 50; } @Override public int getResultLimitMax() { return 100; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { if (startDate != null) { this.startDate = startDate; } } }
Resolve some issues bringing the new candidates chart into master
var TopicChartsView = Backbone.View.extend({ initialize: function() { this.$el = $("#charts-container"); this.template = JST["templates/topic-charts/topicChartsTemplate"]; }, render: function() { this.$el.html(this.template({ charts: this.collection })); if (this.collection[0].collection.options.topicId == 1) { drawDatamap(this.collection[0].attributes[0]); InitLineGraph(this.collection[1].attributes.responses); $("#line-graph-container").hide(); var timeSlider = new TimeSlider(); timeSlider.render(); this.$el.find("#slider").on("slide", this.updateChartData.bind(this)); this.$el.find(".ui-tabs-panel").on("click", this.toggleTab) } else { candidateLineGraph(this.collection); } }, updateChartData: function(event, ui) { $("#map-container").html(""); drawDatamap(this.collection[0].attributes[30 - ui.value]); }, toggleTab: function(event, ui) { event.preventDefault(); $("div ul a li").removeClass("active"); $(".charts").hide() var link = $(this.parentElement).attr("href") $(this).addClass("active"); $(link).show(); } })
var TopicChartsView = Backbone.View.extend({ initialize: function() { this.$el = $("#charts-container"); this.template = JST["templates/topic-charts/topicChartsTemplate"]; }, render: function() { this.$el.html(this.template({ charts: this.collection })); if (this.collection.topicId == 1) { drawDatamap(this.collection[0].attributes[0]); InitLineGraph(this.collection[1].attributes.responses); $("#line-graph-container").hide(); var timeSlider = new TimeSlider(); timeSlider.render(); this.$el.find("#slider").on("slide", this.updateChartData.bind(this)); this.$el.find(".ui-tabs-panel").on("click", this.toggleTab) } else { candidateLineGraph(this.collection); } }, updateChartData: function(event, ui) { $("#map-container").html(""); drawDatamap(this.collection[0].attributes[30 - ui.value].attributes); }, toggleTab: function(event, ui) { event.preventDefault(); $("div ul a li").removeClass("active"); $(".charts").hide() var link = $(this.parentElement).attr("href") $(this).addClass("active"); $(link).show(); } })
Move delay to virtual scheduler method
import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' import { merge } from 'rxjs/observable/merge' import { delay } from 'rxjs/operator/delay' import { takeUntil } from 'rxjs/operator/takeUntil' import { share } from 'rxjs/operator/share' const makeVirtualEmission = (scheduler, value, delay) => { return new Observable(observer => { scheduler.schedule(() => { observer.next(value) observer.complete() }, delay, value) }) } const makeVirtualStream = (scheduler, diagram) => { const { emissions, completion } = diagram const partials = emissions.map(({ x, d }) => ( makeVirtualEmission(scheduler, d, x) )) const completion$ = of(null)::delay(completion, scheduler) const emission$ = merge(...partials) ::takeUntil(completion$) ::share() return emission$ } export default makeVirtualStream
import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' import { merge } from 'rxjs/observable/merge' import { delay } from 'rxjs/operator/delay' import { takeUntil } from 'rxjs/operator/takeUntil' import { share } from 'rxjs/operator/share' const makeVirtualEmission = (scheduler, value) => { return new Observable(observer => { scheduler.schedule(() => { observer.next(value) }) }) } const makeVirtualStream = (scheduler, diagram) => { const { emissions, completion } = diagram const partials = emissions.map(({ x, d }) => ( makeVirtualEmission(scheduler, d) ::delay(x, scheduler) )) const completion$ = of(null)::delay(completion, scheduler) const emission$ = merge(...partials) ::takeUntil(completion$) ::share() return emission$ } export default makeVirtualStream
Add check to ensure that the input has been parsed.
// Test for actor system parser. var code = "actor ScriptConsole(inStream, outStream, errStream){\n" + "var reader = IO.LineReader(inStream);\n"+ "var outWriter = IO.TextWriter(outStream);\n"+ "var errWriter = IO.TextWriter(errStream);\n"+ "lineIn <- reader.lineOut;\n"+ "input lineIn (cmd)\n"+ "{\n"+ "var result = safeEval (line);\n"+ "if (result.ok)\n"+ "outWriter.textIn ('> ' + result.value);\n"+ "else\n"+ "errWriter.textIn ('! ' + result.error);\n"+ "}}\n"; var parseResult = asParse (code); assert (parseResult != null, "Input not parsed!"); result = true;
// Test for actor system parser. var code = "actor ScriptConsole(inStream, outStream, errStream){\n" + "var reader = IO.LineReader(inStream);\n"+ "var outWriter = IO.TextWriter(outStream);\n"+ "var errWriter = IO.TextWriter(errStream);\n"+ "lineIn <- reader.lineOut;\n"+ "input lineIn (cmd)\n"+ "{\n"+ "var result = safeEval (line);\n"+ "if (result.ok)\n"+ "outWriter.textIn ('> ' + result.value);\n"+ "else\n"+ "errWriter.textIn ('! ' + result.error);\n"+ "}}\n"; var parseResult = asParse (code); result = true;
Fix mock to import app from cli
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
Add newline to the end of the file
<?php namespace ActiveCollab\DatabaseStructure\Test; use ActiveCollab\DatabaseStructure\Field\Scalar\BooleanField; /** * @package ActiveCollab\DatabaseStructure\Test */ class BooleanFieldTest extends TestCase { /** * @expectedException \LogicException */ public function testExceptionWhenBooleanFieldIsUnique() { (new BooleanField('should_not_be_required'))->unique(); } /** * Test if default value is false */ public function testDefaultValueIsFalse() { $this->assertFalse((new BooleanField('is_he_a_pirate'))->getDefaultValue()); } /** * Test if default value can be changed to NULL */ public function testDefaultValueCanBeChagnedToNull() { $this->assertNull((new BooleanField('should_be_null_by_default'))->defaultValue(null)->getDefaultValue()); } }
<?php namespace ActiveCollab\DatabaseStructure\Test; use ActiveCollab\DatabaseStructure\Field\Scalar\BooleanField; /** * @package ActiveCollab\DatabaseStructure\Test */ class BooleanFieldTest extends TestCase { /** * @expectedException \LogicException */ public function testExceptionWhenBooleanFieldIsUnique() { (new BooleanField('should_not_be_required'))->unique(); } /** * Test if default value is false */ public function testDefaultValueIsFalse() { $this->assertFalse((new BooleanField('is_he_a_pirate'))->getDefaultValue()); } /** * Test if default value can be changed to NULL */ public function testDefaultValueCanBeChagnedToNull() { $this->assertNull((new BooleanField('should_be_null_by_default'))->defaultValue(null)->getDefaultValue()); } }
Add product_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-c1c968b6c0a6dd356a1ae7bc971a2daa2356a46d
{ "name" : "Products & Pricelists", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Inventory Control", "depends" : ["base"], "init_xml" : [], "demo_xml" : ["product_demo.xml"], "description": """ This is the base module to manage products and pricelists in Tiny ERP. Products support variants, different pricing methods, suppliers information, make to stock/order, different unit of measures, packagins and properties. Pricelists supports: * Multiple-level of discount (by product, category, quantities) * Compute price based on different criterions: * Other pricelist, * Cost price, * List price, * Supplier price, ... Pricelists preferences by product and/or partners. Print product labels with barcodes. """, "update_xml" : ["product_data.xml","product_report.xml", "product_view.xml", "pricelist_view.xml","product_security.xml"], "active": False, "installable": True }
{ "name" : "Products & Pricelists", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Inventory Control", "depends" : ["base"], "init_xml" : [], "demo_xml" : ["product_demo.xml"], "description": """ This is the base module to manage products and pricelists in Tiny ERP. Products support variants, different pricing methods, suppliers information, make to stock/order, different unit of measures, packagins and properties. Pricelists supports: * Multiple-level of discount (by product, category, quantities) * Compute price based on different criterions: * Other pricelist, * Cost price, * List price, * Supplier price, ... Pricelists preferences by product and/or partners. Print product labels with barcodes. """, "update_xml" : ["product_data.xml","product_report.xml", "product_view.xml", "pricelist_view.xml"], "active": False, "installable": True }
Fix apollo client in SSR mode
import { ApolloClient, InMemoryCache } from 'apollo-boost'; import { createUploadLink } from 'apollo-upload-client'; import fetch from 'isomorphic-unfetch'; let apolloClient = null; let isBrowser = typeof window !== 'undefined'; function create(initialState) { // TODO: server-side requests must have an absolute URI. We should find a way // to make this part of the project config, seems highly opinionated here const uriHost = !isBrowser ? 'http://localhost:3000' : ''; const uri = `${uriHost}/admin/api`; return new ApolloClient({ connectToDevTools: isBrowser, ssrMode: !isBrowser, link: createUploadLink({ uri, fetch }), cache: new InMemoryCache().restore(initialState || {}), }); } export default function initApollo(initialState) { // Make sure to create a new client for every server-side request so that data // isn't shared between connections (which would be bad) if (!isBrowser) { return create(initialState); } // Reuse client on the client-side if (!apolloClient) { apolloClient = create(initialState); } return apolloClient; }
import { ApolloClient, InMemoryCache } from 'apollo-boost'; import { createUploadLink } from 'apollo-upload-client'; import fetch from 'isomorphic-unfetch'; let apolloClient = null; let isBrowser = typeof window !== 'undefined'; function create(initialState) { return new ApolloClient({ connectToDevTools: isBrowser, ssrMode: !isBrowser, link: createUploadLink({ uri: '/admin/api', fetch }), cache: new InMemoryCache().restore(initialState || {}), }); } export default function initApollo(initialState) { // Make sure to create a new client for every server-side request so that data // isn't shared between connections (which would be bad) if (!isBrowser) { return create(initialState); } // Reuse client on the client-side if (!apolloClient) { apolloClient = create(initialState); } return apolloClient; }
Fix the tinyInteger default value on MySQL
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIncidentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('incidents', function(Blueprint $table) { $table->increments('id'); $table->tinyInteger('component')->default(1); $table->string('name'); $table->tinyInteger('status')->default(1); $table->longText('message'); $table->timestamps(); $table->softDeletes(); $table->index('component'); $table->index('status'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('incidents'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIncidentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('incidents', function(Blueprint $table) { $table->increments('id'); $table->tinyInteger('component')->default(1); $table->string('name'); $table->tinyInteger('status', 1)->default(1); $table->longText('message'); $table->timestamps(); $table->softDeletes(); $table->index('component'); $table->index('status'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('incidents'); } }
QS-969: Fix missing menu icon in UserPage top left place
import React, { PropTypes, Component } from 'react'; import TopLeftMenuLink from '../ui/TopLeftMenuLink'; import RegularTopTitle from '../ui/RegularTopTitle'; import TopRightUserIcons from './TopRightUserIcons'; export default class UserTopNavbar extends Component { static propTypes = { centerText: PropTypes.string }; render() { return ( <div className="navbar"> <div id="navbar-inner" className="navbar-inner"> <div className="row"> <TopLeftMenuLink /> <RegularTopTitle text={this.props.centerText}/> <TopRightUserIcons/> </div> </div> </div> ); } }
import React, { PropTypes, Component } from 'react'; import TopLeftIcon from '../ui/TopLeftIcon'; import RegularTopTitle from '../ui/RegularTopTitle'; import TopRightUserIcons from './TopRightUserIcons'; export default class UserTopNavbar extends Component { static propTypes = { centerText: PropTypes.string }; render() { return ( <div className="navbar"> <div id="navbar-inner" className="navbar-inner"> <div className="row"> <TopLeftIcon icon={'left-arrow'}/> <RegularTopTitle text={this.props.centerText}/> <TopRightUserIcons/> </div> </div> </div> ); } }
Move from props to state
import React from 'react'; class ApplicationPreviewContainer extends React.Component { constructor(props) { super(props); this.state = { previewUrl: 'http://localhost:8000' }; } render() { return ( <div> <div className="input-group mb-3"> <input type="text" className="form-control" placeholder="URL" value={this.state.previewUrl} onChange={(e) => this.handlePreviewUrlChange(e)} /> <div className="input-group-append"> <button className="btn btn-outline-secondary" type="button" onClick={(e) => this.handlePreviewGo(e)}>Go</button> </div> </div> <iframe width="100%" height="500" title="Preview" ref={(iframe) => this.previewIframe = iframe} onLoad={(e) => this.handlePreviewChange(e)} src="http://localhost:8000"></iframe> </div> ); } handlePreviewUrlChange(ev) { this.setState({previewUrl: ev.target.value}); } handlePreviewChange(ev) { try { let url = ev.target.contentWindow.location.toString(); this.setState({previewUrl: url}); } catch(e) { // Nothing here. } } handlePreviewGo() { this.previewIframe.src = this.previewUrl; } } export default ApplicationPreviewContainer;
import PropTypes from 'prop-types'; import React from 'react'; class ApplicationPreviewContainer extends React.Component { constructor(props) { super(props); this.state = { previewUrl: props.previewUrl || 'http://localhost:8000' }; } render() { return ( <div> <div className="input-group mb-3"> <input type="text" className="form-control" placeholder="URL" ref={(input) => this.locationInput = input} value={this.props.previewUrl} /> <div className="input-group-append"> <button className="btn btn-outline-secondary" type="button" onClick={(e) => this.handlePreviewGo(e)}>Go</button> </div> </div> <iframe width="100%" height="500" title="Preview" ref={(iframe) => this.previewIframe = iframe} onLoad={(e) => this.handlePreviewChange(e)} src="http://localhost:8000"></iframe> </div> ); } handlePreviewChange(ev) { try { let url = ev.target.contentWindow.location.toString(); this.setState({previewUrl: url}); } catch(e) { // Nothing here. } } handlePreviewGo() { this.previewIframe.src = this.locationInput.value; } } ApplicationPreviewContainer.propTypes = { previewUrl: PropTypes.string }; export default ApplicationPreviewContainer;
Stop opening devtools on launch
const electron = require('electron') const app = electron.app // Module to control application life. const BrowserWindow = electron.BrowserWindow // Module to create native browser window. let mainWindow function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600, show: false }) mainWindow.loadURL(`file://${__dirname}/index.html`) // mainWindow.webContents.openDevTools() // Open the DevTools. mainWindow.on('closed', function () { mainWindow = null }) } app.on('ready', () => { createWindow(); mainWindow.once('ready-to-show', () => { mainWindow.show() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { if (mainWindow === null) { createWindow() } }) require('./main-process/file-selection')
const electron = require('electron') const app = electron.app // Module to control application life. const BrowserWindow = electron.BrowserWindow // Module to create native browser window. let mainWindow function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600, show: false }) mainWindow.loadURL(`file://${__dirname}/index.html`) mainWindow.webContents.openDevTools() // Open the DevTools. mainWindow.on('closed', function () { mainWindow = null }) } app.on('ready', () => { createWindow(); mainWindow.once('ready-to-show', () => { mainWindow.show() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { if (mainWindow === null) { createWindow() } }) require('./main-process/file-selection')
Add PMs to service creation.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.boot; import foam.core.*; import foam.nanos.*; import foam.nanos.pm.PM; public class NSpecFactory implements XFactory { NSpec spec_; ProxyX x_; boolean isCreating_ = false; public NSpecFactory(ProxyX x, NSpec spec) { x_ = x; spec_ = spec; } public Object create(X x) { // Avoid infinite recursions when creating services if ( isCreating_ ) { return null; } isCreating_ = true; Object ns = null; PM pm = new PM(this.getClass(), spec_ == null ? "-" : spec_.getName()); try { ns = spec_.createService(x_.getX()); if ( ns instanceof ContextAware ) ((ContextAware) ns).setX(x_.getX()); if ( ns instanceof NanoService ) ((NanoService) ns).start(); } catch (Throwable t) { // TODO: LOG t.printStackTrace(); } finally { pm.log(x_.getX()); isCreating_ = false; } return ns; } }
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.boot; import foam.core.*; import foam.nanos.*; public class NSpecFactory implements XFactory { NSpec spec_; ProxyX x_; public NSpecFactory(ProxyX x, NSpec spec) { x_ = x; spec_ = spec; } public Object create(X x) { Object ns = null; try { ns = spec_.createService(x_.getX()); if ( ns instanceof ContextAware ) ((ContextAware) ns).setX(x_.getX()); if ( ns instanceof NanoService ) ((NanoService) ns).start(); } catch (Throwable t) { // TODO: LOG t.printStackTrace(); } return ns; } }
Fix bug causing header not to be regenerated
<?php namespace ZeroRPC; class ChannelException extends \RuntimeException {} class Channel { const PROTOCOL_VERSION = 3; private static $channels = array(); protected $id; protected $envelope; protected $socket; private $callbacks = array(); public function __construct($id, $envelope, $socket) { $this->id = $id; $this->envelope = $envelope; $this->socket = $socket; self::$channels[$id] = $this; } public static function get($id) { if (isset(self::$channels[$id])) return self::$channels[$id]; } public static function count() { return count(self::$channels); } public function register($callback) { array_push($this->callbacks, $callback); } // Called when the channel receives an event public function invoke(Event $event) { if ($event->name === '_zpc_hb') { // Send heartbeat response return $this->send('_zpc_hb'); } foreach($this->callbacks as $callback) { $callback($event); } unset(self::$channels[$this->id]); } public function send($name, array $args = null) { $event = new Event($this->envelope, $this->createHeader(), $name, $args); $this->socket->send($event); } public function createHeader() { return array('v'=>self::PROTOCOL_VERSION, 'message_id'=>uniqid(), 'response_to'=>$this->id); } }
<?php namespace ZeroRPC; class ChannelException extends \RuntimeException {} class Channel { const PROTOCOL_VERSION = 3; private static $channels = array(); protected $id; protected $envelope; protected $socket; private $callbacks = array(); public function __construct($id, $envelope, $socket) { $this->id = $id; $this->envelope = $envelope; $this->socket = $socket; self::$channels[$id] = $this; } public static function get($id) { if (isset(self::$channels[$id])) return self::$channels[$id]; } public static function count() { return count(self::$channels); } public function register($callback) { array_push($this->callbacks, $callback); } // Called when the channel receives an event public function invoke(Event $event) { if ($event->name === '_zpc_hb') { // Send heartbeat response return $this->send('_zpc_hb'); } foreach($this->callbacks as $callback) { $callback($event); } unset(self::$channels[$this->id]); } public function send($name, array $args = null) { $event = new Event($this->envelope, $this->createHeader(), $name, $args); $this->socket->send($event); } public function createHeader() { return array('v'=>PROTOCOL_VERSION, 'message_id'=>uniqid(), 'response_to'=>$this->id); } }
Handle slug collisions by adding a little salt.
var _ = require('underscore'); var getSlug = require('speakingurl'); var SLUG_MAP_FILE = "src/data/slug_map.json"; module.exports = function(grunt) { function readMap() { try { return grunt.file.readJSON(SLUG_MAP_FILE); } catch (e) { return {}; } } var contents = readMap(); function sluggify(resource, record, salt) { salt = salt || ''; //used to break ties return '/' + getSlug(record.displayName) + salt; } function slugExists(slug) { return _.any(contents, function(val) { return val === slug; }); } function urlFor(resource, record) { var key = resource + '|' + record.id; if(!contents[key]) { var slug = sluggify(resource, record); // just in case there is a collision, tack on the id as a tiebreaker if(slugExists(slug)) { slug = sluggify(resource, record, record.id); } contents[key] = slug; } return contents[key]; } function write() { grunt.file.write(SLUG_MAP_FILE, JSON.stringify(contents)); } return { urlFor: urlFor, write: write, }; }
var _ = require('underscore'); var getSlug = require('speakingurl'); var SLUG_MAP_FILE = "src/data/slug_map.json"; module.exports = function(grunt) { function readMap() { try { return grunt.file.readJSON(SLUG_MAP_FILE); } catch (e) { return {}; } } var contents = readMap(); function sluggify(resource, record) { return '/' + getSlug(record.displayName); } function urlFor(resource, record) { var key = resource + '|' + record.id; if(!contents[key]) { contents[key] = sluggify(resource, record); } return contents[key]; } function write() { grunt.file.write(SLUG_MAP_FILE, JSON.stringify(contents)); } return { urlFor: urlFor, write: write, }; }
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); finishedLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); } $('a.close').click(function() { var qqq = $(this).closest('.modal'); $(qqq).removeClass('active'); });
Make URL shortener more forgiving
var standardPageTypes = { 'event': /^(19|20)[0-9]{2}\// }; var resolveUrl = function(urlFragment) { return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, ''); }; var shortenUrl = function(url) { return url.replace(/^(http:\/\/.*?)?\//, ''); }; var resolvePageType = function(url, types) { url = resolveUrl(url); types = types || standardPageTypes; var matches = Object.keys(types).filter(function(type) { var urlRegExp = types[type]; return urlRegExp.test(url); }); return matches.length ? matches[0] : null; }; module.exports = { resolveUrl: resolveUrl, shortenUrl: shortenUrl, resolvePageType: resolvePageType };
var standardPageTypes = { 'event': /^(19|20)[0-9]{2}\// }; var resolveUrl = function(urlFragment) { return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, ''); }; var shortenUrl = function(url) { return url.replace(/^(http:\/\/){1}(www\.)?(lanyrd\.com\/){1}|\//, ''); }; var resolvePageType = function(url, types) { url = resolveUrl(url); types = types || standardPageTypes; var matches = Object.keys(types).filter(function(type) { var urlRegExp = types[type]; return urlRegExp.test(url); }); return matches.length ? matches[0] : null; }; module.exports = { resolveUrl: resolveUrl, shortenUrl: shortenUrl, resolvePageType: resolvePageType };
Switch of weak pointers for now as it does not yet play nice with stdout
/** * @define {boolean} HS_DEBUG is like goog.DEBUG, but for ghcjs internals */ var HS_DEBUG = true; /** * @define {boolean} enable weak pointers and finalizers */ var HS_WEAKS = false; /** * @define {boolean} enable traceLog in the run loop */ var HS_TRACE = true; /** * @define {boolean} enable tracing in hscall */ var HS_TRACE_CALLS = false; /** * @define {boolean} enable include args in the hscall messages */ var HS_TRACE_ARGS = false; /** * @define {boolean} enable tracing of RTS calls */ var HS_RTS_TRACE = false; /** * @define {boolean} enable the trampoline calling convention */ var HS_TRAMPOLINE = true; /** * @define {number} size of Word and Int. If 64 we use goog.math.Long. */ var WORD_SIZE_IN_BITS = 32;
/** * @define {boolean} HS_DEBUG is like goog.DEBUG, but for ghcjs internals */ var HS_DEBUG = true; /** * @define {boolean} enable weak pointers and finalizers */ var HS_WEAKS = true; /** * @define {boolean} enable traceLog in the run loop */ var HS_TRACE = true; /** * @define {boolean} enable tracing in hscall */ var HS_TRACE_CALLS = false; /** * @define {boolean} enable include args in the hscall messages */ var HS_TRACE_ARGS = false; /** * @define {boolean} enable tracing of RTS calls */ var HS_RTS_TRACE = false; /** * @define {boolean} enable the trampoline calling convention */ var HS_TRAMPOLINE = true; /** * @define {number} size of Word and Int. If 64 we use goog.math.Long. */ var WORD_SIZE_IN_BITS = 32;
Speed up the scrolling on link clicks
/*! * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('body').on('click', '.page-scroll a', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
/*! * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('body').on('click', '.page-scroll a', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1000, 'easeInOutExpo'); event.preventDefault(); }); }); // Floating label headings for the contact form $(function() { $("body").on("input propertychange", ".floating-label-form-group", function(e) { $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val()); }).on("focus", ".floating-label-form-group", function() { $(this).addClass("floating-label-form-group-with-focus"); }).on("blur", ".floating-label-form-group", function() { $(this).removeClass("floating-label-form-group-with-focus"); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
fix(Brush): Use floor instead of round for determining brush's selected pixels
/** * Gets the pixels within the circle. * @export @public @method * @name getCircle * * @param {number} radius The radius of the circle. * @param {number} rows The number of rows. * @param {number} columns The number of columns. * @param {number} [xCoord = 0] The x-location of the center of the circle. * @param {number} [yCoord = 0] The y-location of the center of the circle. * @returns {Array.number[]} Array of pixels contained within the circle. */ export default function getCircle( radius, rows, columns, xCoord = 0, yCoord = 0 ) { const x0 = Math.floor(xCoord); const y0 = Math.floor(yCoord); if (radius === 1) { return [[x0, y0]]; } const circleArray = []; let index = 0; for (let y = -radius; y <= radius; y++) { const yCoord = y0 + y; if (yCoord > rows || yCoord < 0) { continue; } for (let x = -radius; x <= radius; x++) { const xCoord = x0 + x; if (xCoord >= columns || xCoord < 0) { continue; } if (x * x + y * y < radius * radius) { circleArray[index++] = [x0 + x, y0 + y]; } } } return circleArray; }
/** * Gets the pixels within the circle. * @export @public @method * @name getCircle * * @param {number} radius The radius of the circle. * @param {number} rows The number of rows. * @param {number} columns The number of columns. * @param {number} [xCoord = 0] The x-location of the center of the circle. * @param {number} [yCoord = 0] The y-location of the center of the circle. * @returns {Array.number[]} Array of pixels contained within the circle. */ export default function getCircle( radius, rows, columns, xCoord = 0, yCoord = 0 ) { const x0 = Math.round(xCoord); const y0 = Math.round(yCoord); if (radius === 1) { return [[x0, y0]]; } const circleArray = []; let index = 0; for (let y = -radius; y <= radius; y++) { const yCoord = y0 + y; if (yCoord > rows || yCoord < 0) { continue; } for (let x = -radius; x <= radius; x++) { const xCoord = x0 + x; if (xCoord >= columns || xCoord < 0) { continue; } if (x * x + y * y < radius * radius) { circleArray[index++] = [x0 + x, y0 + y]; } } } return circleArray; }
Clean up email notification message
import smtplib from email.mime.text import MIMEText def send_mail(job_id=None, job_fail=None, mail_to=None, mail_from=None, mail_server=None): mail_from = "Inferno Daemon <inferno@localhost.localdomain>" if not mail_from else mail_from if not job_id or not job_fail: raise Exception("Empty job failure reason or job id: Cannot continue") if not mail_to: raise Exception("mail_to cannot be empty: Requires a list of recipient addresses") mail_server = "localhost" if not mail_server else mail_server msg_body = str(job_fail) msg = MIMEText(msg_body) msg['Subject'] = "Job Status: %s" % job_id msg['From'] = mail_from msg['To'] = ", ".join(mail_to) try: s = smtplib.SMTP(mail_server) s.sendmail(mail_from, mail_to, msg.as_string()) s.quit() return True except: return False
import smtplib from email.mime.text import MIMEText def send_mail(job_id=None, job_fail=None, mail_to=None, mail_from=None, mail_server=None): mail_from = "Inferno Daemon <inferno@localhost.localdomain>" if not mail_from else mail_from if not job_id or not job_fail: raise Exception("Empty job failure reason or job id: Cannot continue") if not mail_to: raise Exception("mail_to cannot be empty: Requires a list of recipient addresses") mail_server = "localhost" if not mail_server else mail_server msg_body = str(job_fail) msg = MIMEText(msg_body) msg['Subject'] = "Job Failed: %s" % job_id msg['From'] = mail_from msg['To'] = ", ".join(mail_to) try: s = smtplib.SMTP(mail_server) s.sendmail(mail_from, mail_to, msg.as_string()) s.quit() return True except: return False
Add CORS headers to dev server media.
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from django.views.static import serve as static_serve from funfactory.monkeypatches import patch # Apply funfactory monkeypatches. patch() # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() def robots_txt(request): permission = 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' return HttpResponse('User-agent: *\n{0}: /'.format(permission), mimetype='text/plain') urlpatterns = patterns('', url(r'', include('snippets.base.urls')), url(r'^admin/', include('smuggler.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^robots\.txt$', robots_txt) ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: # Use custom serve function that adds necessary headers. def serve_media(*args, **kwargs): response = static_serve(*args, **kwargs) response['Access-Control-Allow-Origin'] = '*' return response urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', serve_media, { 'document_root': settings.MEDIA_ROOT, }), ) + staticfiles_urlpatterns()
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from funfactory.monkeypatches import patch # Apply funfactory monkeypatches. patch() # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() def robots_txt(request): permission = 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' return HttpResponse('User-agent: *\n{0}: /'.format(permission), mimetype='text/plain') urlpatterns = patterns('', url(r'', include('snippets.base.urls')), url(r'^admin/', include('smuggler.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^robots\.txt$', robots_txt) ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) + staticfiles_urlpatterns()
Change padding depend on window width (the bigger the more big the width is)
var imgWidth = new Array(); var imagePadding = 100; function imageWidth() { var width = $(window).width() - imagePadding; $(".img_flex").each(function(index) { if (width != $(this).width()) { if (width < imgWidth[index]) { $(this).width(width); } else { $(this).width(imgWidth[index]); } } }); } $(document).ready(function() { $(document).keyup(function(e) { if (e.keyCode === 37) window.location.href = prevPage; if (e.keyCode === 39) window.location.href = nextPage; }); $(".jump").on('change', function() { window.location.href = baseUrl + this.value; }); $(".img_flex").each(function(index) { imgWidth.push($(this).width()); }); imageWidth(); $(window).resize(function(){ imageWidth(); }); });
var imgWidth = new Array(); function imageWidth() { var width = $(window).width() - fixedPadding; $(".img_flex").each(function(index) { if (width != $(this).width()) { if (width < imgWidth[index]) { $(this).width(width); } else { $(this).width(imgWidth[index]); } } }); } $(document).ready(function() { $(document).keyup(function(e) { if (e.keyCode === 37) window.location.href = prevPage; if (e.keyCode === 39) window.location.href = nextPage; }); $(".jump").on('change', function() { window.location.href = baseUrl + this.value; }); $(".img_flex").each(function(index) { imgWidth.push($(this).width()); }); imageWidth(); $(window).resize(function(){ imageWidth(); }); });
Clean bug with static file serving
from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.models import get_current_site from django.conf import settings from haystack.forms import SearchForm from entities.models import Entity from oshot.forms import EntityChoiceForm def forms(request): context = {"search_form": SearchForm()} try: kwargs = request.resolver_match.kwargs if 'entity_slug' in kwargs: entity = Entity.objects.get(slug=kwargs['entity_slug']) initial = {'entity': entity.id} elif 'entity_id' in kwargs: entity = Entity.objects.get(id=kwargs['entity_id']) initial = {'entity': entity.id} else: initial = {} context['entity_form'] = EntityChoiceForm(initial=initial, auto_id=False) except AttributeError: pass if not request.user.is_authenticated(): context["login_form"] = AuthenticationForm() # TODO: remove context["site"] = get_current_site(request) context["ANALYTICS_ID"] = getattr(settings, 'ANALYTICS_ID', False) return context
from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.models import get_current_site from django.conf import settings from haystack.forms import SearchForm from entities.models import Entity from oshot.forms import EntityChoiceForm def forms(request): context = {"search_form": SearchForm()} kwargs = request.resolver_match.kwargs if 'entity_slug' in kwargs: entity = Entity.objects.get(slug=kwargs['entity_slug']) initial = {'entity': entity.id} elif 'entity_id' in kwargs: entity = Entity.objects.get(id=kwargs['entity_id']) initial = {'entity': entity.id} else: initial = {} context['entity_form'] = EntityChoiceForm(initial=initial, auto_id=False) if not request.user.is_authenticated(): context["login_form"] = AuthenticationForm() # TODO: remove context["site"] = get_current_site(request) context["ANALYTICS_ID"] = getattr(settings, 'ANALYTICS_ID', False) return context
Fix style in cooper test.
import pagoda.cooper class Base(object): def setUp(self): self.world = pagoda.cooper.World() class TestMarkers(Base): def setUp(self): super(TestMarkers, self).setUp() self.markers = pagoda.cooper.Markers(self.world) def test_c3d(self): self.markers.load_c3d('examples/cooper-motion.c3d') assert self.markers.num_frames == 343 assert len(self.markers.marker_bodies) == 41 assert len(self.markers.attach_bodies) == 0 assert len(self.markers.attach_offsets) == 0 assert len(self.markers.channels) == 41 def test_csv(self): return # TODO self.markers.load_csv('examples/cooper-motion.csv') assert self.markers.num_frames == 343 assert len(self.markers.marker_bodies) == 41 assert len(self.markers.attach_bodies) == 0 assert len(self.markers.attach_offsets) == 0 assert len(self.markers.channels) == 41
import pagoda.cooper class Base(object): def setUp(self): self.world = pagoda.cooper.World() class TestMarkers(Base): def setUp(self): super(TestMarkers, self).setUp() self.markers = pagoda.cooper.Markers(self.world) def test_c3d(self): self.markers.load_c3d('examples/cooper-motion.c3d') assert self.markers.num_frames == 343 assert len(self.markers.marker_bodies) == 41 assert len(self.markers.attach_bodies) == 0 assert len(self.markers.attach_offsets) == 0 assert len(self.markers.channels) == 41 def test_csv(self): return # TODO self.markers.load_csv('examples/cooper-motion.csv') assert self.markers.num_frames == 343 assert len(self.markers.marker_bodies) == 41 assert len(self.markers.attach_bodies) == 0 assert len(self.markers.attach_offsets) == 0 assert len(self.markers.channels) == 41
Use Li method for thresholding instead of Otsu
import numpy as np from scipy import ndimage as ndi from skimage.filters import threshold_li def _extract_roi(image, axis=-1): max_frame = np.max(image, axis=axis) initial_mask = max_frame > threshold_li(max_frame) regions = ndi.label(initial_mask)[0] region_sizes = np.bincount(np.ravel(regions)) return regions == (np.argmax(region_sizes[1:]) + 1) def extract_trace(image, axis=-1): """Get a mean intensity trace over time out of an image. Parameters ---------- image : array The input image. axis : int, optional The axis identifying frames. Returns ------- trace : array of float The trace of the image data over time. roi : array of bool The mask used to obtain the trace. """ roi = _extract_roi(image, axis) trace = np.sum(image[roi].astype(float), axis=0) / np.sum(roi) return trace, roi
import numpy as np from scipy import ndimage as ndi from skimage.filters import threshold_otsu def _extract_roi(image, axis=-1): max_frame = np.max(image, axis=axis) initial_mask = max_frame > threshold_otsu(max_frame) regions = ndi.label(initial_mask)[0] region_sizes = np.bincount(np.ravel(regions)) return regions == (np.argmax(region_sizes[1:]) + 1) def extract_trace(image, axis=-1): """Get a mean intensity trace over time out of an image. Parameters ---------- image : array The input image. axis : int, optional The axis identifying frames. Returns ------- trace : array of float The trace of the image data over time. roi : array of bool The mask used to obtain the trace. """ roi = _extract_roi(image, axis) trace = np.sum(image[roi].astype(float), axis=0) / np.sum(roi) return trace, roi
Use HTTPS frame in clickjacking example
<div style="left: 110px; top: 90px; position: absolute;">SCROLL DOWN</div> <img src="play.png" onclick="alert('never triggered');" width="80" height="80" style="left: 110px; top: 710px; position: absolute;"> <?php $opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5'); $url = (isset($_GET['url']) ? $_GET['url'] : 'https://rungo.idnes.cz/ankety.aspx?idanketa=A20160824_Pil_507&setver=full'); ?> <iframe style="opacity: <?php echo htmlspecialchars($opacity); ?>; width: 400px; height: 800px; left: 0px; position: absolute;" src="<?php echo htmlspecialchars($url); ?>"> </iframe> <p style="padding-top: 820px"><strong>Clickjacking</strong></p> <p><a href="?opacity=0">invisible frame <?php echo htmlspecialchars($url); ?></a></p> <p><a href="?opacity=0.5">half-visible frame <?php echo htmlspecialchars($url); ?></a></p>
<div style="left: 110px; top: 90px; position: absolute;">SCROLL DOWN</div> <img src="play.png" onclick="alert('never triggered');" width="80" height="80" style="left: 110px; top: 710px; position: absolute;"> <?php $opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5'); $url = (isset($_GET['url']) ? $_GET['url'] : 'http://rungo.idnes.cz/ankety.aspx?idanketa=A20160313_Pil_382&setver=full'); ?> <iframe style="opacity: <?php echo htmlspecialchars($opacity); ?>; width: 400px; height: 800px; left: 0px; position: absolute;" src="<?php echo htmlspecialchars($url); ?>"> </iframe> <p style="padding-top: 820px"><strong>Clickjacking</strong></p> <p><a href="?opacity=0">invisible frame <?php echo htmlspecialchars($url); ?></a></p> <p><a href="?opacity=0.5">half-visible frame <?php echo htmlspecialchars($url); ?></a></p>
Use the app string version of foreign keying. It prevents a circular import.
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): user = models.ManyToManyField( 'tracker.Tbluser', related_name="user_foreign" ) activity = models.ManyToManyField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): from timetracker.tracker.models import Tbluser user = models.ManyToManyField( Tbluser, related_name="user_foreign" ) activity = models.ManyToManyField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
Fix for loading bar flicking to empty for some steps.
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.engine.modes.loadProcesses; import org.terasology.engine.modes.LoadProcess; /** * @author Immortius */ public abstract class StepBasedLoadProcess implements LoadProcess { private int stepsComplete; private int totalSteps = 1; protected void stepDone() { stepsComplete++; } protected void setTotalSteps(int amount) { this.totalSteps = Math.max(1, amount); } @Override public final float getProgress() { return (float) Math.min(totalSteps, stepsComplete) / totalSteps; } }
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.engine.modes.loadProcesses; import org.terasology.engine.modes.LoadProcess; /** * @author Immortius */ public abstract class StepBasedLoadProcess implements LoadProcess { private int stepsComplete; private int totalSteps; protected void stepDone() { stepsComplete++; } protected void setTotalSteps(int amount) { this.totalSteps = Math.min(1, amount); } @Override public final float getProgress() { return (float) Math.min(totalSteps, stepsComplete) / totalSteps; } }
Move logging for bookmarks close from voyager to vlui
'use strict'; /** * @ngdoc directive * @name vlui.directive:bookmarkList * @description * # bookmarkList */ angular.module('vlui') .directive('bookmarkList', function (Bookmarks, consts, Logger) { return { templateUrl: 'bookmarklist/bookmarklist.html', restrict: 'E', replace: true, require: '^vlModal', scope: { highlighted: '=' }, link: function postLink(scope, element, attrs, modalController) { scope.deactivate = function() { Logger.logInteraction(Logger.actions.BOOKMARK_CLOSE); modalController.close(); } scope.Bookmarks = Bookmarks; scope.consts = consts; } }; });
'use strict'; /** * @ngdoc directive * @name vlui.directive:bookmarkList * @description * # bookmarkList */ angular.module('vlui') .directive('bookmarkList', function (Bookmarks, consts) { return { templateUrl: 'bookmarklist/bookmarklist.html', restrict: 'E', replace: true, require: '^vlModal', scope: { highlighted: '=' }, link: function postLink(scope, element, attrs, modalController) { scope.deactivate = function() { modalController.close(); } scope.Bookmarks = Bookmarks; scope.consts = consts; } }; });
Migrate all settings to local storage for v3.3.
// listen to install/update events chrome.runtime.onInstalled.addListener(function(details){ switch(details.reason) { case 'install': chrome.tabs.create({url: '/docs/pro-for-trello-installed.html'}); break; case 'update': var version = chrome.runtime.getManifest().version; if(version == '2.0.1') { // minor update (before ppl updated to 2.0) chrome.tabs.create({url: '/docs/pro-for-trello-updated-to-2.0.html'}); break; } else if(version == '3.3') { // migrate all settings and data to local storage, thank you Google :( let migrate = {}; chrome.storage.sync.get(function(data){ for(let key in data) { if(key == 'autohide' || key.indexOf('lists_') == 0 || key.indexOf('data_') == 0) { migrate[key] = data[key]; continue; } migrate['board_' + key] = data[key]; } chrome.storage.local.set(migrate); }); } if(version.split('.').length > 2) break; // ignore minor versions chrome.tabs.create({url: '/docs/pro-for-trello-updated-to-'+version+'.html'}); break; } });
// listen to install/update events chrome.runtime.onInstalled.addListener(function(details){ switch(details.reason) { case 'install': chrome.tabs.create({url: '/docs/pro-for-trello-installed.html'}); break; case 'update': var version = chrome.runtime.getManifest().version; if(version == '2.0.1') { // minor update (before ppl updated to 2.0) chrome.tabs.create({url: '/docs/pro-for-trello-updated-to-2.0.html'}); break; } else if(version == '3.2.1') { // migrate all settings and data to local storage, thank you Google :( let migrate = {}; chrome.storage.sync.get(function(data){ for(let key in data) { if(key == 'autohide' || key.indexOf('lists_') == 0 || key.indexOf('data_') == 0) { migrate[key] = data[key]; continue; } migrate['board_' + key] = data[key]; } chrome.storage.local.set(migrate); }); } if(version.split('.').length > 2) break; // ignore minor versions chrome.tabs.create({url: '/docs/pro-for-trello-updated-to-'+version+'.html'}); break; } });
Add common interfeces to the subscription interface
<?php /* * This file is part of the Active Collab Payments project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Payments\Subscription; use ActiveCollab\DateValue\DateTimeValueInterface; use ActiveCollab\Payments\Common\GatewayedObjectInterface; use ActiveCollab\Payments\Common\InternallyIdentifiedObjectInterface; use ActiveCollab\Payments\Common\ReferencedObjectInterface; use ActiveCollab\Payments\Common\TimestampedObjectInterface; use ActiveCollab\Payments\Product\ProductInterface; interface SubscriptionInterface extends GatewayedObjectInterface, InternallyIdentifiedObjectInterface, ProductInterface, ReferencedObjectInterface, TimestampedObjectInterface { const MONTHLY = 'monthly'; const YEARLY = 'yearly'; const BILLING_PERIODS = [self::MONTHLY, self::YEARLY]; public function getBillingPeriod(): string; public function getNextBillingTimestamp(): DateTimeValueInterface; public function &setNextBillingTimestamp(DateTimeValueInterface $value): SubscriptionInterface; public function calculateNextBillingTimestamp(DateTimeValueInterface $reference): DateTimeValueInterface; }
<?php /* * This file is part of the Active Collab Payments project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Payments\Subscription; use ActiveCollab\DateValue\DateTimeValueInterface; use ActiveCollab\Payments\Common\GatewayedObjectInterface; use ActiveCollab\Payments\Product\ProductInterface; interface SubscriptionInterface extends GatewayedObjectInterface, ProductInterface { const MONTHLY = 'monthly'; const YEARLY = 'yearly'; const BILLING_PERIODS = [self::MONTHLY, self::YEARLY]; public function getBillingPeriod(): string; public function getNextBillingTimestamp(): DateTimeValueInterface; public function &setNextBillingTimestamp(DateTimeValueInterface $value): SubscriptionInterface; public function calculateNextBillingTimestamp(DateTimeValueInterface $reference): DateTimeValueInterface; }
Fix path (just happened to work on Win7, fails on Win8)
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ (function () { "use strict"; var resolve = require("path").resolve, spawn = require("child_process").spawn; var execpath = (__dirname + "/../bin/convert"); module.exports = function convert(args, psPath) { if (process.platform === "darwin") return spawn( psPath + "/Adobe Photoshop CC.app/Contents/MacOS/convert", args ); else return spawn(execpath, args); }; }());
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ (function () { "use strict"; var resolve = require("path").resolve, spawn = require("child_process").spawn; var execpath = (__dirname, "../bin/convert"); module.exports = function convert(args, psPath) { if (process.platform === "darwin") return spawn( psPath + "/Adobe Photoshop CC.app/Contents/MacOS/convert", args ); else return spawn(execpath, args); }; }());
Make the babel-loader test more explicit in dicom_viewer
module.exports = function (config) { config.module.rules.push({ resource: { test: /node_modules(\/|\\)vtk\.js(\/|\\).*.glsl$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/] }, use: [ 'shader-loader' ] }); config.module.rules.push({ resource: { test: /node_modules(\/|\\)vtk\.js(\/|\\).*.js$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/] }, use: [ { loader: 'babel-loader', options: { presets: ['es2015'] } } ] }); return config; };
module.exports = function (config) { config.module.rules.push({ resource: { test: /\.glsl$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/] }, use: [ 'shader-loader' ] }); config.module.rules.push({ resource: { test: /\.js$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/] }, use: [ { loader: 'babel-loader', options: { presets: ['es2015'] } } ] }); return config; };
Decrease splinter timeout to 3 seconds @alexmuller @maxfliri
from pymongo import MongoClient from splinter import Browser from features.support.support import Api class SplinterClient(object): def __init__(self, database_name): self.database_name = database_name self._write_api = Api.start('write', '5001') def storage(self): return MongoClient('localhost', 27017)[self.database_name] def before_scenario(self): self.browser = Browser('phantomjs', wait_time=3) def after_scenario(self): self.browser.quit() def spin_down(self): self._write_api.stop() def get(self, url, headers=None): self.browser.visit(self._write_api.url(url)) return SplinterResponse(self.browser) class SplinterResponse: def __init__(self, browser): self.status_code = browser.status_code self.data = None self.headers = None
from pymongo import MongoClient from splinter import Browser from features.support.support import Api class SplinterClient(object): def __init__(self, database_name): self.database_name = database_name self._write_api = Api.start('write', '5001') def storage(self): return MongoClient('localhost', 27017)[self.database_name] def before_scenario(self): self.browser = Browser('phantomjs', wait_time=15) def after_scenario(self): self.browser.quit() def spin_down(self): self._write_api.stop() def get(self, url, headers=None): self.browser.visit(self._write_api.url(url)) return SplinterResponse(self.browser) class SplinterResponse: def __init__(self, browser): self.status_code = browser.status_code self.data = None self.headers = None
Clarify the role of each test in the simple relationships acceptance tests
import Ember from 'ember'; import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; const { get } = Ember; moduleForAcceptance('Acceptance | simple relationships', { beforeEach() { this.author = server.create('author'); this.post = server.create('post', { author: this.author, }); this.comment = server.create('comment', { post: this.post, }); server.createList('reaction', 4, { post: this.post, }); visit(`/posts/${get(this.post, 'slug')}`); }, }); test('it can use a belongsTo id from the snapshot when generating a url', function(assert) { // The comments relationship comes with with data and ids. Therefore it uses // the findRecord adapter hook in the comment adapter and the comment adapter // urlTemplate. assert.equal(find('#comments p').length, 1); }); test('it can load a hasMany relationship from just a url template', function(assert) { // The reactions relationshp is configured in the post model to use the // urlTemplate. It therefore uses the findMany hook in the post adapter and // the post adapter reactionsUrlTemplate. assert.equal(find('#reactions p').length, 4); }); test('it can load a belongsTo relationship from just a url template', function(assert) { // The reactions relationshp is configured in the post model to use the // urlTemplate. It therefore uses the findBelongsTo hook in the post adapter and // the post adapter authorUrlTemplate. assert.equal(find('#author').text(), `by ${this.author.name}`); });
import Ember from 'ember'; import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; const { get } = Ember; moduleForAcceptance('Acceptance | simple relationships', { beforeEach() { this.author = server.create('author'); this.post = server.create('post', { author: this.author, }); this.comment = server.create('comment', { post: this.post, }); server.createList('reaction', 4, { post: this.post, }); visit(`/posts/${get(this.post, 'slug')}`); }, }); test('it can use a belongsTo id from the snapshot when generating a url', function(assert) { // Comments are loaded with data and ids assert.equal(find('#comments p').length, 1); }); test('it can load a hasMany relationship from just a url template', function(assert) { assert.equal(find('#reactions p').length, 4); }); test('it can load a belongsTo relationship from just a url template', function(assert) { assert.equal(find('#author').text(), `by ${this.author.name}`); });
Change plugin type to profile_reader This repairs the profile reading at startup. It should not be a mesh reader. Contributes to issue CURA-34.
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import GCodeReader from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "GCode Reader"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Provides support for reading GCode files."), "api": 2 }, "profile_reader": { "extension": "gcode", "description": catalog.i18nc("@item:inlistbox", "Gcode File") } } def register(app): return { "profile_reader": GCodeReader.GCodeReader() }
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import GCodeReader from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "GCode Reader"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Provides support for reading GCode files."), "api": 2 }, "mesh_reader": [ { "extension": "gcode", "description": catalog.i18nc("@item:inlistbox", "Gcode File") } ] } def register(app): return { "mesh_reader": GCodeReader.GCodeReader() }
Add items to the list component after they are put into the DOM, such that the itemFocus finds the dom correctly when positioning itself
jsio('from common.javascript import Class, bind'); jsio('import browser.events as events'); jsio('import browser.dom as dom'); jsio('import browser.css as css'); jsio('import browser.ItemView'); jsio('import browser.ListComponent'); jsio('import .Panel'); css.loadStyles(jsio.__path); exports = Class(Panel, function(supr) { this.init = function() { supr(this, 'init', arguments); this._label = this._item; this._listComponent = new browser.ListComponent(bind(this, '_onItemSelected')); } this.createContent = function() { supr(this, 'createContent'); this.addClassName('ListPanel'); } this.addItem = function(item) { item.addClassName('listItem'); this._content.appendChild(item.getElement()); this._listComponent.addItem(item); this._manager.resize(); } this.focus = function() { supr(this, 'focus'); this._listComponent.focus(); } this._onItemSelected = function(item) { this._publish('ItemSelected', item); } })
jsio('from common.javascript import Class, bind'); jsio('import browser.events as events'); jsio('import browser.dom as dom'); jsio('import browser.css as css'); jsio('import browser.ItemView'); jsio('import browser.ListComponent'); jsio('import .Panel'); css.loadStyles(jsio.__path); exports = Class(Panel, function(supr) { this.init = function() { supr(this, 'init', arguments); this._label = this._item; this._listComponent = new browser.ListComponent(bind(this, '_onItemSelected')); } this.createContent = function() { supr(this, 'createContent'); this.addClassName('ListPanel'); } this.addItem = function(item) { item.addClassName('listItem'); this._listComponent.addItem(item); this._content.appendChild(item.getElement()); this._manager.resize(); } this.focus = function() { supr(this, 'focus'); this._listComponent.focus(); } this._onItemSelected = function(item) { this._publish('ItemSelected', item); } })
Set highlighted background color on the newly added evidence
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { $(this.el).fadeOut('fast', function() { $(this.el).remove(); }); }, render: function() { $(this.el).html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { // TODO: Joel, could you specify some highlighting here? <3 <3 // Tried to do it, but don't know on which element I should set the // styles :( <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3 // Color fade out in JS required a jQuery plugin? Only giving new background color now. $(this.el).addClass('highlighted'); } });
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { $(this.el).fadeOut('fast', function() { $(this.el).remove(); }); }, render: function() { $(this.el).html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { // TODO: Joel, could you specify some highlighting here? <3 <3 // Tried to do it, but don't know on which element I should set the // styles :( <3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3 } });
Update setup.py file for numscons build.
#!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('spatial', parent_package, top_path) config.add_data_dir('tests') #config.add_extension('_vq', # sources=[join('src', 'vq_module.c'), join('src', 'vq.c')], # include_dirs = [get_numpy_include_dirs()]) config.add_sconscript('SConstruct') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", author = "Eric Jones", maintainer_email = "scipy-dev@scipy.org", description = "Clustering Algorithms (Information Theory)", url = "http://www.scipy.org", license = "SciPy License (BSD Style)", **configuration(top_path='').todict() )
#!/usr/bin/env python from os.path import join def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('cluster', parent_package, top_path) config.add_data_dir('tests') #config.add_extension('_vq', # sources=[join('src', 'vq_module.c'), join('src', 'vq.c')], # include_dirs = [get_numpy_include_dirs()]) config.add_sconscript('SConstruct') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", author = "Eric Jones", maintainer_email = "scipy-dev@scipy.org", description = "Clustering Algorithms (Information Theory)", url = "http://www.scipy.org", license = "SciPy License (BSD Style)", **configuration(top_path='').todict() )
Move sitemaps to non-language prefix url
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls import include, patterns, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() urlpatterns = [ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), ] urlpatterns += i18n_patterns('', url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^', include('cms.urls')), ) # This is only needed when using runserver. if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls import include, patterns, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), url(r'^', include('cms.urls')), ) # This is only needed when using runserver. if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA
fix(paths): Rename test directory path into mocks
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ module.exports.entityManager = require( 'easy/mocks/entitymanager.mock' ) module.exports.request = require( 'easy/mocks/request.mock' ) module.exports.response = require( 'easy/mocks/response.mock' ) module.exports.fakeAsync = require( 'easy/mocks/fakeAsync.mock' ) module.exports.directory = require( 'easy/mocks/directory.mock' ) module.exports.logger = require( 'easy/mocks/logger.mock' ) module.exports.logWriter = require( 'easy/mocks/logwriter.mock' ) module.exports.logFileManager = require( 'easy/mocks/logfilemanager.mock' ) module.exports.tokenManager = require( 'easy/mocks/tokenmanager.mock' ) module.exports.authorization = require( 'easy/mocks/authorization.mock' )
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ module.exports.entityManager = require( 'easy/test/entitymanager.mock' ) module.exports.request = require( 'easy/test/request.mock' ) module.exports.response = require( 'easy/test/response.mock' ) module.exports.fakeAsync = require( 'easy/test/fakeAsync.mock' ) module.exports.directory = require( 'easy/test/directory.mock' ) module.exports.logger = require( 'easy/test/logger.mock' ) module.exports.logWriter = require( 'easy/test/logwriter.mock' ) module.exports.logFileManager = require( 'easy/test/logfilemanager.mock' ) module.exports.tokenManager = require( 'easy/test/tokenmanager.mock' ) module.exports.authorization = require( 'easy/test/authorization.mock' )
Change code as per @johnotander's suggestion
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = { ignore: [] } } if (!Array.isArray(options.ignore)) { throw TypeError("options.ignore must be an array") } var ignore = options.ignore.map(function (value) { if (typeof value === 'string') { return new RegExp(value + '$', 'i') } else if (value instanceof RegExp) { return value } else { throw TypeError('options.ignore values can either be a string or a regular expression') } }) return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = {}; } var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : []; if (ignore === false) { throw TypeError("options.ignore must be an array") } for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (typeof value === "string") { value = new RegExp(value + "$", "i") } else if (value instanceof RegExp) { } else { throw TypeError("options.ignore values can either be a string or a regular expression") } ignore[i] = value; } return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
Check unique combination of 'name' and 'in' parameters of @RequestParameter
<?php declare(strict_types = 1); namespace Apitte\Core\Annotation\Controller; use Doctrine\Common\Annotations\Annotation\Target; use Doctrine\Common\Annotations\AnnotationException; /** * @Annotation * @Target("METHOD") */ final class RequestParameters { /** @var RequestParameter[] */ private $parameters = []; /** * @param mixed[] $values */ public function __construct(array $values) { if (isset($values['value'])) { if (empty($values['value'])) { throw new AnnotationException('Empty @RequestParameters given'); } $this->parameters = $values['value']; } else { throw new AnnotationException('No @RequestParameter given in @RequestParameters'); } $takenNames = []; /** @var RequestParameter $value */ foreach ($values['value'] as $value) { if (!isset($takenNames[$value->getIn()][$value->getName()])) { $takenNames[$value->getIn()][$value->getName()] = $value; } else { throw new AnnotationException(sprintf( 'Multiple @RequestParameter annotations with "name=%s" and "in=%s" given. Each parameter must have unique combination of location and name.', $value->getName(), $value->getIn() )); } } } /** * @return RequestParameter[] */ public function getParameters(): array { return $this->parameters; } }
<?php declare(strict_types = 1); namespace Apitte\Core\Annotation\Controller; use Doctrine\Common\Annotations\Annotation\Target; use Doctrine\Common\Annotations\AnnotationException; /** * @Annotation * @Target("METHOD") */ final class RequestParameters { /** @var RequestParameter[] */ private $parameters = []; /** * @param mixed[] $values */ public function __construct(array $values) { if (isset($values['value'])) { if (empty($values['value'])) { throw new AnnotationException('Empty @RequestParameters given'); } $this->parameters = $values['value']; } else { throw new AnnotationException('No @RequestParameter given in @RequestParameters'); } } /** * @return RequestParameter[] */ public function getParameters(): array { return $this->parameters; } }
Correct name for Pypi package
from setuptools import setup, find_packages setup( name='emencia-cms-snippet', version=__import__('snippet').__version__, description=__import__('snippet').__doc__, long_description=open('README.rst').read(), author='David Thenon', author_email='dthenon@emencia.com', url='http://pypi.python.org/pypi/emencia-cms-snippet', license='MIT', packages=find_packages(), classifiers=[ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ 'django-cms==2.3.6', 'djangocms_text_ckeditor==1.0.10', ], include_package_data=True, zip_safe=False )
from setuptools import setup, find_packages setup( name='snippet', version=__import__('snippet').__version__, description=__import__('snippet').__doc__, long_description=open('README.rst').read(), author='David Thenon', author_email='dthenon@emencia.com', url='http://pypi.python.org/pypi/emencia-cms-snippet', license='MIT', packages=find_packages(), classifiers=[ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ 'django-cms==2.3.6', 'djangocms_text_ckeditor==1.0.10', ], include_package_data=True, zip_safe=False )
Load tasks module on app load.
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
Allow InstanceSlaHistory to be managed by staff
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)), )
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), )
Improve track API file header.
/** * Track API errors. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
Attach event handlers in routing unit.
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Controllers\ActionDispatcher; use Jivoo\Controllers\Controllers; use Jivoo\Core\LoadableModule; use Jivoo\Snippets\SnippetDispatcher; use Jivoo\Snippets\Snippets; use Jivoo\Routing\Routing; /** * Initializes the routing module. */ class RoutingUnit extends UnitBase { /** * {@inheritdoc} */ protected $requires = array('Request'); /** * {@inheritdoc} */ public function run(App $app, Document $config) { $app->m->routing = new Routing($app, false); $app->m->routing->dispatchers->add( new ActionDispatcher($app) ); $app->m->routing->dispatchers->add( new SnippetDispatcher($app) ); $app->attachEventHandler('afterLoadModules', array($app->m->routing, 'loadRoutes')); $app->attachEventHandler('afterInit', array($app->m->routing, 'findRoute')); } }
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Controllers\ActionDispatcher; use Jivoo\Controllers\Controllers; use Jivoo\Core\LoadableModule; use Jivoo\Snippets\SnippetDispatcher; use Jivoo\Snippets\Snippets; use Jivoo\Routing\Routing; /** * Initializes the routing module. */ class RoutingUnit extends UnitBase { /** * {@inheritdoc} */ protected $requires = array('Request'); /** * {@inheritdoc} */ public function run(App $app, Document $config) { $app->m->routing = new Routing($app, false); $app->m->routing->dispatchers->add( new ActionDispatcher($app) ); $app->m->routing->dispatchers->add( new SnippetDispatcher($app) ); } }
Move external git folder integration tests to a separate class
import unittest import util from git_wrapper import GitWrapper class GitWrapperIntegrationTest(util.RepoTestCase): def test_paths(self): self.open_tar_repo('project01') assert('test_file.txt' in self.repo.paths) assert('hello_world.rb' in self.repo.paths) def test_stage(self): self.open_tar_repo('project02') assert('not_committed_file.txt' in self.repo.stage) assert('second_not_committed_file.txt' in self.repo.stage) class GitWrapperIntegrationTestExternalGitFolder(util.RepoTestCase): def test_paths_external(self): self.open_tar_repo('project03', '../project03.git') assert('test_file.txt' in self.repo.paths) assert('hello_world.rb' in self.repo.paths) def test_stage_external(self): self.open_tar_repo('project04', '../project04.git') assert('not_committed_file.txt' in self.repo.stage) assert('second_not_committed_file.txt' in self.repo.stage)
import unittest import util from git_wrapper import GitWrapper class GitWrapperIntegrationTest(util.RepoTestCase): def test_paths(self): self.open_tar_repo('project01') assert('test_file.txt' in self.repo.paths) assert('hello_world.rb' in self.repo.paths) def test_stage(self): self.open_tar_repo('project02') assert('not_committed_file.txt' in self.repo.stage) assert('second_not_committed_file.txt' in self.repo.stage) def test_paths_external_git_folder(self): self.open_tar_repo('project03', '../project03.git') assert('test_file.txt' in self.repo.paths) assert('hello_world.rb' in self.repo.paths) def test_stage_external_git_folder(self): self.open_tar_repo('project04', '../project04.git') assert('not_committed_file.txt' in self.repo.stage) assert('second_not_committed_file.txt' in self.repo.stage)
Allow changing what object is returned from Command instances.
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
Add @Keep annotation on unsubscribed field Since it's accessed via reflection, this needs to be kept un-obfuscated.
package com.jakewharton.rxbinding.internal; import android.os.Handler; import android.os.Looper; import android.support.annotation.Keep; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import rx.Subscription; public abstract class MainThreadSubscription implements Subscription, Runnable { private static final Handler mainThread = new Handler(Looper.getMainLooper()); @Keep @SuppressWarnings("unused") // Updated by 'unsubscribedUpdater' object. private volatile int unsubscribed; private static final AtomicIntegerFieldUpdater<MainThreadSubscription> unsubscribedUpdater = AtomicIntegerFieldUpdater.newUpdater(MainThreadSubscription.class, "unsubscribed"); @Override public final boolean isUnsubscribed() { return unsubscribed != 0; } @Override public final void unsubscribe() { if (unsubscribedUpdater.compareAndSet(this, 0, 1)) { if (Looper.getMainLooper() == Looper.myLooper()) { onUnsubscribe(); } else { mainThread.post(this); } } } @Override public final void run() { onUnsubscribe(); } protected abstract void onUnsubscribe(); }
package com.jakewharton.rxbinding.internal; import android.os.Handler; import android.os.Looper; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import rx.Subscription; public abstract class MainThreadSubscription implements Subscription, Runnable { private static final Handler mainThread = new Handler(Looper.getMainLooper()); @SuppressWarnings("unused") // Updated by 'unsubscribedUpdater' object. private volatile int unsubscribed; private static final AtomicIntegerFieldUpdater<MainThreadSubscription> unsubscribedUpdater = AtomicIntegerFieldUpdater.newUpdater(MainThreadSubscription.class, "unsubscribed"); @Override public final boolean isUnsubscribed() { return unsubscribed != 0; } @Override public final void unsubscribe() { if (unsubscribedUpdater.compareAndSet(this, 0, 1)) { if (Looper.getMainLooper() == Looper.myLooper()) { onUnsubscribe(); } else { mainThread.post(this); } } } @Override public final void run() { onUnsubscribe(); } protected abstract void onUnsubscribe(); }
Put / after dir path
#!/usr/bin/env python import json from pathlib import Path import ptt_core l = ptt_core.l _TARGETS_DIR_PATH = Path('targets/') if not _TARGETS_DIR_PATH.exists(): _TARGETS_DIR_PATH.mkdir() def generate_target_from(json_path): l.info('Generate target from {} ...'.format(json_path)) txt_path = _TARGETS_DIR_PATH / '{}.txt'.format(json_path.stem) if txt_path.exists(): l.info('Existed and skip {}'.format(txt_path)) return with json_path.open() as f: d = json.load(f) push_score_sum = sum(push_d['score'] for push_d in d['push_ds']) with txt_path.open('w') as f: f.write(str(push_score_sum)) l.info('Wrote into {}'.format(txt_path)) def generate_all(preprocessed_dir_path_str): for path in Path(preprocessed_dir_path_str).iterdir(): generate_target_from(path) if __name__ == '__main__': generate_all('preprocessed')
#!/usr/bin/env python import json from pathlib import Path import ptt_core l = ptt_core.l _TARGETS_DIR_PATH = Path('targets') if not _TARGETS_DIR_PATH.exists(): _TARGETS_DIR_PATH.mkdir() def generate_target_from(json_path): l.info('Generate target from {} ...'.format(json_path)) txt_path = _TARGETS_DIR_PATH / '{}.txt'.format(json_path.stem) if txt_path.exists(): l.info('Existed and skip {}'.format(txt_path)) return with json_path.open() as f: d = json.load(f) push_score_sum = sum(push_d['score'] for push_d in d['push_ds']) with txt_path.open('w') as f: f.write(str(push_score_sum)) l.info('Wrote into {}'.format(txt_path)) def generate_all(preprocessed_dir_path_str): for path in Path(preprocessed_dir_path_str).iterdir(): generate_target_from(path) if __name__ == '__main__': generate_all('preprocessed')
Improve http check to allow https as well We switch from 'startswith' to a regex check which allows both as we tested with https facebook urls and it failed to handle them properly.
# -*- coding: utf-8 -*- # © Copyright 2009 Andre Engelbrecht. All Rights Reserved. # This script is licensed under the BSD Open Source Licence # Please see the text file LICENCE for more information # If this script is distributed, it must be accompanied by the Licence import re from datetime import datetime from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from adzone.models import AdBase, AdClick http_re = re.compile(r'^https?://') def ad_view(request, id): """ Record the click in the database, then redirect to ad url """ ad = get_object_or_404(AdBase, id=id) click = AdClick.objects.create( ad=ad, click_date=datetime.now(), source_ip=request.META.get('REMOTE_ADDR', '') ) click.save() redirect_url = ad.url if not http_re.match(redirect_url): # Add http:// to the url so that the browser redirects correctly redirect_url = 'http://' + redirect_url return HttpResponseRedirect(redirect_url)
# -*- coding: utf-8 -*- # © Copyright 2009 Andre Engelbrecht. All Rights Reserved. # This script is licensed under the BSD Open Source Licence # Please see the text file LICENCE for more information # If this script is distributed, it must be accompanied by the Licence from datetime import datetime from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from adzone.models import AdBase, AdClick def ad_view(request, id): """ Record the click in the database, then redirect to ad url """ ad = get_object_or_404(AdBase, id=id) click = AdClick.objects.create( ad=ad, click_date=datetime.now(), source_ip=request.META.get('REMOTE_ADDR', '') ) click.save() redirect_url = ad.url if not redirect_url.startswith('http://'): # Add http:// to the url so that the browser redirects correctly redirect_url = 'http://' + redirect_url return HttpResponseRedirect(redirect_url)
Update to use ClinGen curation app and test curation app Google Analytics codes
'use strict'; // Minimal inline IE8 html5 compatibility require('shivie8'); // Read and clear stats cookie var cookie = require('cookie-monster')(document); window.stats_cookie = cookie.get('X-Stats') || ''; cookie.set('X-Stats', '', {path: '/', expires: new Date(0)}); // Use a separate tracker for dev / test var ga = require('google-analytics'); var trackers = {'curation.clinicalgenome.org': 'UA-49947422-4'}; var tracker = trackers[document.location.hostname] || 'UA-49947422-5'; ga('create', tracker, {'cookieDomain': 'none', 'siteSpeedSampleRate': 100}); ga('send', 'pageview'); // Need to know if onload event has fired for safe history api usage. window.onload = function () { window._onload_event_fired = true; }; var $script = require('scriptjs'); $script.path('/static/build/'); $script('https://login.persona.org/include.js', 'persona');
'use strict'; // Minimal inline IE8 html5 compatibility require('shivie8'); // Read and clear stats cookie var cookie = require('cookie-monster')(document); window.stats_cookie = cookie.get('X-Stats') || ''; cookie.set('X-Stats', '', {path: '/', expires: new Date(0)}); // Use a separate tracker for dev / test var ga = require('google-analytics'); var trackers = {'www.encodeproject.org': 'UA-47809317-1'}; var tracker = trackers[document.location.hostname] || 'UA-47809317-2'; ga('create', tracker, {'cookieDomain': 'none', 'siteSpeedSampleRate': 100}); ga('send', 'pageview'); // Need to know if onload event has fired for safe history api usage. window.onload = function () { window._onload_event_fired = true; }; var $script = require('scriptjs'); $script.path('/static/build/'); $script('https://login.persona.org/include.js', 'persona');
Rework commented out code a tad
# Copyright 2013 IBM Corporation # All rights reserved # This is the main application. # It should check for existing UDP socket to negotiate socket listen takeover # It will have three paths into it: # -Unix domain socket # -TLS socket # -WSGI # Additionally, it will be able to receive particular UDP packets to facilitate # Things like heartbeating and discovery # It also will optionally snoop SLP DA requests import confluent.pluginapi as pluginapi import confluent.httpapi as httpapi import confluent.sockapi as sockapi import eventlet import eventlet.backdoor as backdoor from eventlet.green import socket from eventlet import wsgi import multiprocessing import sys import os def run(): pluginapi.load_plugins() #TODO(jbjohnso): eventlet has a bug about unix domain sockets, this code #works with bugs fixed #dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", # family=socket.AF_UNIX) #eventlet.spawn_n(backdoor.backdoor_server, dbgsock) webservice = httpapi.HttpApi() webservice.start() sockservice = sockapi.SockApi() sockservice.start() while (1): eventlet.sleep(100)
# Copyright 2013 IBM Corporation # All rights reserved # This is the main application. # It should check for existing UDP socket to negotiate socket listen takeover # It will have three paths into it: # -Unix domain socket # -TLS socket # -WSGI # Additionally, it will be able to receive particular UDP packets to facilitate # Things like heartbeating and discovery # It also will optionally snoop SLP DA requests import confluent.pluginapi as pluginapi import confluent.httpapi as httpapi import confluent.sockapi as sockapi import eventlet import eventlet.backdoor as backdoor from eventlet.green import socket from eventlet import wsgi import multiprocessing import sys import os def run(): pluginapi.load_plugins() #TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed #dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX) #eventlet.spawn_n(backdoor.backdoor_server, dbgsock) webservice = httpapi.HttpApi() webservice.start() sockservice = sockapi.SockApi() sockservice.start() while (1): eventlet.sleep(100)
Make History example run anytime.
<?php declare(strict_types = 1); use Apixu\Exception\ApixuException; use Apixu\Exception\InternalServerErrorException; use Apixu\Exception\ErrorException; require dirname(__DIR__) . '/vendor/autoload.php'; try { $api = \Apixu\ApixuBuilder::instance()->setApiKey($_SERVER['APIXUKEY'])->build(); } catch (ApixuException $e) { die($e->getMessage()); } $q = 'London'; $since = new \DateTime(); $since->modify('-1 day'); try { $history = $api->history($q, $since); } catch (InternalServerErrorException $e) { die($e->getMessage()); } catch (ErrorException $e) { die($e->getMessage()); } catch (ApixuException $e) { die($e->getMessage()); } print_r($history->toArray());
<?php declare(strict_types = 1); use Apixu\Exception\ApixuException; use Apixu\Exception\InternalServerErrorException; use Apixu\Exception\ErrorException; require dirname(__DIR__) . '/vendor/autoload.php'; try { $api = \Apixu\ApixuBuilder::instance()->setApiKey($_SERVER['APIXUKEY'])->build(); } catch (ApixuException $e) { die($e->getMessage()); } $q = 'London'; $since = \DateTime::createFromFormat('Y-m-d', '2018-10-03'); try { $history = $api->history($q, $since); } catch (InternalServerErrorException $e) { die($e->getMessage()); } catch (ErrorException $e) { die($e->getMessage()); } catch (ApixuException $e) { die($e->getMessage()); } print_r($history->toArray());
Make MoveDirections each a byte.
package main import ( twodee "../libs/twodee" ) const ( UpLayer twodee.GameEventType = iota DownLayer UpWaterLevel DownWaterLevel PlayerMove GameIsClosing PlayExploreMusic PauseMusic ResumeMusic PlayerPickedUpItem sentinel ) const ( NumGameEventTypes = int(sentinel) ) type MoveDirection byte const ( None MoveDirection = iota North MoveDirection = 1 << (iota - 1) East South West ) type PlayerMoveEvent struct { *twodee.BasicGameEvent Dir MoveDirection } func NewPlayerMoveEvent(direction MoveDirection) (e *PlayerMoveEvent) { e = &PlayerMoveEvent{ twodee.NewBasicGameEvent(PlayerMove), direction, } return } type PlayerPickedUpItemEvent struct { *twodee.BasicGameEvent Item *Item } func NewPlayerPickedUpItemEvent(i *Item) (e *PlayerPickedUpItemEvent) { e = &PlayerPickedUpItemEvent{ twodee.NewBasicGameEvent(PlayerPickedUpItem), i, } return }
package main import ( twodee "../libs/twodee" ) const ( UpLayer twodee.GameEventType = iota DownLayer UpWaterLevel DownWaterLevel PlayerMove GameIsClosing PlayExploreMusic PauseMusic ResumeMusic PlayerPickedUpItem sentinel ) const ( NumGameEventTypes = int(sentinel) ) type MoveDirection int const ( North MoveDirection = iota East South West None ) type PlayerMoveEvent struct { *twodee.BasicGameEvent Dir MoveDirection } func NewPlayerMoveEvent(direction MoveDirection) (e *PlayerMoveEvent) { e = &PlayerMoveEvent{ twodee.NewBasicGameEvent(PlayerMove), direction, } return } type PlayerPickedUpItemEvent struct { *twodee.BasicGameEvent Item *Item } func NewPlayerPickedUpItemEvent(i *Item) (e *PlayerPickedUpItemEvent) { e = &PlayerPickedUpItemEvent{ twodee.NewBasicGameEvent(PlayerPickedUpItem), i, } return }
Switch Dartium buildbot script to stable 1.6 BUG= Review URL: https://codereview.chromium.org/504383002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291655 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' result = chromium_utils.RunCommand([sys.executable, script]) if result: print 'Running annotated steps % failed' % script return 1 # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') # Temporary until 1.6 ships on stable. if builder_name.endswith('-be') or builder_name.endswith("-dev"): script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' result = chromium_utils.RunCommand([sys.executable, script]) if result: print 'Running annotated steps % failed' % script return 1 # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
ALIEN-Github-3: Use the component name descriptor
'use strict'; angular.module('alienUiApp').controller( 'NewCloudController', ['$scope', '$modalInstance', '$http', function($scope, $modalInstance, $http) { $scope.newCloud = {}; $http.get('rest/passprovider').success(function(response) { $scope.paasProviders = response.data; for (var i=0; i<$scope.paasProviders.length; i++) { $scope.paasProviders[i].nameAndId = $scope.paasProviders[i].componentDescriptor.name + " : " + $scope.paasProviders[i].version; } }); $scope.save = function(valid) { if(valid) { $modalInstance.close($scope.newCloud); } }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }]);
'use strict'; angular.module('alienUiApp').controller( 'NewCloudController', ['$scope', '$modalInstance', '$http', function($scope, $modalInstance, $http) { $scope.newCloud = {}; $http.get('rest/passprovider').success(function(response) { $scope.paasProviders = response.data; for (var i=0; i<$scope.paasProviders.length; i++) { $scope.paasProviders[i].nameAndId = $scope.paasProviders[i].pluginName + " : " + $scope.paasProviders[i].version; } }); $scope.save = function(valid) { if(valid) { $modalInstance.close($scope.newCloud); } }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }]);
Set default updateInterval to 2 minutes. Supercell's API only updates every 10 minutes.
module.exports = { asyncLimit: 5, updateInterval: 60 * 2, // 2 Minutes clans: [ { tag: '', channelId: '' } ], coc: { apiKey: '', }, discord: { clientId: '', userToken: '' }, starColors: [ 0xff484e, // 0 Stars 0xffbc48, // 1 Star 0xc7ff48, // 2 Stars 0x4dff48 // 3 Stars ], finalMinutes: 15, messages: { prepDay: { title: 'War has been declared', body: 'The battle begins %date%\n@ %time%', color: 0x007cff }, battleDay: { title: 'The war has begun!', body: 'Attack!', color: 0x007cff }, lastHour: { title: 'The final hour is upon us!', body: 'If you haven\'t made both of your attacks you better get on it.', color: 0x007cff }, finalMinutes: { title: 'The final minutes are here!', body: '@everyone If you haven\'t made both of your attacks you better get on it.', color: 0x007cff } } }
module.exports = { asyncLimit: 5, updateInterval: 90, clans: [ { tag: '', channelId: '' } ], coc: { apiKey: '', }, discord: { clientId: '', userToken: '' }, starColors: [ 0xff484e, // 0 Stars 0xffbc48, // 1 Star 0xc7ff48, // 2 Stars 0x4dff48 // 3 Stars ], finalMinutes: 15, messages: { prepDay: { title: 'War has been declared', body: 'The battle begins %date%\n@ %time%', color: 0x007cff }, battleDay: { title: 'The war has begun!', body: 'Attack!', color: 0x007cff }, lastHour: { title: 'The final hour is upon us!', body: 'If you haven\'t made both of your attacks you better get on it.', color: 0x007cff }, finalMinutes: { title: 'The final minutes are here!', body: '@everyone If you haven\'t made both of your attacks you better get on it.', color: 0x007cff } } }
Use a Twitter Python API version that has a pip for it
from setuptools import setup setup( name='birdseed', version='0.2.1', description='Twitter random number seeder/generator', url='https://github.com/ryanmcdermott/birdseed', author='Ryan McDermott', author_email='ryan.mcdermott@ryansworks.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='random sysadmin development', py_modules=['birdseed'], install_requires=['twitter>=1.17.1'], )
from setuptools import setup setup( name='birdseed', version='0.2.1', description='Twitter random number seeder/generator', url='https://github.com/ryanmcdermott/birdseed', author='Ryan McDermott', author_email='ryan.mcdermott@ryansworks.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='random sysadmin development', py_modules=['birdseed'], install_requires=['twitter>=2.2'], )
Tweak raw text parameter name
from __future__ import unicode_literals import os try: from io import StringIO except ImportError: # pragma: no cover from StringIO import StringIO from rock.exceptions import ConfigError ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split() ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0])) def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) try: basestring def isstr(s): return isinstance(s, basestring) except NameError: # pragma: no cover def isstr(s): return isinstance(s, str) def raw(text): return text.replace('\\', '\\\\') class Shell(object): def __init__(self): self.stdin = StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
from __future__ import unicode_literals import os try: from io import StringIO except ImportError: # pragma: no cover from StringIO import StringIO from rock.exceptions import ConfigError ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split() ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0])) def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) try: basestring def isstr(s): return isinstance(s, basestring) except NameError: # pragma: no cover def isstr(s): return isinstance(s, str) def raw(value): return value.replace('\\', '\\\\') class Shell(object): def __init__(self): self.stdin = StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
FIX : ignore __esModule key
import 'ui-router-extras'; import futureRoutes from 'app/routes.json!'; var routing = function(module) { module.requires.push('ct.ui.router.extras.future'); var RouterConfig = ['$stateProvider', '$futureStateProvider', function ($stateProvider, $futureStateProvider) { $futureStateProvider.stateFactory('load', ['$q', '$ocLazyLoad', 'futureState', function($q, $ocLazyLoad, futureState) { var def = $q.defer(); System.import(futureState.src).then(loaded => { var newModule = loaded; if (!loaded.name) { var key = Object.keys(loaded); newModule = loaded[key[1]]; } $ocLazyLoad.load(newModule).then(function() { def.resolve(); }, function() { console.log('error loading: ' + loaded.name); }); }); return def.promise; }]); futureRoutes.forEach(function(r) { $futureStateProvider.futureState(r); }); }]; return RouterConfig; }; export default routing;
import 'ui-router-extras'; import futureRoutes from 'app/routes.json!'; var routing = function(module) { module.requires.push('ct.ui.router.extras.future'); var RouterConfig = ['$stateProvider', '$futureStateProvider', function ($stateProvider, $futureStateProvider) { $futureStateProvider.stateFactory('load', ['$q', '$ocLazyLoad', 'futureState', function($q, $ocLazyLoad, futureState) { var def = $q.defer(); System.import(futureState.src).then(loaded => { var newModule = loaded; if (!loaded.name) { var key = Object.keys(loaded); newModule = loaded[key[0]]; } $ocLazyLoad.load(newModule).then(function() { def.resolve(); }, function() { console.log('error loading: ' + loaded.name); }); }); return def.promise; }]); futureRoutes.forEach(function(r) { $futureStateProvider.futureState(r); }); }]; return RouterConfig; }; export default routing;
Use xml.sax.saxutils.escape instead of deprecated cgi.escape ``` /usr/local/lib/python3.6/dist-packages/mammoth/writers/html.py:34: DeprecationWarning: cgi.escape is deprecated, use html.escape instead return cgi.escape(text, quote=True) ```
from __future__ import unicode_literals from xml.sax.saxutils import escape from .abc import Writer class HtmlWriter(Writer): def __init__(self): self._fragments = [] def text(self, text): self._fragments.append(_escape_html(text)) def start(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1}>".format(name, attribute_string)) def end(self, name): self._fragments.append("</{0}>".format(name)) def self_closing(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1} />".format(name, attribute_string)) def append(self, html): self._fragments.append(html) def as_string(self): return "".join(self._fragments) def _escape_html(text): return escape(text, {'"': "&quot;"}) def _generate_attribute_string(attributes): if attributes is None: return "" else: return "".join( ' {0}="{1}"'.format(key, _escape_html(attributes[key])) for key in sorted(attributes) )
from __future__ import unicode_literals from .abc import Writer import cgi class HtmlWriter(Writer): def __init__(self): self._fragments = [] def text(self, text): self._fragments.append(_escape_html(text)) def start(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1}>".format(name, attribute_string)) def end(self, name): self._fragments.append("</{0}>".format(name)) def self_closing(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1} />".format(name, attribute_string)) def append(self, html): self._fragments.append(html) def as_string(self): return "".join(self._fragments) def _escape_html(text): return cgi.escape(text, quote=True) def _generate_attribute_string(attributes): if attributes is None: return "" else: return "".join( ' {0}="{1}"'.format(key, _escape_html(attributes[key])) for key in sorted(attributes) )
Store request information in exception
<?php class PodioError extends Exception { public $body; public $status; public $url; public function __construct($body, $status, $url) { $this->body = json_decode($body, TRUE); $this->status = $status; $this->url = $url; $this->request = $this->body['request']; if (!empty($this->body['error_description'])) { $this->message = $this->body['error_description']; } } } class PodioInvalidGrantError extends PodioError {} class PodioBadRequestError extends PodioError {} class PodioAuthorizationError extends PodioError {} class PodioForbiddenError extends PodioError {} class PodioNotFoundError extends PodioError {} class PodioConflictError extends PodioError {} class PodioGoneError extends PodioError {} class PodioRateLimitError extends PodioError {} class PodioServerError extends PodioError {} class PodioUnavailableError extends PodioError {} class PodioMissingRelationshipError extends PodioError {}
<?php class PodioError extends Exception { public $body; public $status; public $url; public function __construct($body, $status, $url) { $this->body = json_decode($body, TRUE); $this->status = $status; $this->url = $url; if (!empty($this->body['error_description'])) { $this->message = $this->body['error_description']; } } } class PodioInvalidGrantError extends PodioError {} class PodioBadRequestError extends PodioError {} class PodioAuthorizationError extends PodioError {} class PodioForbiddenError extends PodioError {} class PodioNotFoundError extends PodioError {} class PodioConflictError extends PodioError {} class PodioGoneError extends PodioError {} class PodioRateLimitError extends PodioError {} class PodioServerError extends PodioError {} class PodioUnavailableError extends PodioError {} class PodioMissingRelationshipError extends PodioError {}
Switch authenticator to migrate back to Django style passwords
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): supports_anonymous_user = False supports_object_permissions = False supports_inactive_user = False def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if '$' in user.password: if user.check_password(password): return user else: if user.password == sha1(password).hexdigest(): user.set_password(password) return user return None
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): supports_anonymous_user = False supports_object_permissions = False supports_inactive_user = False def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if '$' in user.password: if user.check_password(password): user.password = sha1(password).hexdigest() user.save() return user else: if user.password == sha1(password).hexdigest(): return user return None
Revert basic bot random turtle factor Former-commit-id: 53ffe42cf718cfedaa3ec329b0688c093513683c Former-commit-id: 6a282c036f4e11a0aa9e954f72050053059ac557 Former-commit-id: c52f52d401c4a3768c7d590fb02f3d08abd38002
from hlt import * from networking import * playerTag, gameMap = getInit() sendInit("BasicBot"+str(playerTag)) while True: moves = [] gameMap = getFrame() for y in range(0, len(gameMap.contents)): for x in range(0, len(gameMap.contents[y])): site = gameMap.contents[y][x] if site.owner == playerTag: direction = random.randint(0, 5) if site.strength < 5*site.production: direction = STILL else: for d in CARDINALS: if gameMap.getSite(Location(x, y), d).owner != playerTag: direction = d break moves.append(Move(Location(x, y), direction)) sendFrame(moves)
from hlt import * from networking import * playerTag, gameMap = getInit() sendInit("BasicBot"+str(playerTag)) turtleFactor = random.randint(1, 20) while True: moves = [] gameMap = getFrame() for y in range(0, len(gameMap.contents)): for x in range(0, len(gameMap.contents[y])): site = gameMap.contents[y][x] if site.owner == playerTag: direction = random.randint(0, 5) if site.strength < turtleFactor*site.production: direction = STILL else: for d in CARDINALS: if gameMap.getSite(Location(x, y), d).owner != playerTag: direction = d break moves.append(Move(Location(x, y), direction)) sendFrame(moves)
Set crossorigin attribute to empty string.
/* global BackgroundCheck:false */ function convertImageToDataURI(img) { var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return canvas.toDataURL('image/png'); } document.addEventListener('DOMContentLoaded', function () { var img = new Image(); img.setAttribute('crossorigin', ''); var background = document.querySelector('.demo-css--cross-origin'); var dataSrc = background.getAttribute('data-src'); img.onload = function () { var data = convertImageToDataURI(img); background.style.backgroundImage = 'url(' + data + ')'; // Prepare BackgroundCheck BackgroundCheck.init({ targets: '.target', images: background }); }; img.src = dataSrc; });
/* global BackgroundCheck:false */ function convertImageToDataURI(img) { var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return canvas.toDataURL('image/png'); } document.addEventListener('DOMContentLoaded', function () { var img = new Image(); img.setAttribute('crossorigin'); var background = document.querySelector('.demo-css--cross-origin'); var dataSrc = background.getAttribute('data-src'); img.onload = function () { var data = convertImageToDataURI(img); background.style.backgroundImage = 'url(' + data + ')'; // Prepare BackgroundCheck BackgroundCheck.init({ targets: '.target', images: background }); }; img.src = dataSrc; });
Trim whitespace on category tags
<?php namespace App\Helpers\BBCode\Tags; class WikiCategoryTag extends LinkTag { function __construct() { $this->token = false; $this->element = ''; } public function Matches($state, $token) { $peekTag = $state->Peek(5); $pt = $state->PeekTo(']'); return $peekTag == '[cat:' && $pt && strlen($pt) > 5 && strstr($pt, "\n") === false; } public function Parse($result, $parser, $state, $scope) { $index = $state->Index(); if ($state->ScanTo(':') != '[cat' || $state->Next() != ':') { $state->Seek($index, true); return false; } $str = $state->ScanTo(']'); if ($state->Next() != ']') { $state->Seek($index, true); return false; } $state->SkipWhitespace(); $result->AddMeta('WikiCategory', trim($str)); return ''; } }
<?php namespace App\Helpers\BBCode\Tags; class WikiCategoryTag extends LinkTag { function __construct() { $this->token = false; $this->element = ''; } public function Matches($state, $token) { $peekTag = $state->Peek(5); $pt = $state->PeekTo(']'); return $peekTag == '[cat:' && $pt && strlen($pt) > 5 && strstr($pt, "\n") === false; } public function Parse($result, $parser, $state, $scope) { $index = $state->Index(); if ($state->ScanTo(':') != '[cat' || $state->Next() != ':') { $state->Seek($index, true); return false; } $str = $state->ScanTo(']'); if ($state->Next() != ']') { $state->Seek($index, true); return false; } $state->SkipWhitespace(); $result->AddMeta('WikiCategory', $str); return ''; } }
Use pop for getting blocking parameter
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, title='', **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *title* is the image title. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.title(title) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. *title* is also alowed to be in *kwargs* which sets the figure title. This command always creates a new figure. Returns a list of ``Line2D`` instances. """ blocking = kwargs.pop('blocking', False) title = kwargs.pop('title', '') plt.figure() lines = plt.plot(*args, **kwargs) plt.title(title) plt.show(blocking) return lines
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, title='', **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *title* is the image title. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.title(title) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. *title* is also alowed to be in *kwargs* which sets the figure title. This command always creates a new figure. Returns a list of ``Line2D`` instances. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') title = kwargs.pop('title', '') plt.figure() lines = plt.plot(*args, **kwargs) plt.title(title) plt.show(blocking) return lines
Update check_requires_python and describe behavior in docstring
from __future__ import absolute_import import logging import sys from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers from pip._vendor.packaging import version logger = logging.getLogger(__name__) def get_metadata(dist): if (isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata('METADATA')): return dist.get_metadata('METADATA') elif dist.has_metadata('PKG-INFO'): return dist.get_metadata('PKG-INFO') def check_requires_python(requires_python): """ Check if the python version in used match the `requires_python` specifier passed. Return `True` if the version of python in use matches the requirement. Return `False` if the version of python in use does not matches the requirement. Raises an InvalidSpecifier if `requires_python` have an invalid format. """ if requires_python is None: # The package provides no information return True try: requires_python_specifier = specifiers.SpecifierSet(requires_python) except specifiers.InvalidSpecifier as e: logger.debug( "Package %s has an invalid Requires-Python entry - %s" % ( requires_python, e)) raise specifiers.InvalidSpecifier(*e.args) # We only use major.minor.micro python_version = version.parse('.'.join(map(str, sys.version_info[:3]))) return python_version in requires_python_specifier
from __future__ import absolute_import import logging import sys from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers from pip._vendor.packaging import version logger = logging.getLogger(__name__) def get_metadata(dist): if (isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata('METADATA')): return dist.get_metadata('METADATA') elif dist.has_metadata('PKG-INFO'): return dist.get_metadata('PKG-INFO') def check_requires_python(requires_python): if requires_python is None: # The package provides no information return True try: requires_python_specifier = specifiers.SpecifierSet(requires_python) except specifiers.InvalidSpecifier as e: logger.debug( "Package %s has an invalid Requires-Python entry - %s" % ( requires_python, e)) return ValueError('Wrong Specifier') # We only use major.minor.micro python_version = version.parse('.'.join(map(str, sys.version_info[:3]))) if python_version not in requires_python_specifier: return False
Clarify what the code is for
$(function(){ setup_table(); }); function setup_table() { var filter_container, filter; $('#dists').DataTable({ paging: false, autoWidth: false, scrollX: false, info: false, columnDefs: [ { targets: [ 2, 3, 4, 5, 6 ], searchable: false }, { targets: [ 6 ], orderSequence: [ "desc", "asc" ] } ] }); // Mess around with markup to accomodate the table plugin and marry // it nicely with both our JS-less version of the site and Bootstrap $('#dists_wrapper').addClass('table-responsive').unwrap(); $('#search').remove(); filter_container = $('#dists_filter'); filter = filter_container.addClass('form-group').find('[type=search]') .addClass('form-control').attr('placeholder', 'Search'); filter_container.append(filter); filter_container.find('label').remove(); filter.focus(); }
$(function(){ setup_table(); }); function setup_table() { $('#dists').DataTable({ paging: false, autoWidth: false, scrollX: false, info: false, columnDefs: [ { targets: [ 2, 3, 4, 5, 6 ], searchable: false }, { targets: [ 6 ], orderSequence: [ "desc", "asc" ] } ] }); $('#dists_wrapper').addClass('table-responsive').unwrap(); $('#search').remove(); var filter_container = $('#dists_filter'); var filter = filter_container.addClass('form-group').find('[type=search]') .addClass('form-control').attr('placeholder', 'Search'); filter_container.append(filter); filter_container.find('label').remove(); filter.focus(); }
Fix up to the child watcher example. Without yielding to the ioloop after each call to client.delete() the child znodes would be deleted but that would never be reported.
import logging import random from tornado import gen from zoonado import exc log = logging.getLogger() def arguments(parser): parser.add_argument( "--path", "-p", type=str, default="/examplewatcher", help="ZNode path to use for the example." ) def watcher_callback(children): children.sort() log.info("There are %d items now: %s", len(children), ", ".join(children)) @gen.coroutine def run(client, args): yield client.start() try: yield client.create(args.path) except exc.NodeExists: pass watcher = client.recipes.ChildrenWatcher() watcher.add_callback(args.path, watcher_callback) to_make = ["cat", "dog", "mouse", "human"] random.shuffle(to_make) for item in to_make: yield client.create(args.path + "/" + item, ephemeral=True) yield gen.sleep(1) for item in to_make: yield client.delete(args.path + "/" + item) yield gen.sleep(1)
import logging import random from tornado import gen from zoonado import exc log = logging.getLogger() def arguments(parser): parser.add_argument( "--path", "-p", type=str, default="/examplewatcher", help="ZNode path to use for the example." ) def watcher_callback(children): children.sort() log.info("There are %d items now: %s", len(children), children) @gen.coroutine def run(client, args): yield client.start() try: yield client.create(args.path) except exc.NodeExists: pass watcher = client.recipes.ChildrenWatcher() watcher.add_callback(args.path, watcher_callback) to_make = ["cat", "dog", "mouse", "human"] random.shuffle(to_make) for item in to_make: yield client.create(args.path + "/" + item, ephemeral=True) yield gen.sleep(1) for item in to_make: yield client.delete(args.path + "/" + item)
Change from_spotify and from_gpm to classmethods
class Track(): artist = "" name = "" track_id = "" def __init__(self, artist, name, track_id=""): self.artist = artist self.name = name self.track_id = track_id @classmethod def from_spotify(cls, track): track_id = track.get("id") name = track.get("name") artist = "" if "artists" in track: artist = track["artists"][0]["name"] return cls(artist, name, track_id) @classmethod def from_gpm(cls, track): return cls( track.get("artist"), track.get("title"), track.get("storeId") )
class Track(): artist = "" name = "" track_id = "" def __init__(self, artist, name, track_id=""): self.artist = artist self.name = name self.track_id = track_id @staticmethod def from_spotify(self, track): track_id = track.get("id") name = track.get("name") artist = "" if "artists" in track: artist = track["artists"][0]["name"] return Track(artist, name, track_id) @staticmethod def from_gpm(self, track): return Track( track.get("artist"), track.get("title"), track.get("storeId") )
Update to use theme header.
<?php /* * Theme Name: Bootstrap * Author: Paladin Digital */ $theme = 'themes::paladindigital.laravel-bootstrap'; ?><!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> @yield('head') @yield('meta') @yield('styles') </head> <body> @include($theme . '._nav') @yield('content') <aside> @yield('sidebar') @yield('widgets') </aside> @include($theme . '._footer') <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> @yield('scripts') </body> </html>
<!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> @yield('head') @yield('meta') @yield('styles') </head> <body> @include('themes::paladindigital.laravel-bootstrap._nav') @yield('content') <aside> @yield('sidebar') @yield('widgets') </aside> @include('themes::paladindigital.laravel-bootstrap._footer') <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> @yield('scripts') </body> </html>
fix(changed): Clarify early exit log message
"use strict"; const chalk = require("chalk"); const Command = require("@lerna/command"); const collectUpdates = require("@lerna/collect-updates"); const output = require("@lerna/output"); module.exports = factory; function factory(argv) { return new ChangedCommand(argv); } class ChangedCommand extends Command { get otherCommandConfigs() { return ["publish"]; } initialize() { this.updates = collectUpdates(this); this.count = this.updates.length; const proceedWithUpdates = this.count > 0; if (!proceedWithUpdates) { this.logger.info("", "No changed packages found"); process.exitCode = 1; } return proceedWithUpdates; } execute() { const updatedPackages = this.updates.map(({ pkg }) => ({ name: pkg.name, version: pkg.version, private: pkg.private, })); const formattedUpdates = this.options.json ? JSON.stringify(updatedPackages, null, 2) : updatedPackages .map(pkg => `- ${pkg.name}${pkg.private ? ` (${chalk.red("private")})` : ""}`) .join("\n"); output(formattedUpdates); this.logger.success( "found", "%d %s ready to publish", this.count, this.count === 1 ? "package" : "packages" ); } } module.exports.ChangedCommand = ChangedCommand;
"use strict"; const chalk = require("chalk"); const Command = require("@lerna/command"); const collectUpdates = require("@lerna/collect-updates"); const output = require("@lerna/output"); module.exports = factory; function factory(argv) { return new ChangedCommand(argv); } class ChangedCommand extends Command { get otherCommandConfigs() { return ["publish"]; } initialize() { this.updates = collectUpdates(this); this.count = this.updates.length; const proceedWithUpdates = this.count > 0; if (!proceedWithUpdates) { this.logger.info("No packages need updating"); process.exitCode = 1; } return proceedWithUpdates; } execute() { const updatedPackages = this.updates.map(({ pkg }) => ({ name: pkg.name, version: pkg.version, private: pkg.private, })); const formattedUpdates = this.options.json ? JSON.stringify(updatedPackages, null, 2) : updatedPackages .map(pkg => `- ${pkg.name}${pkg.private ? ` (${chalk.red("private")})` : ""}`) .join("\n"); output(formattedUpdates); this.logger.success( "found", "%d %s ready to publish", this.count, this.count === 1 ? "package" : "packages" ); } } module.exports.ChangedCommand = ChangedCommand;
Add apache headers to interceptor git-svn-id: 0f15cb08c8344e4f03ae17f6299848a7299a746f@1506125 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.rave.rest.interceptor; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.rave.rest.model.JsonResponseWrapper; /** * Created with IntelliJ IDEA. * User: erinnp * Date: 7/22/13 * Time: 4:56 PM * To change this template use File | Settings | File Templates. */ public class JsonResponseWrapperInterceptor extends AbstractPhaseInterceptor<Message> { public JsonResponseWrapperInterceptor() { super(Phase.WRITE); } @Override public void handleMessage(Message message) throws Fault { Object o = message.getContent(Object.class); JsonResponseWrapper wrapper = new JsonResponseWrapper(o); message.setContent(JsonResponseWrapper.class, wrapper); } }
package org.apache.rave.rest.interceptor; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.rave.rest.model.JsonResponseWrapper; /** * Created with IntelliJ IDEA. * User: erinnp * Date: 7/22/13 * Time: 4:56 PM * To change this template use File | Settings | File Templates. */ public class JsonResponseWrapperInterceptor extends AbstractPhaseInterceptor<Message> { public JsonResponseWrapperInterceptor() { super(Phase.WRITE); } @Override public void handleMessage(Message message) throws Fault { Object o = message.getContent(Object.class); JsonResponseWrapper wrapper = new JsonResponseWrapper(o); message.setContent(JsonResponseWrapper.class, wrapper); } }
Add publish task (for gh-pages)
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("default", ["scripts", "watch"]) var buildBranch = require("buildbranch") gulp.task("publish", function(cb) { buildBranch({folder: "src"} , function(err) { if (err) { throw err } console.log(pkg.name + " published.") cb() }) })
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("default", ["scripts", "watch"])
Replace out-of-place h3 with a p styled as heading Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling
<?php $showBannerOnNetwork = get_site_option('banner_setting'); $showBannerBySite = get_field('show_banner', 'options'); if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) { $bannerTitle = get_site_option('banner_title'); $bannerLinkText = get_site_option('banner_link_text'); $bannerLink = get_site_option('banner_link'); ?> <div id="user-satisfaction-survey-container" class="govuk-width-container"> <section id="user-satisfaction-survey" class="visible" aria-hidden="false"> <div class="govuk-grid-row"> <div class="govuk-grid-column-three-quarters"> <p class="govuk-heading-s"><?php echo esc_html($bannerTitle) ?></p> <p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?></a></p> </div> <div class="govuk-grid-column-one-quarter"> <p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks">No thanks</a></p> </div> </div> </section> </div> <?php } ?>
<?php $showBannerOnNetwork = get_site_option('banner_setting'); $showBannerBySite = get_field('show_banner', 'options'); if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) { $bannerTitle = get_site_option('banner_title'); $bannerLinkText = get_site_option('banner_link_text'); $bannerLink = get_site_option('banner_link'); ?> <div id="user-satisfaction-survey-container" class="govuk-width-container"> <section id="user-satisfaction-survey" class="visible" aria-hidden="false"> <div class="govuk-grid-row"> <div class="govuk-grid-column-three-quarters"> <h3><?php echo esc_html($bannerTitle) ?></h2> <p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?></a></p> </div> <div class="govuk-grid-column-one-quarter"> <p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks">No thanks</a></p> </div> </div> </section> </div> <?php } ?>
Fix trying to display result in case of not 2D vectors
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: clusters = kmeans(vectors, clusters_count=clusters_count) if len(vectors[0]) == 2: display_source(vectors) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: if len(vectors[0]) == 2: display_source(vectors) clusters = kmeans(vectors, clusters_count=clusters_count) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
Add comments and call _super
/* jshint node: true */ 'use strict'; var imagemin = require('broccoli-imagemin'); module.exports = { name: 'ember-cli-imagemin', included: function() { this._super.included.apply(this, arguments); // Default options var defaultOptions = { enabled: this.app.env === 'production' }; // If the imagemin options key is set to `false` instead of // an options object, disable the addon if (this.app.options.imagemin === false) { this.options = this.app.options.imagemin = { enabled: false }; } else { this.options = this.app.options.imagemin = this.app.options.imagemin || {}; } // Merge the default options with the passed in options for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function(type, tree) { if (this.options.enabled) { tree = imagemin(tree, this.options); } return tree; } };
/* jshint node: true */ 'use strict'; var imagemin = require('broccoli-imagemin'); module.exports = { name: 'ember-cli-imagemin', included: function(app) { this.app = app; var defaultOptions = { enabled: this.app.env === 'production' }; if (this.app.options.imagemin === false) { this.options = this.app.options.imagemin = { enabled: false }; } else { this.options = this.app.options.imagemin = this.app.options.imagemin || {}; } for (var option in defaultOptions) { if (!this.options.hasOwnProperty(option)) { this.options[option] = defaultOptions[option]; } } }, postprocessTree: function(type, tree) { if (this.options.enabled) { tree = imagemin(tree, this.options); } return tree; } };