text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move config parsing to plugin, use for SSL keys
import yaml from twisted.python import usage from twisted.plugin import IPlugin from twisted.application.service import IServiceMaker from twisted.application import internet from twisted.web import server from twisted.internet import ssl from zope.interface import implements import specter class Options(usage.Options): optParameters = [ ["port", "p", 2400, "The port to listen on"], ["config", "c", "specter.yml", "Config file"], ] class SpecterServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = "specter" description = "Distributex - A simple mutex lock service" options = Options def makeService(self, options): config = yaml.load(open(options['config'])) return internet.SSLServer( int(options['port']), server.Site(specter.SiteRoot(config)), ssl.DefaultOpenSSLContextFactory( config['ssl-key'], config['ssl-cert'] ) ) serviceMaker = SpecterServiceMaker()
from zope.interface import implements from twisted.python import usage from twisted.plugin import IPlugin from twisted.application.service import IServiceMaker from twisted.application import internet from twisted.web import server from twisted.internet import ssl import specter class Options(usage.Options): optParameters = [ ["port", "p", 2400, "The port to listen on"], ["config", "c", "specter.yml", "Config file"], ["key", None, "specter.key", "SSL key file"], ["cert", None, "specter.crt", "SSL certificate file"] ] class SpecterServiceMaker(object): implements(IServiceMaker, IPlugin) tapname = "specter" description = "Distributex - A simple mutex lock service" options = Options def makeService(self, options): return internet.SSLServer( int(options['port']), server.Site(specter.SiteRoot(options['config'])), ssl.DefaultOpenSSLContextFactory( options['key'], options['cert'] ) ) serviceMaker = SpecterServiceMaker()
Fix bug where selected requests would pop open the details page even when not needed
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), // TODO: Not sure I need to store the requests _requests = {}, _requestSelectedId = null; function requestsChanged(targetRequests) { glimpse.emit('shell.request.summary.changed', targetRequests); } // Clear Request (function() { function clearRequest() { _requestSelectedId = null; glimpse.emit('shell.request.detail.changed', null); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Data (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; if (payload.newRequest.id === _requestSelectedId) { glimpse.emit('shell.request.detail.changed', payload.newRequest); } } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function() { function triggerRequest(payload) { _requestSelectedId = payload.requestId; if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.requestId); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), // TODO: Not sure I need to store the requests _requests = {}; function requestsChanged(targetRequests) { glimpse.emit('shell.request.summary.changed', targetRequests); } // Clear Request (function() { function clearRequest() { glimpse.emit('shell.request.detail.changed', null); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Data (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; glimpse.emit('shell.request.detail.changed', payload.newRequest); } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function() { function triggerRequest(payload) { if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.id); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
Change URL for image retrieval -> better quality
package com.proxerme.library.connection; import android.support.annotation.IntRange; import android.support.annotation.NonNull; /** * Helper class, containing all the different Urls for accessing the API. * * @author Ruben Gees */ public class UrlHolder { private static final String HOST = "http://proxer.me"; private static final String NEWS = "/notifications?format=json&s=news&p="; private static final String NEWS_IMAGE = "http://cdn.proxer.me/news/tmp/"; private static final String LOGIN = "/login?format=json&action=login"; @NonNull public static String getHost() { return HOST; } @NonNull public static String getNewsUrl(@IntRange(from = 1) int page) { return getHost() + NEWS + page; } @NonNull public static String getNewsImageUrl(@NonNull String newsId, @NonNull String imageId) { return NEWS_IMAGE + newsId + "_" + imageId + ".png"; } @NonNull public static String getNewsPageUrl(@NonNull String categoryId, @NonNull String threadId) { return getHost() + "/forum/" + categoryId + "/" + threadId + "#top"; } @NonNull public static String getDonateUrl() { return getHost() + "/donate"; } @NonNull public static String getLoginUrl() { return getHost() + LOGIN; } }
package com.proxerme.library.connection; import android.support.annotation.IntRange; import android.support.annotation.NonNull; /** * Helper class, containing all the different Urls for accessing the API. * * @author Ruben Gees */ public class UrlHolder { private static final String HOST = "http://proxer.me"; private static final String NEWS = "/notifications?format=json&s=news&p="; private static final String NEWS_IMAGE = "http://cdn.proxer.me/news/"; private static final String LOGIN = "/login?format=json&action=login"; @NonNull public static String getHost() { return HOST; } @NonNull public static String getNewsUrl(@IntRange(from = 1) int page) { return getHost() + NEWS + page; } @NonNull public static String getNewsImageUrl(@NonNull String newsId, @NonNull String imageId) { return NEWS_IMAGE + newsId + "_" + imageId + ".png"; } @NonNull public static String getNewsPageUrl(@NonNull String categoryId, @NonNull String threadId) { return getHost() + "/forum/" + categoryId + "/" + threadId + "#top"; } @NonNull public static String getDonateUrl() { return getHost() + "/donate"; } @NonNull public static String getLoginUrl() { return getHost() + LOGIN; } }
Use key-responder 0.4 in the blueprint as well Updating the dependency here to match package.json. #191 updated the `ember-key-responder` version in package.json, but this version from the blueprint is used when I installed this as a addon in my project.
var RSVP = require('rsvp'); module.exports = { normalizeEntityName: function() {}, beforeInstall: function(options) { return this.addBowerPackageToProject('materialize', '~0.97.0'); }, afterInstall: function() { return RSVP.all([ this.addPackageToProject('ember-composability', '~0.1.1'), this.addPackageToProject('ember-radio-button', '1.0.7'), this.addPackageToProject('ember-new-computed', '~1.0.0'), this.addPackageToProject('ember-key-responder', '~0.4.0'), this.addPackageToProject('ember-modal-dialog', '~0.7.5'), this.addPackageToProject('ember-cli-sass', '^3.3.0'), this.addPackageToProject('ember-legacy-views', '^0.2.0') ]); } }
var RSVP = require('rsvp'); module.exports = { normalizeEntityName: function() {}, beforeInstall: function(options) { return this.addBowerPackageToProject('materialize', '~0.97.0'); }, afterInstall: function() { return RSVP.all([ this.addPackageToProject('ember-composability', '~0.1.1'), this.addPackageToProject('ember-radio-button', '1.0.7'), this.addPackageToProject('ember-new-computed', '~1.0.0'), this.addPackageToProject('ember-key-responder', '0.2.1'), this.addPackageToProject('ember-modal-dialog', '~0.7.5'), this.addPackageToProject('ember-cli-sass', '^3.3.0'), this.addPackageToProject('ember-legacy-views', '^0.2.0') ]); } }
Switch to git part two, this time URL for website
import os try: from setuptools import setup except ImportError: from distutils.core import setup def get_docs(): result = [] in_docs = False f = open(os.path.join(os.path.dirname(__file__), 'speaklater.py')) try: for line in f: if in_docs: if line.lstrip().startswith(':copyright:'): break result.append(line[4:].rstrip()) elif line.strip() == 'r"""': in_docs = True finally: f.close() return '\n'.join(result) setup( name='speaklater', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', version='1.2', url='http://github.com/mitsuhiko/speaklater', py_modules=['speaklater'], description='implements a lazy string for python useful for use with gettext', long_description=get_docs(), zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Internationalization', 'Programming Language :: Python' ] )
import os try: from setuptools import setup except ImportError: from distutils.core import setup def get_docs(): result = [] in_docs = False f = open(os.path.join(os.path.dirname(__file__), 'speaklater.py')) try: for line in f: if in_docs: if line.lstrip().startswith(':copyright:'): break result.append(line[4:].rstrip()) elif line.strip() == 'r"""': in_docs = True finally: f.close() return '\n'.join(result) setup( name='speaklater', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', version='1.2', url='http://dev.pocoo.org/hg/speaklater-main', py_modules=['speaklater'], description='implements a lazy string for python useful for use with gettext', long_description=get_docs(), zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Internationalization', 'Programming Language :: Python' ] )
Make sure blackhole implmenents its interface
<?php namespace Happyr\TranslationBundle\Service; use Happyr\TranslationBundle\Model\Message; class Blackhole implements TranslationServiceInterface { /** * @inheritDoc */ public function fetchTranslation(Message $message, $updateFs = false) { } /** * @inheritDoc */ public function updateTranslation(Message $message) { } /** * @inheritDoc */ public function flagTranslation(Message $message, $type = 0) { } /** * @inheritDoc */ public function createAsset(Message $message) { } /** * @inheritDoc */ public function downloadAllTranslations() { } /** * @inheritDoc */ public function importAllTranslations() { } /** * @inheritDoc */ public function synchronizeAllTranslations() { } /** * @inheritDoc */ public function uploadAllTranslations() { } }
<?php namespace Happyr\TranslationBundle\Service; use Happyr\TranslationBundle\Model\Message; class Blackhole implements TranslationServiceInterface { /** * @inheritDoc */ public function fetchTranslation(Message $message, $updateFs = false) { } /** * @inheritDoc */ public function updateTranslation(Message $message) { } /** * @inheritDoc */ public function flagTranslation(Message $message, $type = 0) { } /** * @inheritDoc */ public function createAsset(Message $message) { } /** * @inheritDoc */ public function downloadAllTranslations() { } /** * @inheritDoc */ public function importAllTranslations() { } /** * @inheritDoc */ public function synchronizeAllTranslations() { } }
feat(TrelloProvider): Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name data['scope'] = self.get_scope(request) # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
Change upgrade step to not use rev link.
from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
Use a chord in order to start tasks
import os import json import requests import rethinkdb as r from flask import Blueprint, current_app from utils.decorators import validate, require from utils.validators import validate_url from krunchr.vendors.rethinkdb import db from .parser import Parser from .tasks import get_file, push_data endpoint = Blueprint('analyse_url', __name__) @endpoint.route('analyse/', methods=['POST']) @require('url') @validate({ 'url': validate_url }) def analyse_url(url): name, ext = os.path.splitext(url) parse = Parser(ext=ext[1:]) response = requests.get(url, stream=True) fields = [] for chunk in response.iter_lines(1024): fields = parse(chunk) if fields: break task_id = (get_file.s(url, current_app.config['DISCO_FILES']) | push_data.s()).apply_async().task_id r.table('jobs').insert({ 'url': url, 'task_id': task_id, 'state': 'starting' }).run(db.conn) return json.dumps(fields)
import os import json import requests import rethinkdb as r from flask import Blueprint, current_app from utils.decorators import validate, require from utils.validators import validate_url from krunchr.vendors.rethinkdb import db from .parser import Parser from .tasks import get_file endpoint = Blueprint('analyse_url', __name__) @endpoint.route('analyse/', methods=['POST']) @require('url') @validate({ 'url': validate_url }) def analyse_url(url): name, ext = os.path.splitext(url) parse = Parser(ext=ext[1:]) response = requests.get(url, stream=True) fields = [] for chunk in response.iter_lines(1024): fields = parse(chunk) if fields: break task_id = get_file.delay(url, current_app.config['DISCO_FILES']).task_id r.table('jobs').insert({ 'url': url, 'task_id': task_id, 'state': 'starting' }).run(db.conn) return json.dumps(fields)
Apply Chrome Headless fix for Travis builds
/* eslint-env node */ module.exports = function (config) { config.set({ basePath: 'public', browsers: ['ChromeHeadlessCustom'], files: ['scripts/modules.js', 'scripts/test.js'], reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []), frameworks: ['mocha'], middleware: ['static'], preprocessors: { '**/*.js': ['sourcemap'], 'scripts/modules.js': process.env.COVERAGE ? ['coverage'] : [] }, coverageReporter: { type: 'json', dir: '../coverage/', subdir: '.', file: 'coverage-unmapped.json' }, static: { path: 'public' }, customLaunchers: { ChromeHeadlessCustom: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } } }); };
/* eslint-env node */ module.exports = function (config) { config.set({ basePath: 'public', browsers: ['ChromeHeadless'], files: ['scripts/modules.js', 'scripts/test.js'], reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []), frameworks: ['mocha'], middleware: ['static'], preprocessors: { '**/*.js': ['sourcemap'], 'scripts/modules.js': process.env.COVERAGE ? ['coverage'] : [] }, coverageReporter: { type: 'json', dir: '../coverage/', subdir: '.', file: 'coverage-unmapped.json' }, static: { path: 'public' } }); };
Add console log send invitations command
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): help = "Send invitations to people on the waiting list" def handle(self, *args, **options): try: count = args[0] except IndexError: print u'usage :', __name__.split('.')[-1], 'number_of_invitations' return from betainvite.models import WaitingListEntry entries = WaitingListEntry.objects.filter(invited=False)[:count] print "Sending invitations to %d people" % (entries.count()) for entry in entries: print "Sending invitation to %s" % (entry.email) entry.send_invitation()
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): help = "Send invitations to people on the waiting list" option_list = BaseCommand.option_list + ( make_option('-c', '--count', type="int", default = 10, dest="count", help='number of new invitations'), ) def handle(self, *args, **options): from betainvite.models import WaitingListEntry count = options.get('count') entries = WaitingListEntry.objects.filter(invited=False)[:count] for entry in entries: entry.send_invitation()
FIX add links to reports generated v2
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit a text to 20 chars length, if necessary strips the middle of the text and substitute it for an ellipsis. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name) <= 20: return name return name[:10] + "..." + name[-7:] def serialize(instance, file_attr='file'): """serialize -- Serialize a Picture instance into a dict. instance -- Picture instance file_attr -- attribute name that contains the FileField or ImageField """ obj = getattr(instance, file_attr) return { 'resource_id': instance.pk, 'url': obj.url, 'file_type': instance.file_type, 'name': order_name(obj.name), 'type': mimetypes.guess_type(obj.path)[0] or 'image/png', 'thumbnailUrl': obj.url, 'size': obj.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit a text to 20 chars length, if necessary strips the middle of the text and substitute it for an ellipsis. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name) <= 20: return name return name[:10] + "..." + name[-7:] def serialize(instance, file_attr='file'): """serialize -- Serialize a Picture instance into a dict. instance -- Picture instance file_attr -- attribute name that contains the FileField or ImageField """ obj = getattr(instance, file_attr) return { 'resource_id': instance.pk, 'url': obj.url, 'file_type': obj.file_type, 'name': order_name(obj.name), 'type': mimetypes.guess_type(obj.path)[0] or 'image/png', 'thumbnailUrl': obj.url, 'size': obj.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
Add "application/octet-stream" mime type for package
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import requests from platformio.util import get_api_result def pytest_generate_tests(metafunc): if "package_data" not in metafunc.fixturenames: return pkgs_manifest = get_api_result("/packages") assert isinstance(pkgs_manifest, dict) packages = [] for _, variants in pkgs_manifest.iteritems(): for item in variants: packages.append(item) metafunc.parametrize("package_data", packages) def validate_response(req): assert req.status_code == 200 assert int(req.headers['Content-Length']) > 0 def validate_package(url): r = requests.head(url, allow_redirects=True) validate_response(r) assert r.headers['Content-Type'] in ("application/x-gzip", "application/octet-stream") def test_package(package_data): assert package_data['url'].endswith("%d.tar.gz" % package_data['version']) validate_package(package_data['url'])
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import requests from platformio.util import get_api_result def pytest_generate_tests(metafunc): if "package_data" not in metafunc.fixturenames: return pkgs_manifest = get_api_result("/packages") assert isinstance(pkgs_manifest, dict) packages = [] for _, variants in pkgs_manifest.iteritems(): for item in variants: packages.append(item) metafunc.parametrize("package_data", packages) def validate_response(req): assert req.status_code == 200 assert int(req.headers['Content-Length']) > 0 def validate_package(url): r = requests.head(url, allow_redirects=True) validate_response(r) assert r.headers['Content-Type'] == "application/x-gzip" def test_package(package_data): assert package_data['url'].endswith("%d.tar.gz" % package_data['version']) validate_package(package_data['url'])
Add temp channel init with game name
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { var split = message.split(' '); var givenName = 'Temporary Channel'; // Check if user is in game, then name it that var user = this.bot.users[uid]; if (user.game !== null) { givenName = user.game.name; } // Check if name is defined, use that if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { console.log("Got command, sending"); this.bot.sendMessage({ to: cid, message: 'Hello ' + username + ' [' + message + ']', }, (err, res) => { console.log('CB', err, res); }); var split = message.split(' '); var givenName = 'Temporary Channel'; if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
Update tenant name in tenantarea
<div id="navigation" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{ route('tenantarea.home') }}"><b>{{ $currentTenant->name }}</b></a> </div> <div class="navbar-collapse collapse"> {!! Menu::render('tenantarea.header.navigation') !!} <div class="navbar-right"> {!! Menu::render('tenantarea.header.language') !!} {!! Menu::render('tenantarea.header.user') !!} </div> </div> </div> </div>
<div id="navigation" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{ route('tenantarea.home') }}"><b>{{ config('app.name') }}</b></a> </div> <div class="navbar-collapse collapse"> {!! Menu::render('tenantarea.header.navigation') !!} <div class="navbar-right"> {!! Menu::render('tenantarea.header.language') !!} {!! Menu::render('tenantarea.header.user') !!} </div> </div> </div> </div>
Increase namespace, sleep before cmd window closes
#! python3 ''' rename files in local directory with random integer names. windows screen saver isn't very good at randomizing fotos shown. Change file names regularly to provide more variety ''' import os import re import random import time random.seed() new_names = set() original_files = [] for entry in os.listdir(): if os.path.isfile(entry): if re.match(".*jpg", entry): original_files.append(entry) for counter in range(0, len(original_files)): new_value = random.randint(0,1000000000) # Make sure the new names are unique # -- note this is only the new set, the new name # may still duplicate an old name. The set is # to minimize this chance while new_value in new_names: new_value = random.randint(0,1000000000) new_names.add(new_value) for of in original_files: nf = str(new_names.pop()).zfill(10) + ".jpg" try: os.rename(of, nf) except Exception as e: print("{}: {}".format(of, e)) time.sleep(5)
''' rename files in local directory with random integer names. windows screen saver isn't very good at randomizing fotos shown. Change file names regularly to provide more variety ''' import os import re import random random.seed() new_names = set() original_files = [] for entry in os.listdir(): if os.path.isfile(entry): if re.match(".*jpg", entry): original_files.append(entry) for counter in range(0, len(original_files)): new_value = random.randint(0,100000) while new_value in new_names: new_value = random.randint(0,100000) new_names.add(new_value) for of in original_files: nf = str(new_names.pop()).zfill(6) + ".jpg" try: os.rename(of, nf) except Exception as e: print("{}: {}".format(of, e))
Revert "Fixed the function syntax" This reverts commit 9b1cba30501212f0dda428bf9228d20ac441dfff.
$(document).ready(function(){ //initialize code here function update_ranking() { $.get ( 'ajax.php?m=get_ranking', function( xml ) { var table = $( '<table>' ); $( xml ).find( 'team' ).each ( function() { var trow = $( '<tr>' ); $( '<td>' ).text( $( this ).find( 'rank' ).text() ).appendTo( trow ); $( '<td>' ).text( $( this ).find( 'name' ).text() ).appendTo( trow ); $( '<td>' ).addClass( 'score' ).text( $( this ).find( 'score' ).text() ).appendTo( trow ); trow.appendTo( table ); } ); $( '#ranking' ).html( table.html() ); } ); } });
$(document).ready(function(){ //initialize code here var update_ranking = function() { $.get ( 'ajax.php?m=get_ranking', function( xml ) { var table = $( '<table>' ); $( xml ).find( 'team' ).each ( function() { var trow = $( '<tr>' ); $( '<td>' ).text( $( this ).find( 'rank' ).text() ).appendTo( trow ); $( '<td>' ).text( $( this ).find( 'name' ).text() ).appendTo( trow ); $( '<td>' ).addClass( 'score' ).text( $( this ).find( 'score' ).text() ).appendTo( trow ); trow.appendTo( table ); } ); $( '#ranking' ).html( table.html() ); } ); } });
Add subscription to all roles except admin
Template.resident.created = function () { // Get reference to template instance var instance = this; // Get Resident ID from router instance.residentId = Router.current().params.residentId; // Subscribe to current resident instance.subscribe('residentComposite', instance.residentId); // Subscribe to all roles except admin instance.subscribe("allRolesExceptAdmin"); instance.autorun(function () { if (instance.subscriptionsReady()) { instance.resident = Residents.findOne(instance.residentId); instance.activities = Activities.find({residentIds: instance.residentId}).fetch(); } }); }; Template.resident.events({ 'click #edit-resident': function () { // Get reference to template instance var instance = Template.instance(); // Show the edit home modal Modal.show('editResident', instance.resident); } }); Template.resident.helpers({ 'resident': function () { // Get reference to template instance var instance = Template.instance(); // Get resident from template instance var resident = instance.resident; return resident; }, 'activities': function () { // Get reference to template instance const instance = Template.instance(); // Get activities from template instance var activities = instance.activities; return activities; } })
Template.resident.created = function () { // Get reference to template instance var instance = this; // Get Resident ID from router instance.residentId = Router.current().params.residentId; // Subscribe to current resident instance.subscribe('residentComposite', instance.residentId); instance.autorun(function () { if (instance.subscriptionsReady()) { instance.resident = Residents.findOne(instance.residentId); instance.activities = Activities.find({residentIds: instance.residentId}).fetch(); } }); }; Template.resident.events({ 'click #edit-resident': function () { // Get reference to template instance var instance = Template.instance(); // Show the edit home modal Modal.show('editResident', instance.resident); } }); Template.resident.helpers({ 'resident': function () { // Get reference to template instance var instance = Template.instance(); // Get resident from template instance var resident = instance.resident; return resident; }, 'activities': function () { // Get reference to template instance const instance = Template.instance(); // Get activities from template instance var activities = instance.activities; return activities; } })
Add checkmark on login message
const Discord = require('discord.js'), client = new Discord.Client; client.run = ctx => { client.on('ready', () => { if (client.user.bot) { client.destroy(); } else { ctx.gui.put(`{green-fg}➜{/green-fg} Logged in as {bold}{yellow-fg}${client.user.tag}{/yellow-fg} {green-fg}✓{/green-fg}{/bold}`); ctx.gui.put('{green-fg}➜{/green-fg} Use the join command to join a guild, dm, or channel (:join discord api #general)'); } }); client.on('message', msg => { if (ctx.current.channel && msg.channel.id === ctx.current.channel.id) { ctx.gui.putMessage(msg); } }).on('typingStart', (channel, user) => { if (ctx.current.channel && channel.id === ctx.current.channel.id) { ctx.gui.putTypingStart(channel, user); } }).on('typingStop', (channel, user) => { if (ctx.current.channel && channel.id === ctx.current.channel.id) { ctx.gui.putTypingStop(channel, user); } }); client.login(ctx.token) .catch(e => { ctx.gui.put(`{bold}Login error:{/bold} ${e.message}.`); ctx.gui.put('Try using the :login <token> command to log in.'); }); } module.exports = client;
const Discord = require('discord.js'), client = new Discord.Client; client.run = ctx => { client.on('ready', () => { if (client.user.bot) { client.destroy(); } else { ctx.gui.put(`{green-fg}➜{/green-fg} Logged in as {bold}{yellow-fg}${client.user.tag}{/yellow-fg}{/bold}`); ctx.gui.put('{green-fg}➜{/green-fg} Use the join command to join a guild, dm, or channel (:join discord api #general)'); } }); client.on('message', msg => { if (ctx.current.channel && msg.channel.id === ctx.current.channel.id) { ctx.gui.putMessage(msg); } }).on('typingStart', (channel, user) => { if (ctx.current.channel && channel.id === ctx.current.channel.id) { ctx.gui.putTypingStart(channel, user); } }).on('typingStop', (channel, user) => { if (ctx.current.channel && channel.id === ctx.current.channel.id) { ctx.gui.putTypingStop(channel, user); } }); client.login(ctx.token) .catch(e => { ctx.gui.put(`{bold}Login error:{/bold} ${e.message}.`); ctx.gui.put('Try using the :login <token> command to log in.'); }); } module.exports = client;
[MNG-3400] Implement clone properly following Effective Java' book considerations git-svn-id: 2c527eb49caa05e19d6b2be874bf74fa9d7ea670@627935 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.maven.lifecycle.statemgmt; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; /** * Setup a new project instance for the forked executions to use. * * @author jdcasey * */ public class StartForkedExecutionMojo extends AbstractMojo { private MavenProject project; private MavenSession session; private int forkId = -1; public void execute() throws MojoExecutionException, MojoFailureException { getLog().info( "Starting forked execution [fork id: " + forkId + "]" ); if ( project != null ) { try { session.addForkedProject( (MavenProject) project.clone() ); } catch ( CloneNotSupportedException e ) { throw new IllegalStateException( "MavenProject instance of class " + project.getClass().getName() + " does not support clone " ); } } } }
package org.apache.maven.lifecycle.statemgmt; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; /** * Setup a new project instance for the forked executions to use. * * @author jdcasey * */ public class StartForkedExecutionMojo extends AbstractMojo { private MavenProject project; private MavenSession session; private int forkId = -1; public void execute() throws MojoExecutionException, MojoFailureException { getLog().info( "Starting forked execution [fork id: " + forkId + "]" ); if ( project != null ) { session.addForkedProject( (MavenProject) project.clone() ); } } }
Enable occ cloud region for example Change-Id: I4f6fb7840b684e024ceca37bc5b7e2c858574665
# 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. """ Example Connection Command Make sure you can authenticate before running this command. For example: python -m examples.connection """ import sys import os_client_config from examples import common from openstack import connection def make_connection(opts): occ = os_client_config.OpenStackConfig() cloud = occ.get_one_cloud(opts.cloud, opts) opts.user_preferences.set_region(opts.user_preferences.ALL, cloud.region) auth = cloud.config['auth'] if 'insecure' in cloud.config: auth['verify'] = cloud.config['insecure'] conn = connection.Connection(preference=opts.user_preferences, **auth) return conn def run_connection(opts): conn = make_connection(opts) print("Connection: %s" % conn) for flavor in conn.compute.flavors(): print(flavor.id + " " + flavor.name) return if __name__ == "__main__": opts = common.setup() sys.exit(common.main(opts, run_connection))
# 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. """ Example Connection Command Make sure you can authenticate before running this command. For example: python -m examples.connection """ import sys import os_client_config from examples import common from openstack import connection def make_connection(opts): occ = os_client_config.OpenStackConfig() cloud = occ.get_one_cloud(opts.cloud, opts) auth = cloud.config['auth'] if 'insecure' in cloud.config: auth['verify'] = cloud.config['insecure'] conn = connection.Connection(preference=opts.user_preferences, **auth) return conn def run_connection(opts): conn = make_connection(opts) print("Connection: %s" % conn) for flavor in conn.compute.flavors(): print(flavor.id + " " + flavor.name) return if __name__ == "__main__": opts = common.setup() sys.exit(common.main(opts, run_connection))
Add official OSI name in the license metadata This makes it easier for automatic license checkers to verify the license of this package.
import os from glob import glob from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() def recursive_include(module): module_path = module.replace(".", "/") + "/" files = glob(f"{module_path}**", recursive=True) return [file.replace(module_path, "") for file in files] setup( name="kivy-ios", version="1.3.0.dev0", description="Kivy for iOS", license="MIT License", long_description=read("README.md"), long_description_content_type="text/markdown", author="The Kivy team", author_email="kivy-dev@googlegroups.com", url="https://github.com/kivy/kivy-ios", python_requires=">=3.6.0", install_requires=["cookiecutter", "pbxproj", "Pillow", "requests", "sh"], packages=find_packages(), package_data={ # note this method is a bit excessive as it includes absolutely everything # make sure you run with from a clean directory "kivy_ios": recursive_include("kivy_ios"), }, entry_points={"console_scripts": ["toolchain = kivy_ios.toolchain:main"]}, )
import os from glob import glob from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() def recursive_include(module): module_path = module.replace(".", "/") + "/" files = glob(f"{module_path}**", recursive=True) return [file.replace(module_path, "") for file in files] setup( name="kivy-ios", version="1.3.0.dev0", description="Kivy for iOS", long_description=read("README.md"), long_description_content_type="text/markdown", author="The Kivy team", author_email="kivy-dev@googlegroups.com", url="https://github.com/kivy/kivy-ios", python_requires=">=3.6.0", install_requires=["cookiecutter", "pbxproj", "Pillow", "requests", "sh"], packages=find_packages(), package_data={ # note this method is a bit excessive as it includes absolutely everything # make sure you run with from a clean directory "kivy_ios": recursive_include("kivy_ios"), }, entry_points={"console_scripts": ["toolchain = kivy_ios.toolchain:main"]}, )
Comment how to add safemode
//Load Roles var deathCreeps = require('role.deathCreeps'); var spawnCreeps = require('role.spawnCreeps'); var roleHarvester = require('role.harvester'); var roleBuilder = require('role.builder'); var roleUpgrader = require('role.upgrader'); // Consts var CONST_HARVESTER = "harvester"; var CONST_UPGRADER = "upgrader"; var CONST_BUILDER = "builder"; // How to activate safeMode: Game.spawns['Spawn1'].room.controller.activateSafeMode(); // Main Loop module.exports.loop = function () { deathCreeps.run(); spawnCreeps.run(CONST_HARVESTER); for(var indx in Game.creeps) { var creep = Game.creeps[indx]; if (creep.memory.role == 'harvester') { roleHarvester.run(creep); } if (creep.memory.role == 'upgrader') { roleUpgrader.run(creep); } if (creep.memory.role == 'builder') { roleBuilder.run(creep); } } }
//Load Roles var deathCreeps = require('role.deathCreeps'); var spawnCreeps = require('role.spawnCreeps'); var roleHarvester = require('role.harvester'); var roleBuilder = require('role.builder'); var roleUpgrader = require('role.upgrader'); // Consts var CONST_HARVESTER = "harvester"; var CONST_UPGRADER = "upgrader"; var CONST_BUILDER = "builder"; // Main Loop module.exports.loop = function () { deathCreeps.run(); spawnCreeps.run(CONST_HARVESTER); for(var indx in Game.creeps) { var creep = Game.creeps[indx]; if (creep.memory.role == 'harvester') { roleHarvester.run(creep); } if (creep.memory.role == 'upgrader') { roleUpgrader.run(creep); } if (creep.memory.role == 'builder') { roleBuilder.run(creep); } } }
Fix missing underscore in comment type
import Base from './base'; import process from 'reddit-text-js'; class Comment extends Base { _type = 'Comment'; constructor(props) { super(props); var comment = this; this.validators = { body: function() { return Base.validators.minLength(this.get('body'), 1); }.bind(comment), thingId: function() { var thingId = this.get('thingId'); return Base.validators.thingId(thingId); }.bind(comment), }; } get bodyHtml () { return process(this.get('body')); } toJSON () { var props = this.props; props._type = this._type; props.bodyHtml = this.bodyHtml; return props; } }; export default Comment;
import Base from './base'; import process from 'reddit-text-js'; class Comment extends Base { _type = 'Comment'; constructor(props) { super(props); var comment = this; this.validators = { body: function() { return Base.validators.minLength(this.get('body'), 1); }.bind(comment), thingId: function() { var thingId = this.get('thingId'); return Base.validators.thingId(thingId); }.bind(comment), }; } get bodyHtml () { return process(this.get('body')); } toJSON () { var props = this.props; props._type = this.type; props.bodyHtml = this.bodyHtml; return props; } }; export default Comment;
Modify Config file Pick DB_NAME, TOKEN_DURATION and SECRET from the environment Use the hard coded details as backup in case not in the environment
import os class Config(object): """Parent configuration class""" DEBUG = False CSRF_ENABLED = True # ALT: <variable> = os.getenv('<env_var_name>') __SECRET = 'HeathLEDGERwasTHEBESTidc' # database with host configuration removed. Defaults to machine localhost __DB_NAME = "postgresql://bruce:Inline-360@localhost/bucketlist_api" BCRYPT_LOG_ROUNDS = 13 SECRET_KEY = os.getenv('SECRET') or __SECRET AUTH_TOKEN_DURATION = os.getenv('TOKEN_DURATION') or 300 SQLALCHEMY_DATABASE_URI = os.getenv('DB_NAME') or __DB_NAME class DevelopmentConfig(Config): """Configurations for Development""" DEBUG = True BCRYPT_LOG_ROUNDS = 4 class TestingConfig(Config): """Configurations for Testing with a separate test database""" TESTING = True SQLALCHEMY_DATABASE_URI = "postgresql://bruce:Inline-360@localhost/test_db" DEBUG = True BCRYPT_LOG_ROUNDS = 4 class StagingConfig(Config): """Configurations for staging""" DEBUG = True class ProductionConfig(Config): """Configurations for Production""" DEBUG = False TESTING = False app_config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'staging': StagingConfig, 'production': ProductionConfig }
import os class Config(object): """Parent configuration class""" DEBUG = False CSRF_ENABLED = True # ALT: <variable> = os.getenv('<env_var_name>') SECRET = 'HeathLEDGERwasTHEBESTidc' # database with host configuration removed. Defaults to machine localhost SQLALCHEMY_DATABASE_URI = "postgresql://bruce:Inline-360@localhost/bucketlist_api" BCRYPT_LOG_ROUNDS = 13 class DevelopmentConfig(Config): """Configurations for Development""" DEBUG = True BCRYPT_LOG_ROUNDS = 4 class TestingConfig(Config): """Configurations for Testing with a separate test database""" TESTING = True SQLALCHEMY_DATABASE_URI = "postgresql://bruce:Inline-360@localhost/test_db" DEBUG = True BCRYPT_LOG_ROUNDS = 4 class StagingConfig(Config): """Configurations for staging""" DEBUG = True class ProductionConfig(Config): """Configurations for Production""" DEBUG = False TESTING = False app_config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'staging': StagingConfig, 'production': ProductionConfig }
Fix a bug with undefined split
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text; } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } if(changes.metadata.text) { config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text; } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); finalCb(null, changes); };
Remove .env comment for word array I'm not going to separate those into a separate file for now.
<?php if (!PHP_SAPI == 'cli') { die(); } // Only allow the CLI to run this script. // tweeter.php // https://github.com/plusreed/yourownbot-php $word1 = array("Add", "your", "words", "here"); $word2 = array("Add", "your", "words", "here"); $rand_word1 = $word1[array_rand($word1, 1)]; $rand_word2 = $word2[array_rand($word2, 1)]; require_once('twitteroauth.php'); // TODO: Separate into .env $consumerkey = "consumerkeyhere"; $consumersecret = "consumersecrethere"; $apikey = "apikeyhere"; $apisecret = "apisecrethere"; // Create a new object $tweet = new TwitterOAuth($consumerkey, $consumersecret, $apikey, $apikeysecret); // Randomize tweet $tweetMessage = '$rand_word1 your own $rand_word2!'; // Make sure generated tweet is under 280 characters if(strlen($tweetMessage) <= 280) { // Post the tweet $tweet->post('statuses/update', array('status' => $tweetMessage)); } ?>
<?php if (!PHP_SAPI == 'cli') { die(); } // Only allow the CLI to run this script. // tweeter.php // https://github.com/plusreed/yourownbot-php // TODO: Separate into .env $word1 = array("Add", "your", "words", "here"); $word2 = array("Add", "your", "words", "here"); $rand_word1 = $word1[array_rand($word1, 1)]; $rand_word2 = $word2[array_rand($word2, 1)]; require_once('twitteroauth.php'); // TODO: Separate into .env $consumerkey = "consumerkeyhere"; $consumersecret = "consumersecrethere"; $apikey = "apikeyhere"; $apisecret = "apisecrethere"; // Create a new object $tweet = new TwitterOAuth($consumerkey, $consumersecret, $apikey, $apikeysecret); // Randomize tweet $tweetMessage = '$rand_word1 your own $rand_word2!'; // Make sure generated tweet is under 280 characters if(strlen($tweetMessage) <= 280) { // Post the tweet $tweet->post('statuses/update', array('status' => $tweetMessage)); } ?>
Remove "return response" which can cause issues
// [START fs_schedule_export] const functions = require('firebase-functions'); const firestore = require('@google-cloud/firestore'); const client = new firestore.v1.FirestoreAdminClient(); // Replace BUCKET_NAME const bucket = 'gs://BUCKET_NAME'; exports.scheduledFirestoreExport = functions.pubsub .schedule('every 24 hours') .onRun((context) => { const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT; const databaseName = client.databasePath(projectId, '(default)'); return client.exportDocuments({ name: databaseName, outputUriPrefix: bucket, // Leave collectionIds empty to export all collections // or set to a list of collection IDs to export, // collectionIds: ['users', 'posts'] collectionIds: [] }) .then(responses => { const response = responses[0]; console.log(`Operation Name: ${response['name']}`); }) .catch(err => { console.error(err); throw new Error('Export operation failed'); }); }); // [END fs_schedule_export]
// [START fs_schedule_export] const functions = require('firebase-functions'); const firestore = require('@google-cloud/firestore'); const client = new firestore.v1.FirestoreAdminClient(); // Replace BUCKET_NAME const bucket = 'gs://BUCKET_NAME'; exports.scheduledFirestoreExport = functions.pubsub .schedule('every 24 hours') .onRun((context) => { const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT; const databaseName = client.databasePath(projectId, '(default)'); return client.exportDocuments({ name: databaseName, outputUriPrefix: bucket, // Leave collectionIds empty to export all collections // or set to a list of collection IDs to export, // collectionIds: ['users', 'posts'] collectionIds: [] }) .then(responses => { const response = responses[0]; console.log(`Operation Name: ${response['name']}`); return response; }) .catch(err => { console.error(err); throw new Error('Export operation failed'); }); }); // [END fs_schedule_export]
Test to see if changes are published to Github contribution graph.
package patterns; public class Singleton { public static void main(String[] args) { Elvis theKing = Elvis.INSTANCE; theKing.hasLeftTheBuilding(); AnotherElvis anotherKing = AnotherElvis.getInstance(); anotherKing.hasLeftTheBuilding(); EnumElvis enumElvis = EnumElvis.INSTANCE; enumElvis.hasLeftTheBuilding(); } } // With public static method. class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {} public void hasLeftTheBuilding() { System.out.println("Elvis:Long live the king!"); } } // With static factory. class AnotherElvis { private static final AnotherElvis INSTANCE = new AnotherElvis(); private AnotherElvis() {} public static AnotherElvis getInstance() { return INSTANCE; } public void hasLeftTheBuilding() { System.out.println("AnotherElvis: Long live the king!"); } } // With Enum. enum EnumElvis { INSTANCE; public void hasLeftTheBuilding() { System.out.println("EnumElvis:Long live the king!"); } } //
package patterns; public class Singleton { public static void main(String[] args) { Elvis theKing = Elvis.INSTANCE; theKing.hasLeftTheBuilding(); AnotherElvis anotherKing = AnotherElvis.getInstance(); anotherKing.hasLeftTheBuilding(); EnumElvis enumElvis = EnumElvis.INSTANCE; enumElvis.hasLeftTheBuilding(); } } // With public static method. class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {} public void hasLeftTheBuilding() { System.out.println("Elvis:Long live the king!"); } } // With static factory. class AnotherElvis { private static final AnotherElvis INSTANCE = new AnotherElvis(); private AnotherElvis() {} public static AnotherElvis getInstance() { return INSTANCE; } public void hasLeftTheBuilding() { System.out.println("AnotherElvis: Long live the king!"); } } // With Enum. enum EnumElvis { INSTANCE; public void hasLeftTheBuilding() { System.out.println("EnumElvis:Long live the king!"); } }
Add Dictionary to shell context
import os import coverage from flask_script import Manager, Shell from flask_migrate import Migrate, MigrateCommand from config import basedir from app import create_app, db from app.models import User, Dictionary app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default") migrate = Migrate(app, db) manager = Manager(app) def make_shell_context(): return dict(app=app, db=db, User=User, Dictionary=Dictionary) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command("db", MigrateCommand) cov = coverage.coverage(branch=True, include="app/*") @manager.command def test(coverage=False): """ Run the unit tests. """ if coverage: cov.start() import unittest tests = unittest.TestLoader().discover("tests") unittest.TextTestRunner(verbosity=2).run(tests) if coverage: cov.stop() cov.save() print("Coverage Summary:") cov.report() cov_dir = os.path.join(basedir, "tmp/coverage") cov.html_report(directory=cov_dir) print("HTML version: %s/index.html" % cov_dir) cov.erase() if __name__ == "__main__": manager.run()
import os import coverage from flask_script import Manager, Shell from flask_migrate import Migrate, MigrateCommand from config import basedir from app import create_app, db from app.models import User app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default") migrate = Migrate(app, db) manager = Manager(app) def make_shell_context(): return dict(app=app, db=db, User=User) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command("db", MigrateCommand) cov = coverage.coverage(branch=True, include="app/*") @manager.command def test(coverage=False): """ Run the unit tests. """ if coverage: cov.start() import unittest tests = unittest.TestLoader().discover("tests") unittest.TextTestRunner(verbosity=2).run(tests) if coverage: cov.stop() cov.save() print("Coverage Summary:") cov.report() cov_dir = os.path.join(basedir, "tmp/coverage") cov.html_report(directory=cov_dir) print("HTML version: %s/index.html" % cov_dir) cov.erase() if __name__ == "__main__": manager.run()
Remove artifiact of old settings
package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } }
package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getMinNumberOfGamesToCaptain(){ return (int)getSetting("minNumberOfGamesToCaptain").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } }
Remove no longer used setting.
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data') OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output') LOGGING_DIR = os.path.expandvars('$HOME/stormtracks_data/logs') FIGURE_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/figures') C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full') C20_GRIB_DATA_DIR = os.path.join(DATA_DIR, 'c20_grib') C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean') IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data') TMP_DATA_DIR = None OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output') LOGGING_DIR = os.path.expandvars('$HOME/stormtracks_data/logs') FIGURE_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/figures') C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full') C20_GRIB_DATA_DIR = os.path.join(DATA_DIR, 'c20_grib') C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean') IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
Set commenter to logged in user, not ticket requestor
from django.shortcuts import get_object_or_404, render, redirect from django.views.decorators.http import require_POST from ticketus.core.models import * from ticketus.core.forms import CommentForm def ticket_list(request, template='ui/ticket_list.html'): tickets = Ticket.objects.all() context = {'tickets': tickets} return render(request, template, context) def ticket_page(request, ticket_id, template='ui/ticket_page.html'): ticket = get_object_or_404(Ticket, id=ticket_id) context = {'ticket': ticket} return render(request, template, context) @require_POST def post_new_comment(request, ticket_id): ticket = get_object_or_404(Ticket, id=ticket_id) form = CommentForm(request.POST) if form.is_valid(): c = Comment(raw_text=form.cleaned_data['raw_text'], commenter=request.user) ticket.comment_set.add(c) return redirect(ticket)
from django.shortcuts import get_object_or_404, render, redirect from django.views.decorators.http import require_POST from ticketus.core.models import * from ticketus.core.forms import CommentForm def ticket_list(request, template='ui/ticket_list.html'): tickets = Ticket.objects.all() context = {'tickets': tickets} return render(request, template, context) def ticket_page(request, ticket_id, template='ui/ticket_page.html'): ticket = get_object_or_404(Ticket, id=ticket_id) context = {'ticket': ticket} return render(request, template, context) @require_POST def post_new_comment(request, ticket_id): ticket = get_object_or_404(Ticket, id=ticket_id) form = CommentForm(request.POST) if form.is_valid(): c = Comment(raw_text=form.cleaned_data['raw_text'], commenter=ticket.requester) ticket.comment_set.add(c) return redirect(ticket)
Add coco_test_data.py to lit ignore list
import os import sys import lit.formats import lit.util import lit.llvm # Configuration file for the 'lit' test runner. lit.llvm.initialize(lit_config, config) # name: The name of this test suite. config.name = 'TFLITEHUB' config.test_format = lit.formats.ShTest() # suffixes: A list of file extensions to treat as test files. config.suffixes = ['.py'] # test_source_root: The root path where tests are located. config.test_source_root = os.path.dirname(__file__) #config.use_default_substitutions() config.excludes = [ 'coco_test_data.py', 'imagenet_test_data.py', 'lit.cfg.py', 'lit.site.cfg.py', 'manual_test.py', 'squad_test_data.py', 'test_util.py', ] config.substitutions.extend([ ('%PYTHON', sys.executable), ]) config.environment['PYTHONPATH'] = ":".join(sys.path) project_root = os.path.dirname(os.path.dirname(__file__)) # Enable features based on -D FEATURES=hugetest,vulkan # syntax. features_param = lit_config.params.get('FEATURES') if features_param: config.available_features.update(features_param.split(','))
import os import sys import lit.formats import lit.util import lit.llvm # Configuration file for the 'lit' test runner. lit.llvm.initialize(lit_config, config) # name: The name of this test suite. config.name = 'TFLITEHUB' config.test_format = lit.formats.ShTest() # suffixes: A list of file extensions to treat as test files. config.suffixes = ['.py'] # test_source_root: The root path where tests are located. config.test_source_root = os.path.dirname(__file__) #config.use_default_substitutions() config.excludes = [ 'imagenet_test_data.py', 'lit.cfg.py', 'lit.site.cfg.py', 'manual_test.py', 'squad_test_data.py', 'test_util.py', ] config.substitutions.extend([ ('%PYTHON', sys.executable), ]) config.environment['PYTHONPATH'] = ":".join(sys.path) project_root = os.path.dirname(os.path.dirname(__file__)) # Enable features based on -D FEATURES=hugetest,vulkan # syntax. features_param = lit_config.params.get('FEATURES') if features_param: config.available_features.update(features_param.split(','))
Use a custom version of the requests package to default to SSLv3
#!/usr/bin/env python # encoding: utf-8 """ tempodb/setup.py Copyright (c) 2012 TempoDB Inc. All rights reserved. """ import os from setuptools import setup def get_version(version_tuple): version = '%s.%s' % (version_tuple[0], version_tuple[1]) if version_tuple[2]: version = '%s.%s' % (version, version_tuple[2]) return version # Dirty hack to get version number from tempodb/__init__.py - we can't # import it as it depends on dateutil, requests, and simplejson which aren't # installed until this file is read init = os.path.join(os.path.dirname(__file__), 'tempodb', '__init__.py') version_line = filter(lambda l: l.startswith('VERSION'), open(init))[0] VERSION = get_version(eval(version_line.split('=')[-1])) setup( name="tempodb", version=VERSION, author="TempoDB Inc", author_email="dev@tempo-db.com", description="A client for the TempoDB API", packages=["tempodb"], long_description="A client for the TempoDB API.", dependency_links=[ 'http://github.com/tempodb/requests/tarball/development#egg=requests-0.11.1ssl' ], install_requires=[ 'python-dateutil==1.5', 'requests==0.11.1ssl', 'simplejson', ] )
#!/usr/bin/env python # encoding: utf-8 """ tempodb/setup.py Copyright (c) 2012 TempoDB Inc. All rights reserved. """ import os from setuptools import setup def get_version(version_tuple): version = '%s.%s' % (version_tuple[0], version_tuple[1]) if version_tuple[2]: version = '%s.%s' % (version, version_tuple[2]) return version # Dirty hack to get version number from tempodb/__init__.py - we can't # import it as it depends on dateutil, requests, and simplejson which aren't # installed until this file is read init = os.path.join(os.path.dirname(__file__), 'tempodb', '__init__.py') version_line = filter(lambda l: l.startswith('VERSION'), open(init))[0] VERSION = get_version(eval(version_line.split('=')[-1])) setup( name="tempodb", version=VERSION, author="TempoDB Inc", author_email="dev@tempo-db.com", description="A client for the TempoDB API", packages=["tempodb"], long_description="A client for the TempoDB API.", install_requires=[ 'python-dateutil==1.5', 'requests', 'simplejson', ] )
Reduce duplicated code when initializing streams
Elm.Native.Keyboard = {}; Elm.Native.Keyboard.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Keyboard = localRuntime.Native.Keyboard || {}; if (localRuntime.Native.Keyboard.values) { return localRuntime.Native.Keyboard.values; } var NS = Elm.Native.Signal.make(localRuntime); function keyEvent(event) { return { _: {}, alt: event.altKey, meta: event.metaKey, keyCode: event.keyCode }; } function keyStream(node, eventName, handler) { var stream = NS.input(null); localRuntime.addListener([stream.id], node, eventName, function(e) { localRuntime.notify(stream.id, handler(e)); }); return stream; } var downs = keyStream(document, 'keydown', keyEvent); var ups = keyStream(document, 'keyup', keyEvent); var presses = keyStream(document, 'keypress', keyEvent); var blurs = keyStream(window, 'blur', function() { return null; }); return localRuntime.Native.Keyboard.values = { downs: downs, ups: ups, blurs: blurs, presses: presses }; };
Elm.Native.Keyboard = {}; Elm.Native.Keyboard.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Keyboard = localRuntime.Native.Keyboard || {}; if (localRuntime.Native.Keyboard.values) { return localRuntime.Native.Keyboard.values; } var NS = Elm.Native.Signal.make(localRuntime); function keyEvent(event) { return { _: {}, alt: event.altKey, meta: event.metaKey, keyCode: event.keyCode }; } var downs = NS.input(null); localRuntime.addListener([downs.id], document, 'keydown', function down(e) { localRuntime.notify(downs.id, keyEvent(e)); }); var ups = NS.input(null); localRuntime.addListener([ups.id], document, 'keyup', function up(e) { localRuntime.notify(ups.id, keyEvent(e)); }); var presses = NS.input(null); localRuntime.addListener([downs.id], document, 'keypress', function press(e) { localRuntime.notify(press.id, keyEvent(e)); }); var blurs = NS.input(null); localRuntime.addListener([blurs.id], window, 'blur', function blur(e) { localRuntime.notify(blurs.id, null); }); return localRuntime.Native.Keyboard.values = { downs: downs, ups: ups, blurs: blurs, presses: presses }; };
Include CSS files in VUI loaded library.
'use strict'; var configViewer = require('./configViewer'); var jQueryName = 'D2L.LP.Web.UI.Html.jQuery'; var vuiName = 'D2L.LP.Web.UI.Html.Vui'; module.exports.jquery = function( opts ) { return configViewer.readConfig( jQueryName, opts ) .then( function( value ) { return value.jqueryBaseLocation + 'jquery.js'; } ); }; module.exports.jqueryui = function( opts ) { return configViewer.readConfig( jQueryName, opts ) .then( function( value ) { return value.jqueryUIBaseLocation + 'jquery-ui.js'; } ); }; module.exports.valenceui = function( opts ) { return configViewer.readConfig( vuiName, opts ) .then( function( value ) { return value.baseLocation + 'valenceui.js'; } ); }; module.exports.jquerySync = function( opts ) { return configViewer.readConfigSync( jQueryName, opts ).jqueryBaseLocation + 'jquery.js'; }; module.exports.jqueryuiSync = function( opts ) { return configViewer.readConfigSync( jQueryName, opts ).jqueryUIBaseLocation + 'jquery-ui.js'; }; module.exports.valenceuiSync = function( opts ) { return [ configViewer.readConfigSync( vuiName, opts ).baseLocation + 'valenceui.css', configViewer.readConfigSync( vuiName, opts ).baseLocation + 'valenceui.js' ]; };
'use strict'; var configViewer = require('./configViewer'); var jQueryName = 'D2L.LP.Web.UI.Html.jQuery'; var vuiName = 'D2L.LP.Web.UI.Html.Vui'; module.exports.jquery = function( opts ) { return configViewer.readConfig( jQueryName, opts ) .then( function( value ) { return value.jqueryBaseLocation + 'jquery.js'; } ); }; module.exports.jqueryui = function( opts ) { return configViewer.readConfig( jQueryName, opts ) .then( function( value ) { return value.jqueryUIBaseLocation + 'jquery-ui.js'; } ); }; module.exports.valenceui = function( opts ) { return configViewer.readConfig( vuiName, opts ) .then( function( value ) { return value.baseLocation + 'valenceui.js'; } ); }; module.exports.jquerySync = function( opts ) { return configViewer.readConfigSync( jQueryName, opts ).jqueryBaseLocation + 'jquery.js'; }; module.exports.jqueryuiSync = function( opts ) { return configViewer.readConfigSync( jQueryName, opts ).jqueryUIBaseLocation + 'jquery-ui.js'; }; module.exports.valenceuiSync = function( opts ) { return configViewer.readConfigSync( vuiName, opts ).baseLocation + 'valenceui.js'; };
Remove qualification that idea-generation starts the retro in earnest - the prime directive is a part of the retro proper
export default { "prime-directive": { alert: null, confirmationMessage: "Are you sure want to proceed to the Idea Generation stage?", nextStage: "idea-generation", progressionButton: { copy: "Proceed to Idea Generation", iconClass: "arrow right", }, }, "idea-generation": { alert: null, confirmationMessage: "Are you sure you would like to proceed to the action items stage?", nextStage: "action-items", progressionButton: { copy: "Proceed to Action Items", iconClass: "arrow right", }, }, "action-items": { alert: null, confirmationMessage: null, nextStage: "action-item-distribution", progressionButton: { copy: "Send Action Items", iconClass: "send", }, }, "action-item-distribution": { alert: { headerText: "Action Items Distributed", bodyText: "The facilitator has distributed this retro's action items. You will receive an email breakdown shortly!", }, confirmationMessage: null, nextStage: null, progressionButton: null, }, }
export default { "prime-directive": { alert: null, confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.", nextStage: "idea-generation", progressionButton: { copy: "Proceed to Idea Generation", iconClass: "arrow right", }, }, "idea-generation": { alert: null, confirmationMessage: "Are you sure you would like to proceed to the action items stage?", nextStage: "action-items", progressionButton: { copy: "Proceed to Action Items", iconClass: "arrow right", }, }, "action-items": { alert: null, confirmationMessage: null, nextStage: "action-item-distribution", progressionButton: { copy: "Send Action Items", iconClass: "send", }, }, "action-item-distribution": { alert: { headerText: "Action Items Distributed", bodyText: "The facilitator has distributed this retro's action items. You will receive an email breakdown shortly!", }, confirmationMessage: null, nextStage: null, progressionButton: null, }, }
Set default limit for blog to 6.
<?php namespace Yajra\CMS\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Yajra\CMS\Entities\Category; use Yajra\CMS\Events\CategoryWasViewed; class CategoryController extends Controller { /** * Display an article. * * @param \Yajra\CMS\Entities\Category $category * @param \Illuminate\Http\Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Category $category, Request $request) { $category->increment('hits'); $layout = $request->query('layout', 'blog'); $limit = $request->get('limit', $layout == 'list' ? 10 : 6); /** @var \Illuminate\Contracts\Pagination\Paginator $articles */ $articles = $category->articles()->published()->isNotPage()->latest()->paginate($limit); if ($layout === 'list') { $articles->appends('layout', 'list'); } if ($request->has('limit')) { $articles->appends('limit', $limit); } event(new CategoryWasViewed($category)); return view("category.$layout", compact('category', 'articles', 'limit')); } }
<?php namespace Yajra\CMS\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Yajra\CMS\Entities\Category; use Yajra\CMS\Events\CategoryWasViewed; class CategoryController extends Controller { /** * Display an article. * * @param \Yajra\CMS\Entities\Category $category * @param \Illuminate\Http\Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Category $category, Request $request) { $category->increment('hits'); $layout = $request->query('layout', 'blog'); $limit = $request->get('limit', $layout == 'list' ? 10 : 5); /** @var \Illuminate\Contracts\Pagination\Paginator $articles */ $articles = $category->articles()->published()->isNotPage()->latest()->paginate($limit); if ($layout === 'list') { $articles->appends('layout', 'list'); } if ($request->has('limit')) { $articles->appends('limit', $limit); } event(new CategoryWasViewed($category)); return view("category.$layout", compact('category', 'articles', 'limit')); } }
Fix null processing in QuoteString Fix null processing in QuoteString when use prepareStatement with null values for placeholders
/** * Quotes a string for SQL statements * * @param {string|number} string * @returns {string} the quoted string, or the passed parameter if it is a finite number */ function QuoteString(string) { if (typeof string === 'number') { if (Number.isFinite(string) === false) { return QuoteString(string.toString()); } return string.toString(); } else if (string === null) { return 'null'; } string = string.toString(); string = string.replace(/\\/g, '\\\\'); string = string.replace('\x00', '\\x00'); string = string.replace('\n', '\\n'); string = string.replace('\r', '\\r'); string = string.replace("'", "''"); return "'" + string + "'"; } module.exports = QuoteString;
/** * Quotes a string for SQL statements * * @param {string|number} string * @returns {string} the quoted string, or the passed parameter if it is a finite number */ function QuoteString(string) { if (typeof string === 'number') { if (Number.isFinite(string) === false) { return QuoteString(string.toString()); } return string.toString(); } string = string.toString(); string = string.replace(/\\/g, '\\\\'); string = string.replace('\x00', '\\x00'); string = string.replace('\n', '\\n'); string = string.replace('\r', '\\r'); string = string.replace("'", "''"); return "'" + string + "'"; } module.exports = QuoteString;
Make compatible with Meteor 2.3+
Package.describe({ name: 'dburles:two-factor', version: '1.3.1', summary: 'Two-factor authentication for accounts-password', git: 'https://github.com/dburles/meteor-two-factor.git', documentation: 'README.md', }); Package.onUse(function(api) { api.versionsFrom(['1.2.1', '2.3']); api.use(['ecmascript', 'check']); api.use('reactive-dict', 'client'); api.use('accounts-password', ['client', 'server']); api.addFiles('common.js'); api.addFiles('client.js', 'client'); api.addFiles('server.js', 'server'); api.export('twoFactor'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('tinytest'); api.use('dburles:two-factor'); api.addFiles('tests.js'); });
Package.describe({ name: 'dburles:two-factor', version: '1.3.0', summary: 'Two-factor authentication for accounts-password', git: 'https://github.com/dburles/meteor-two-factor.git', documentation: 'README.md', }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use(['ecmascript', 'check']); api.use('reactive-dict', 'client'); api.use('accounts-password', ['client', 'server']); api.addFiles('common.js'); api.addFiles('client.js', 'client'); api.addFiles('server.js', 'server'); api.export('twoFactor'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('tinytest'); api.use('dburles:two-factor'); api.addFiles('tests.js'); });
Enable to type dot(.) in title Changed 'keypress' event to 'keyup' event since keypress event is for printable characters. Author: Mina Lee <minalee@nflabs.com> Closes #95 from minahlee/fix/enable_dot_in_title and squashes the following commits: 9100fa6 [Mina Lee] Enable to type dot(.) in title
/* * 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. */ 'use strict'; /** * @ngdoc directive * @name zeppelinWebApp.directive:delete * @description * # ngDelete */ angular.module('zeppelinWebApp').directive('ngDelete', function() { return function(scope, element, attrs) { element.bind('keydown keyup', function(event) { if (event.which === 27 || event.which === 46) { scope.$apply(function() { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; });
/* * 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. */ 'use strict'; /** * @ngdoc directive * @name zeppelinWebApp.directive:delete * @description * # ngDelete */ angular.module('zeppelinWebApp').directive('ngDelete', function() { return function(scope, element, attrs) { element.bind('keydown keypress', function(event) { if (event.which === 27 || event.which === 46) { scope.$apply(function() { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; });
Make path parser robust to trailing /
import json import sys import re def parse(version, endpoint_path): """Map an HTTP endpoint path to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) endpoint_path_parts = endpoint_path.strip('/').split('/') paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)] for path_parts in paths_parts: found = True for (endpoint_part, part) in zip(endpoint_path_parts, path_parts): if not part.startswith('{') and endpoint_part != part: found = False break if found: sys.stdout.flush() return '{}/{}'.format(version, '/'.join(path_parts)) return None
import json import sys import re def parse(version, endpoint_path): """Map an HTTP call to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) endpoint_path_parts = endpoint_path.split('/') paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)] for path_parts in paths_parts: found = True for (endpoint_part, part) in zip(endpoint_path_parts, path_parts): print endpoint_part, part if not part.startswith('{') and endpoint_part != part: found = False break if found: sys.stdout.flush() return '{}/{}'.format(version, '/'.join(path_parts)) return None
Add space on tab with no suggestion
package ishell import "strings" type iCompleter struct { cmd *Cmd } func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) { words := strings.Fields(string(line)) var cWords []string prefix := "" if len(words) > 0 && line[pos-1] != ' ' { prefix = words[len(words)-1] cWords = ic.getWords(words[:len(words)-1]) } else { cWords = ic.getWords(words) } var suggestions [][]rune for _, w := range cWords { if strings.HasPrefix(w, prefix) { suggestions = append(suggestions, []rune(strings.TrimPrefix(w, prefix))) } } if len(suggestions) == 1 && prefix != "" && string(suggestions[0]) == "" { suggestions = [][]rune{[]rune(" ")} } return suggestions, len(prefix) } func (ic iCompleter) getWords(w []string) (s []string) { cmd, args := ic.cmd.FindCmd(w) if cmd == nil { cmd, args = ic.cmd, w } if cmd.Completer != nil { return cmd.Completer(args) } for k := range cmd.children { s = append(s, k) } return }
package ishell import "strings" type iCompleter struct { cmd *Cmd } func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) { words := strings.Fields(string(line)) var cWords []string prefix := "" if len(words) > 0 && line[pos-1] != ' ' { prefix = words[len(words)-1] cWords = ic.getWords(words[:len(words)-1]) } else { cWords = ic.getWords(words) } var suggestions [][]rune for _, w := range cWords { if strings.HasPrefix(w, prefix) { suggestions = append(suggestions, []rune(strings.TrimPrefix(w, prefix))) } } return suggestions, len(prefix) } func (ic iCompleter) getWords(w []string) (s []string) { cmd, args := ic.cmd.FindCmd(w) if cmd == nil { cmd, args = ic.cmd, w } if cmd.Completer != nil { return cmd.Completer(args) } for k := range cmd.children { s = append(s, k) } return }
Update download URL and add more output to downloader.
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(urlbase, name, into): print("Downloading " + name) fname = download(os.path.join(urlbase, name), into) print("Extracting...") with tarfile.open(fname) as f: f.extractall(path=into) if __name__ == '__main__': baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/' datadir = here('data') # First, download the Tosato datasets. download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir) download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir) download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir) download_extract(baseurl, 'HOC.tar.bz2', into=datadir) download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir) download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir) download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir) print("Done.")
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(url, into): fname = download(url, into) print("Extracting...") with tarfile.open(fname) as f: f.extractall(path=into) if __name__ == '__main__': baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/' datadir = here('data') # First, download the Tosato datasets. download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir) download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir) download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir) download_extract(baseurl + 'HOC.tar.bz2', into=datadir) download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir) download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir) download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
Disable manual input of date. Made the input field read-only to prevent input of date manually.
from django import forms from django.conf import settings from moviealert.base.widgets import CalendarWidget from .models import TaskList, RegionData class MovieForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MovieForm, self).__init__(*args, **kwargs) self.fields['movie_date'] = forms.DateField( widget=CalendarWidget(attrs={"readonly": "readonly", "style": "background:white;"}), input_formats=settings.ALLOWED_DATE_FORMAT) self.fields["city"] = forms.CharField( widget=forms.TextInput(attrs={"id": "txtSearch"})) self.fields["city"].label = "City Name" def clean(self): cleaned_data = super(MovieForm, self).clean() cleaned_data['city'] = RegionData.objects.get( bms_city=cleaned_data['city']) class Meta: model = TaskList exclude = ("username", "task_completed", "notified", "movie_found",)
from django import forms from django.conf import settings from moviealert.base.widgets import CalendarWidget from .models import TaskList, RegionData class MovieForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MovieForm, self).__init__(*args, **kwargs) self.fields['movie_date'] = forms.DateField( widget=CalendarWidget, input_formats=settings.ALLOWED_DATE_FORMAT) self.fields["city"] = forms.CharField( widget=forms.TextInput(attrs={"id": "txtSearch"})) self.fields["city"].label = "City Name" def clean(self): cleaned_data = super(MovieForm, self).clean() cleaned_data['city'] = RegionData.objects.get( bms_city=cleaned_data['city']) class Meta: model = TaskList exclude = ("username", "task_completed", "notified", "movie_found",)
Save hometown and current location into user profile
Accounts.onCreateUser(function(options, user) { console.log(options); console.log(user); if (options.profile) { options.profile.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture?type=large"; user.profile = options.profile; } result = Meteor.http.get("https://graph.facebook.com/me", { params: { access_token: user.services.facebook.accessToken } }); if (result.error) throw result.error; user.services.facebook.hometown = result.data.hometown; user.services.facebook.location = result.data.location; return user; }); ServiceConfiguration.configurations.remove({ service: "facebook" }); ServiceConfiguration.configurations.insert({ service: "facebook", appId: "555425911257817", secret: "a8b54ac1cfa42ec80b9200688ac24bb5" }); // Meteor.loginWithFacebook({ // // requestPermissions: ['user'] // }, function (err) { // if (err) // Session.set('errorMessage', err.reason || 'Unknown error'); // });
// Accounts.loginServiceConfiguration.remove({ // service: "facebook" // }); // Accounts.loginServiceConfiguration.insert({ // service: "facebook", // appId: "607442322661481", // secret: "7731fdbd9a85748fc2e16038f8cfebe6" // }); Accounts.onCreateUser(function(options, user) { console.log(options); console.log(user); if (options.profile) { options.profile.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture?type=large"; user.profile = options.profile; } return user; }); ServiceConfiguration.configurations.remove({ service: "facebook" }); ServiceConfiguration.configurations.insert({ service: "facebook", appId: "555425911257817", secret: "a8b54ac1cfa42ec80b9200688ac24bb5" }); // Meteor.loginWithFacebook({ // // requestPermissions: ['user'] // }, function (err) { // if (err) // Session.set('errorMessage', err.reason || 'Unknown error'); // });
Simplify log messages in bioentities/buildIndex/status
package uk.ac.ebi.atlas.model.resource; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; public abstract class AtlasResource<T> { protected final Path path; AtlasResource(Path path) { this.path = path; } public boolean exists() { return Files.exists(path); } public boolean existsAndIsNonEmpty() { return exists() && ( path.toFile().isDirectory() ? path.toFile().list().length > 0 : path.toFile().length() > 0 ); } public boolean isReadable() { return Files.isReadable(path); } public abstract T get(); public Reader getReader() throws IOException { return Files.newBufferedReader(path, StandardCharsets.UTF_8); } public long size() { return path.toFile().length(); } @Override public String toString() { return this.getClass().getSimpleName() + " with path " + path.toString(); } }
package uk.ac.ebi.atlas.model.resource; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; public abstract class AtlasResource<T> { protected final Path path; AtlasResource(Path path) { this.path = path; } public boolean exists() { return Files.exists(path); } public boolean existsAndIsNonEmpty() { return exists() && ( path.toFile().isDirectory() ? path.toFile().list().length > 0 : path.toFile().length() > 0 ); } public boolean isReadable() { return Files.isReadable(path); } public abstract T get(); public Reader getReader() throws IOException { return Files.newBufferedReader(path, StandardCharsets.UTF_8); } public long size() { return path.toFile().length(); } @Override public String toString() { return this.getClass().getName() + " with path " + path.toString(); } }
Allow setting Route.useNavigation to an actual navigation component to replace the default
import React from 'react' import {Grid, Row, Col} from 'react-bootstrap' import SecurityBanner from '../components/SecurityBanner' import Header from '../components/Header' import Nav from '../components/Nav' export default class App extends React.Component { render() { return ( <div className="anet"> <SecurityBanner location={this.props.location} /> <Header /> <div className="container"> {this.props.children.type.useNavigation === false ? ( <Col xs={12}> {this.props.children} </Col> ) : ( <Grid> <Row> <Col sm={3}> {this.props.children.type.useNavigation || <Nav />} </Col> <Col sm={9}> {this.props.children} </Col> </Row> </Grid> )} </div> </div> ) } }
import React from 'react' import {Grid, Row, Col} from 'react-bootstrap' import SecurityBanner from '../components/SecurityBanner' import Header from '../components/Header' import Nav from '../components/Nav' export default class App extends React.Component { render() { return ( <div className="anet"> <SecurityBanner location={this.props.location} /> <Header /> <div className="container"> {this.props.children.type.useNavigation === false ? ( <Col xs={12}> {this.props.children} </Col> ) : ( <Grid> <Row> <Col sm={3}> <Nav /> </Col> <Col sm={9}> {this.props.children} </Col> </Row> </Grid> )} </div> </div> ) } }
Add exitcode and segv check for timing util
#!/usr/bin/python # # Small helper for perftest runs. # import os import sys import subprocess def main(): count = int(sys.argv[1]) time_min = None for i in xrange(count): cmd = [ 'time', '-f', '%U', '--quiet', sys.argv[2], # cmd sys.argv[3] # testcase ] #print(repr(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() retval = p.wait() #print(i, retval, stdout, stderr) if retval == 139: print 'segv' sys.exit(1) elif retval != 0: print 'n/a' sys.exit(1) time = float(stderr) #print(i, time) if time_min is None: time_min = time else: time_min = min(time_min, time) # /usr/bin/time has only two digits of resolution print('%.02f' % time_min) sys.exit(0) if __name__ == '__main__': main()
#!/usr/bin/python # # Small helper for perftest runs. # import os import sys import subprocess def main(): count = int(sys.argv[1]) time_min = None for i in xrange(count): cmd = [ 'time', '-f', '%U', '--quiet', sys.argv[2], # cmd sys.argv[3] # testcase ] #print(repr(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() retval = p.wait() #print(i, retval, stdout, stderr) if retval != 0: print 'n/a' return time = float(stderr) #print(i, time) if time_min is None: time_min = time else: time_min = min(time_min, time) # /usr/bin/time has only two digits of resolution print('%.02f' % time_min) if __name__ == '__main__': main()
Remove extra blank line for consistency
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong>{this.props.title}</strong> {hint ? ' ' + hint : null} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, }; module.exports = DetailPaneSection;
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong>{this.props.title}</strong> {hint ? ' ' + hint : null} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, }; module.exports = DetailPaneSection;
Update url of pip package
""" CartoDB Services Python Library See: https://github.com/CartoDB/geocoder-api """ from setuptools import setup, find_packages setup( name='cartodb_services', version='0.6.2', description='CartoDB Services API Python Library', url='https://github.com/CartoDB/dataservices-api', author='Data Services Team - CartoDB', author_email='dataservices@cartodb.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Mapping comunity', 'Topic :: Maps :: Mapping Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='maps api mapping tools geocoder routing', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'dev': ['unittest'], 'test': ['unittest', 'nose', 'mockredispy', 'mock'], } )
""" CartoDB Services Python Library See: https://github.com/CartoDB/geocoder-api """ from setuptools import setup, find_packages setup( name='cartodb_services', version='0.6.2', description='CartoDB Services API Python Library', url='https://github.com/CartoDB/geocoder-api', author='Data Services Team - CartoDB', author_email='dataservices@cartodb.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Mapping comunity', 'Topic :: Maps :: Mapping Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='maps api mapping tools geocoder routing', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'dev': ['unittest'], 'test': ['unittest', 'nose', 'mockredispy', 'mock'], } )
fix(ZNTA-2146): Remove Helmet from ProjectVersion page
import React, {Component} from 'react' import PropTypes from 'prop-types' import {connect} from 'react-redux' import TMMergeModal from './TMMergeModal' import { toggleTMMergeModal } from '../../actions/version-actions' /** * Root component for Project Version Page */ class ProjectVersion extends Component { static propTypes = { openTMMergeModal: PropTypes.func.isRequired, params: PropTypes.shape({ project: PropTypes.string.isRequired, version: PropTypes.string.isRequired }) } render () { const { params } = this.props return ( <div className='page wide-view-theme' id='version'> <div className='center-block'> <TMMergeModal projectSlug={params.project} versionSlug={params.version} /> </div> </div> ) } } const mapDispatchToProps = (dispatch) => { return { openTMMergeModal: () => { dispatch(toggleTMMergeModal()) } } } export default connect(undefined, mapDispatchToProps)(ProjectVersion)
import React, {Component} from 'react' import PropTypes from 'prop-types' import {connect} from 'react-redux' import Helmet from 'react-helmet' import TMMergeModal from './TMMergeModal' import { toggleTMMergeModal } from '../../actions/version-actions' /** * Root component for Project Version Page */ class ProjectVersion extends Component { static propTypes = { openTMMergeModal: PropTypes.func.isRequired, params: PropTypes.shape({ project: PropTypes.string.isRequired, version: PropTypes.string.isRequired }) } render () { const { params } = this.props return ( <div className='page wide-view-theme' id='version'> <Helmet title='ProjectVersion' /> <div className='center-block'> <TMMergeModal projectSlug={params.project} versionSlug={params.version} /> </div> </div> ) } } const mapDispatchToProps = (dispatch) => { return { openTMMergeModal: () => { dispatch(toggleTMMergeModal()) } } } export default connect(undefined, mapDispatchToProps)(ProjectVersion)
Fix open external link (mobile)
'use strict'; angular.module('copayApp.services').service('externalLinkService', function(platformInfo, nodeWebkitService, popupService, gettextCatalog, $window, $log, $timeout) { var _restoreHandleOpenURL = function(old) { $timeout(function() { $window.handleOpenURL = old; }, 500); }; this.open = function(url, optIn, title, message, okText, cancelText) { var old = $window.handleOpenURL; $window.handleOpenURL = function(url) { // Ignore external URLs $log.debug('Skip: ' + url); }; if (platformInfo.isNW) { nodeWebkitService.openExternalLink(url); _restoreHandleOpenURL(old); } else { if (optIn) { var message = gettextCatalog.getString(message), title = gettextCatalog.getString(title), okText = gettextCatalog.getString(okText), cancelText = gettextCatalog.getString(cancelText), openBrowser = function(res) { if (res) window.open(url, '_system'); _restoreHandleOpenURL(old); }; popupService.showConfirm(title, message, okText, cancelText, openBrowser); } else { window.open(url, '_system'); _restoreHandleOpenURL(old); } } }; });
'use strict'; angular.module('copayApp.services').service('externalLinkService', function(platformInfo, nodeWebkitService, popupService, gettextCatalog, $window, $log, $timeout) { this.open = function(url, optIn, title, message, okText, cancelText) { var old = $window.handleOpenURL; $window.handleOpenURL = function(url) { // Ignore external URLs $log.debug('Skip: ' + url); }; $timeout(function() { $window.handleOpenURL = old; }, 500); if (platformInfo.isNW) { nodeWebkitService.openExternalLink(url); } else { if (optIn) { var message = gettextCatalog.getString(message), title = gettextCatalog.getString(title), okText = gettextCatalog.getString(okText), cancelText = gettextCatalog.getString(cancelText), openBrowser = function(res) { if (res) window.open(url, '_system'); }; popupService.showConfirm(title, message, okText, cancelText, openBrowser); } else window.open(url, '_system'); } }; });
Add new final v1.0.0 PyPI release version
from distutils.core import setup setup( name = 'pybenchmark', packages = ['pybenchmark'], # this must be the same as the name above version = '1.0.0', description = 'A benchmark utility used in performance tests.', author = 'Eugene Duboviy', author_email = 'eugene.dubovoy@gmail.com', url = 'https://github.com/duboviy/pybenchmark', # use the URL to the github repo download_url = 'https://github.com/duboviy/pybenchmark/tarball/1.0.0', # I'll explain this in a second keywords = ['benchmark', 'performance', 'testing'], # arbitrary keywords classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description=""" When measuring execution time, the result depends on the computer hardware. To be able to produce a universal measure, the simplest way is to benchmark the speed of a fixed sequence of code and calculate a ratio out of it. From there, the time taken by a function can be translated to a universal value that can be compared on any computer. Python provides a benchmark utility in its test package that measures the duration of a sequence of well-chosen operations. pybenchmark designed to provide a simple and pythonic way to get performance data. """, install_requires=[ 'psutil', 'gevent', ], )
from distutils.core import setup setup( name = 'pybenchmark', packages = ['pybenchmark'], # this must be the same as the name above version = '0.0.6', description = 'A benchmark utility used in performance tests.', author = 'Eugene Duboviy', author_email = 'eugene.dubovoy@gmail.com', url = 'https://github.com/duboviy/pybenchmark', # use the URL to the github repo download_url = 'https://github.com/duboviy/pybenchmark/tarball/0.0.6', # I'll explain this in a second keywords = ['benchmark', 'performance', 'testing'], # arbitrary keywords classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description=""" When measuring execution time, the result depends on the computer hardware. To be able to produce a universal measure, the simplest way is to benchmark the speed of a fixed sequence of code and calculate a ratio out of it. From there, the time taken by a function can be translated to a universal value that can be compared on any computer. Python provides a benchmark utility in its test package that measures the duration of a sequence of well-chosen operations. pybenchmark designed to provide a simple and pythonic way to get performance data. """, install_requires=[ 'psutil', 'gevent', ], )
Use multiprocessing.Pool to speed up
from requests import get from bs4 import BeautifulSoup as BS from os.path import exists from multiprocessing import Pool url = "https://www.projecteuler.net/problem=%d" def get_info(i): soup = BS(get(url % i, verify=False).content) problem = soup.find(id="content") title = problem.h2.string content = problem.find(class_="problem_content").get_text() info = title + '\n' + content info = info.encode('u8') return info def save(i): name = "%03d.py" % i # if exists(name): # print name, "exist" # return f = file(name, "w") info = get_info(i) f.write( '''\ #-*- encoding: utf-8 -*- """ %s""" from utils import * # ''' % info) f.close() print name, "saved" def save_all(i, j): p = Pool() p.map(save, range(i, j + 1)) if __name__ == '__main__': N = 10 last = int(file('last.txt').read()) save_all(last + 1, last + N) file('last.txt', 'w').write(str(last + N))
from requests import get from bs4 import BeautifulSoup as BS from os.path import exists url = "https://www.projecteuler.net/problem=%d" def get_info(i): soup = BS(get(url % i, verify=False).content) problem = soup.find(id="content") title = problem.h2.string content = problem.find(class_="problem_content").get_text() info = title + '\n' + content info = info.encode('u8') return info def save(i): name = "%03d.py" % i # if exists(name): # print name, "exist" # return f = file(name, "w") info = get_info(i) f.write( '''\ #-*- encoding: utf-8 -*- """ %s""" from utils import * # ''' % info) f.close() print name, "saved" def save_all(i, j): map(save, range(i, j + 1)) N = 10 last = int(file('last.txt').read()) save_all(last + 1, last + N) file('last.txt', 'w').write(str(last + N))
Fix state leak causing flakiness.
#!/usr/bin/env python from absl.testing import absltest from grr_response_server import cronjobs from grr_response_server.rdfvalues import cronjobs as rdf_cronjobs from grr.test_lib import test_lib from grr.test_lib import testing_startup class CronJobRegistryTest(test_lib.GRRBaseTest): @classmethod def setUpClass(cls): super(CronJobRegistryTest, cls).setUpClass() testing_startup.TestInit() # TODO: Remove once metaclass registry madness is resolved. def testCronJobRegistryInstantiation(self): # We import the `server_startup` module to ensure that all cron jobs classes # that are really used on the server are imported and populate the registry. # pylint: disable=unused-variable, g-import-not-at-top from grr_response_server import server_startup # pylint: enable=unused-variable, g-import-not-at-top for job_cls in cronjobs.CronJobRegistry.CRON_REGISTRY.values(): job = rdf_cronjobs.CronJob(cron_job_id="foobar") job_run = rdf_cronjobs.CronJobRun(cron_job_id="foobar", status="RUNNING") job_cls(job_run, job) # Should not fail. if __name__ == "__main__": absltest.main()
#!/usr/bin/env python from absl.testing import absltest from grr_response_server import cronjobs from grr_response_server import server_startup from grr_response_server.rdfvalues import cronjobs as rdf_cronjobs from grr.test_lib import test_lib from grr.test_lib import testing_startup class CronJobRegistryTest(test_lib.GRRBaseTest): @classmethod def setUpClass(cls): super(CronJobRegistryTest, cls).setUpClass() testing_startup.TestInit() with test_lib.ConfigOverrider({"Server.initialized": True}): server_startup.Init() # TODO: Remove once metaclass registry madness is resolved. def testCronJobRegistryInstantiation(self): for job_cls in cronjobs.CronJobRegistry.CRON_REGISTRY.values(): job = rdf_cronjobs.CronJob(cron_job_id="foobar") job_run = rdf_cronjobs.CronJobRun(cron_job_id="foobar", status="RUNNING") job_cls(job_run, job) # Should not fail. if __name__ == "__main__": absltest.main()
Add custom placeholder for empty value
// @flow export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { return placeholder ? '—' : ''; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
// @flow export function roundValue(value: number | string | void): number | string { if (typeof value !== 'number') { return '—'; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
Bugfix: Sort needs to be an array of arrays in the query string but a list of tuples in python.
#!/usr/bin/python import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') # Turns a JSON array of arrays to a list of tuples. sort = [tuple(field) for field in sort] if sort else None cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
#!/usr/bin/python import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
Fix case sensitivity in public key comparison
const prompt = require('prompt'); const { randomBytes } = require('crypto') const ethutil = require('ethereumjs-util'); const secp256k1 = require('secp256k1'); prompt.start(); prompt.get(['publicAddress', 'privateKey'], function (err, result) { const privateKeyBuffer = new Buffer(result.privateKey, 'hex'); const publicKeyBuffer = ethutil.privateToPublic(privateKeyBuffer); // verify private key console.log('Private key legal: ' + ethutil.isValidPrivate(privateKeyBuffer)); // verify public address console.log('Wallet address matches public address derived from private key: ' + (ethutil.bufferToHex(ethutil.pubToAddress(publicKeyBuffer)).toUpperCase() === result.publicAddress.toUpperCase())); // generate message to sign const msg = randomBytes(32); // sign the message const sigObj = secp256k1.sign(msg, privateKeyBuffer); // verify the signature console.log('Signature verified: ' + secp256k1.verify(msg, sigObj.signature, Buffer.concat([ Buffer.from([4]), publicKeyBuffer ]))); });
const prompt = require('prompt'); const { randomBytes } = require('crypto') const ethutil = require('ethereumjs-util'); const secp256k1 = require('secp256k1'); prompt.start(); prompt.get(['publicAddress', 'privateKey'], function (err, result) { const privateKeyBuffer = new Buffer(result.privateKey, 'hex'); const publicKeyBuffer = ethutil.privateToPublic(privateKeyBuffer); // verify private key console.log('Private key legal: ' + ethutil.isValidPrivate(privateKeyBuffer)); // verify public address console.log('Wallet address matches public address derived from private key: ' + (ethutil.bufferToHex(ethutil.pubToAddress(publicKeyBuffer)) === result.publicAddress)); // generate message to sign const msg = randomBytes(32); // sign the message const sigObj = secp256k1.sign(msg, privateKeyBuffer); // verify the signature console.log('Signature verified: ' + secp256k1.verify(msg, sigObj.signature, Buffer.concat([ Buffer.from([4]), publicKeyBuffer ]))); });
[FEATURE] Add the updateSession method to the UserService
angular.module('publicApp').service('UserService', ['$http','$location', function($http, $location) { var user = { isLogged: false, username: '', updateSession: function(fn){ $http.get('/api/v1/sessions').success(function(resp){ console.log('response') console.log(resp) if (resp.success && resp.session) { console.log('yes') console.log(user) user.isLogged = true user.username = resp.session.username console.log('user',user) $location.path('/gateway_account') } }) }, login: function(username, password) { $http.post('/api/v1/sessions', { name: username, password: password }).success(function(response){ if (!!response.session.username) { user.isLogged = true, user.username = username console.log('about to redirect to /gateway_account') $location.path('/gateway_account'); } else { $location.path('/admin/users/new'); } }).error(function(){ }) } } return user }])
angular.module('publicApp').service('UserService', ['$http','$location', function($http, $location) { var user = { isLogged: false, username: '', login: function(username, password) { user = this $http.post('/api/v1/sessions', { name: username, password: password }).success(function(response){ if (!!response.session.username) { this.isLogged = true, this.username = username console.log('about to redirect to /gateway_account') $location.path('/gatway_account'); } else { $location.path('/admin/users/new'); } }).error(function(){ }) } } return user }])
Update when 0 new grades
<html> <head> </head> <body> <p> Witaj,<br> </p> @if (count($data['added']) > 0) <p> Poniżej znajduja się twoje NOWE dodane do dziennika oceny.<br> @foreach($data['added'] as $grade) Data: {{ $grade->date }}<br> Ocena: {{ $grade->value }}<br> Waga: {{ $grade->weight }}<br> Przedmiot: {{ $grade->subject->name }}<br> Tytuł: {{ $grade->abbreviation }} - {{ $grade->title }}<br><br> @endforeach </p> @endif @if (count($data['deleted']) > 0) <p> Poniższe oceny zostały USUNIĘTE z dziennika: @foreach($data['deleted'] as $grade) Data: {{ $grade->date }}<br> Ocena: {{ $grade->value }}<br> Waga: {{ $grade->weight }}<br> Przedmiot: {{ $grade->subject->name }}<br> Tytuł: {{ $grade->abbreviation }} - {{ $grade->title }}<br><br> @endforeach </p> @endif @if(count($data['added']) === 0 && count($data['deleted']) === 0) <p> Brak nowych zmian. </p> @endif <p> Z poważaniem,<br> DziennikLogin </p> </body> </html>
<html> <head> </head> <body> <p> Witaj,<br> </p> @if (count($data['added']) > 0) <p> Poniżej znajduja się twoje NOWE dodane do dziennika oceny.<br> @foreach($data['added'] as $grade) Data: {{ $grade->date }}<br> Ocena: {{ $grade->value }}<br> Waga: {{ $grade->weight }}<br> Przedmiot: {{ $grade->subject->name }}<br> Tytuł: {{ $grade->abbreviation }} - {{ $grade->title }}<br><br> @endforeach </p> @endif @if (count($data['deleted']) > 0) <p> Poniższe oceny zostały USUNIĘTE z dziennika: @foreach($data['deleted'] as $grade) Data: {{ $grade->date }}<br> Ocena: {{ $grade->value }}<br> Waga: {{ $grade->weight }}<br> Przedmiot: {{ $grade->subject->name }}<br> Tytuł: {{ $grade->abbreviation }} - {{ $grade->title }}<br><br> @endforeach </p> @endif <p> Z poważaniem,<br> DziennikLogin </p> </body> </html>
Refactor node() into a closure
# -*- coding: utf-8 -*- """ eve-swagger.swagger ~~~~~~~~~~~~~~~~~~~ swagger.io extension for Eve-powered REST APIs. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from collections import OrderedDict from flask import Blueprint, jsonify from objects import info, host, base_path, schemes, consumes, produces, \ definitions, parameters, responses, security_definitions, security, \ tags, external_docs from paths import paths swagger = Blueprint('eve_swagger', __name__) @swagger.route('/api-docs') def index(): def node(parent, key, value): if value: parent[key] = value root = OrderedDict() root['swagger'] = '2.0' node(root, 'info', info()) node(root, 'host', host()) node(root, 'basePath', base_path()) node(root, 'schemes', schemes()) node(root, 'consumes', consumes()) node(root, 'produces', produces()) node(root, 'paths', paths()) node(root, 'definitions', definitions()) node(root, 'parameters', parameters()) node(root, 'responses', responses()) node(root, 'securityDefinitions', security_definitions()) node(root, 'security', security()) node(root, 'tags', tags()) node(root, 'externalDocs', external_docs()) return jsonify(root)
# -*- coding: utf-8 -*- """ eve-swagger.swagger ~~~~~~~~~~~~~~~~~~~ swagger.io extension for Eve-powered REST APIs. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from collections import OrderedDict from flask import Blueprint, jsonify from objects import info, host, base_path, schemes, consumes, produces, \ definitions, parameters, responses, security_definitions, security, \ tags, external_docs from paths import paths swagger = Blueprint('eve_swagger', __name__) @swagger.route('/api-docs') def index(): root = OrderedDict() root['swagger'] = '2.0' node(root, 'info', info()) node(root, 'host', host()) node(root, 'basePath', base_path()) node(root, 'schemes', schemes()) node(root, 'consumes', consumes()) node(root, 'produces', produces()) node(root, 'paths', paths()) node(root, 'definitions', definitions()) node(root, 'parameters', parameters()) node(root, 'responses', responses()) node(root, 'securityDefinitions', security_definitions()) node(root, 'security', security()) node(root, 'tags', tags()) node(root, 'externalDocs', external_docs()) return jsonify(root) def node(parent, key, value): if value: parent[key] = value
Add alternative to browser opening on headless servers
module.exports = function () { var browser = require('openurl'); var config = require('./config'); var REDIRECT_URI = 'https://rogeriopvl.github.com/downstagram'; console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********'); console.log('\n To use downstagram you need to authorize it to access your instagram account.'); console.log('Your browser will open for you to authorize the app...'); var authURI = [ 'https://instagram.com/oauth/authorize/?', 'client_id=' + config.auth.client_id, '&redirect_uri=' + REDIRECT_URI, '&response_type=token' ].join(''); try { browser.open(authURI); } catch (e) { console.log('Could not open browser. Maybe you are on a headless server?'); console.log('Open a web browser on this URL to continue: ', authURI); } console.log('Now according to the intructions in the App page, insert your access token here:'); var stdin = process.openStdin(); stdin.on('data', function(chunk) { var token = chunk.toString().trim(); config.auth.access_token = token; config.save(config.auth); process.exit(0); }); };
module.exports = function () { var browser = require('openurl'); var config = require('./config'); var REDIRECT_URI = 'https://rogeriopvl.github.com/downstagram'; console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********'); console.log('\n To use downstagram you need to authorize it to access your instagram account.'); console.log('Your browser will open for you to authorize the app...'); var authURI = [ 'https://instagram.com/oauth/authorize/?', 'client_id=' + config.auth.client_id, '&redirect_uri=' + REDIRECT_URI, '&response_type=token' ].join(''); browser.open(authURI); console.log('Now according to the intructions in the App page, insert your access token here:'); var stdin = process.openStdin(); stdin.on('data', function(chunk) { var token = chunk.toString().trim(); config.auth.access_token = token; config.save(config.auth); process.exit(0); }); };
Allow user to read the name of the host
package se.arbetsformedlingen.venice.probe; import java.util.Objects; public class Host { private String host; Host(String host) { this.host = host; } String getName() { return host; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Host host1 = (Host) o; return Objects.equals(host, host1.host); } @Override public int hashCode() { return Objects.hash(host); } @Override public String toString() { return "Host{" + "host='" + host + '\'' + '}'; } }
package se.arbetsformedlingen.venice.probe; import java.util.Objects; public class Host { private String host; Host(String host) { this.host = host; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Host host1 = (Host) o; return Objects.equals(host, host1.host); } @Override public int hashCode() { return Objects.hash(host); } @Override public String toString() { return "Host{" + "host='" + host + '\'' + '}'; } }
Remove position resetting from fork after upstream clone solution
package testdb import ( "database/sql/driver" "io" ) type rows struct { closed bool columns []string rows [][]driver.Value pos int } func (rs *rows) clone() *rows { if rs == nil { return nil } return &rows{closed: false, columns: rs.columns, rows: rs.rows, pos: 0} } func (rs *rows) Next(dest []driver.Value) error { rs.pos++ if rs.pos > len(rs.rows) { rs.closed = true return io.EOF // per interface spec } for i, col := range rs.rows[rs.pos-1] { dest[i] = col } return nil } func (rs *rows) Err() error { return nil } func (rs *rows) Columns() []string { return rs.columns } func (rs *rows) Close() error { return nil }
package testdb import ( "database/sql/driver" "io" ) type rows struct { closed bool columns []string rows [][]driver.Value pos int } func (rs *rows) clone() *rows { if rs == nil { return nil } return &rows{closed: false, columns: rs.columns, rows: rs.rows, pos: 0} } func (rs *rows) Next(dest []driver.Value) error { rs.pos++ if rs.pos > len(rs.rows) { rs.closed = true rs.pos = 0 return io.EOF // per interface spec } for i, col := range rs.rows[rs.pos-1] { dest[i] = col } return nil } func (rs *rows) Err() error { return nil } func (rs *rows) Columns() []string { return rs.columns } func (rs *rows) Close() error { return nil }
Make the translate entity abstract
<?php namespace ContentTranslator\Entity; abstract class Translate { protected $lang; protected $db; public function __construct() { global $wpdb; $this->db = $wpdb; $this->lang = \ContentTranslator\Switcher::$currentLanguage->code; } /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangualOption($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangualOption($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } }
<?php namespace ContentTranslator\Entity; class Translate { protected $lang; protected $db; public function __construct() { global $wpdb; $this->db = $wpdb; $this->lang = \ContentTranslator\Switcher::$currentLanguage->code; } /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangualOption($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangualOption($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } }
Add jp command line interface
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages setup( name='jmespath', version='0.0.2', description='JSON Matching Expressions', long_description=open('README.rst').read(), author='James Saryerwinnie', author_email='js@jamesls.com', url='https://github.com/boto/jmespath', scripts=['bin/jp'], packages=find_packages(), install_requires=[ 'ply==3.4', ], classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ), )
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages setup( name='jmespath', version='0.0.2', description='JSON Matching Expressions', long_description=open('README.rst').read(), author='James Saryerwinnie', author_email='js@jamesls.com', url='https://github.com/boto/jmespath', scripts=[], packages=find_packages(), install_requires=[ 'ply==3.4', ], classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ), )
Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os from ava.util import time_uuid, base_path, defines, misc class TestTimeUUID(object): def test_uuids_should_be_in_alaphabetical_order(self): old = time_uuid.oid() for i in range(100): t = time_uuid.oid() assert t > old old = t def test_base_path_should_contain_pod_folder(): basedir = base_path() source_pod_folder = os.path.join(basedir, defines.POD_FOLDER_NAME) assert os.path.exists(source_pod_folder) assert os.path.isdir(source_pod_folder) def test_is_frizon_should_return_false(): assert not misc.is_frozen() def test_get_app_dir(): app_dir = misc.get_app_dir('TestApp') assert 'TestApp'.lower() in app_dir.lower() def test_get_app_dir_via_env(): os.environ.setdefault('AVA_POD', '/test/folder') app_dir = misc.get_app_dir() assert app_dir == '/test/folder'
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os from ava.util import time_uuid, base_path, defines, misc class TestTimeUUID(object): def test_uuids_should_be_in_alaphabetical_order(self): old = time_uuid.oid() for i in range(100): t = time_uuid.oid() assert t > old old = t def test_base_path_should_contain_pod_folder(): basedir = base_path() source_pod_folder = os.path.join(basedir, defines.POD_FOLDER_NAME) assert os.path.exists(source_pod_folder) assert os.path.isdir(source_pod_folder) def test_is_frizon_should_return_false(): assert not misc.is_frozen() def test_get_app_dir(): app_dir = misc.get_app_dir('TestApp') assert 'TestApp' in app_dir def test_get_app_dir_via_env(): os.environ.setdefault('AVA_POD', '/test/folder') app_dir = misc.get_app_dir() assert app_dir == '/test/folder'
Remove created file after unit test
package com.github.hypfvieh.util; import java.io.File; import org.junit.Test; import com.github.hypfvieh.AbstractBaseUtilTest; public class CompressionUtilTest extends AbstractBaseUtilTest { @Test public void testGzipCompressUncompress() { System.out.println("GzipCompressUncompress"); File compressedGzip = CompressionUtil.compressFileGzip("src/test/resources/CompressionUtilTest/FileToCompress.txt", SystemUtil.concatFilePath(SystemUtil.getTempDir(), "SampleCompress.gz")); assertFileExists(compressedGzip); File extractedGzip = CompressionUtil.extractFileGzip(compressedGzip.getAbsolutePath(), SystemUtil.concatFilePath(SystemUtil.getTempDir(), "SampleUncompressCompress.txt")); assertFileExists(extractedGzip); String content = FileIoUtil.readFileToString(extractedGzip); assertContains(content, "compressed by a unit test"); extractedGzip.delete(); // remove no longer needed file } }
package com.github.hypfvieh.util; import java.io.File; import org.junit.Test; import com.github.hypfvieh.AbstractBaseUtilTest; public class CompressionUtilTest extends AbstractBaseUtilTest { @Test public void testGzipCompressUncompress() { System.out.println("GzipCompressUncompress"); File compressedGzip = CompressionUtil.compressFileGzip("src/test/resources/CompressionUtilTest/FileToCompress.txt", SystemUtil.concatFilePath(SystemUtil.getTempDir(), "SampleCompress.gz")); assertFileExists(compressedGzip); File extractedGzip = CompressionUtil.extractFileGzip(compressedGzip.getAbsolutePath(), SystemUtil.concatFilePath(SystemUtil.getTempDir(), "SampleUncompressCompress.txt")); assertFileExists(extractedGzip); String content = FileIoUtil.readFileToString(extractedGzip); assertContains(content, "compressed by a unit test"); } }
Set created by ID only if resolved
<?php /* * This file is part of the Active Collab DatabaseStructure project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\DatabaseStructure\Behaviour\CreatedByInterface; /** * @package ActiveCollab\DatabaseStructure\Behaviour\CreatedByInterface */ trait Implementation { public function ActiveCollabDatabaseStructureBehaviourCreatedByInterfaceImplementation() { $this->registerEventHandler('on_before_save', function () { if (empty($this->getFieldValue('created_by_id'))) { $resolve_created_by_id = $this->resolveCreatedById(); if ($resolve_created_by_id) { $this->setFieldValue('created_by_id', $this->resolveCreatedById()); } } }); } /** * Register an internal event handler. * * @param string $event * @param callable $handler */ abstract protected function registerEventHandler($event, callable $handler); abstract public function getFieldValue($field, $default = null); abstract public function &setFieldValue($field, $value); abstract protected function resolveCreatedById(): ?int; }
<?php /* * This file is part of the Active Collab DatabaseStructure project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\DatabaseStructure\Behaviour\CreatedByInterface; /** * @package ActiveCollab\DatabaseStructure\Behaviour\CreatedByInterface */ trait Implementation { public function ActiveCollabDatabaseStructureBehaviourCreatedByInterfaceImplementation() { $this->registerEventHandler('on_before_save', function () { if (empty($this->getFieldValue('created_by_id'))) { $this->setFieldValue('created_by_id', $this->resolveCreatedById()); } }); } /** * Register an internal event handler. * * @param string $event * @param callable $handler */ abstract protected function registerEventHandler($event, callable $handler); abstract public function getFieldValue($field, $default = null); abstract public function &setFieldValue($field, $value); abstract protected function resolveCreatedById(): ?int; }
Remove strike from wysiwyg tool bar
CKEDITOR.editorConfig = function (config) { config.filebrowserImageBrowseLinkUrl = '/ckeditor/pictures'; config.filebrowserImageBrowseUrl = '/ckeditor/pictures'; config.filebrowserImageUploadUrl = '/ckeditor/pictures'; config.toolbar = [ { name: 'styles', items: ['Format'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['Image'] } ]; };
CKEDITOR.editorConfig = function (config) { config.filebrowserImageBrowseLinkUrl = '/ckeditor/pictures'; config.filebrowserImageBrowseUrl = '/ckeditor/pictures'; config.filebrowserImageUploadUrl = '/ckeditor/pictures'; config.toolbar = [ { name: 'styles', items: ['Format'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['Image'] } ]; };
Fix routes, add new ones
var Cosimg = require('../models/cosimg'); var express = require('express'); var router = express.Router(); //retrieve all router.route('/cosimgs').get(function (req, res) { Cosimg.find({}).exec(function (err, data) { if(err) { return res.send(err); } res.json(data); }); }); //add new router.route('/cosimgs').post(function (req, res) { var cosimg = new Cosimg(req.body); cosimg.save(function (err) { if(err) { return res.send(err); } res.json({message: 'New cosimg added'}); }); }); //retrieve by id router.route('/cosimgs/:id').get(function (req, res) { Cosimg.findOne({ _id: req.params.id }, function (err, cosimg) { if(err) { return res.send(err); } res.json(cosimg); }); }); //deleting movie by id router.route('/cosimgs/:id').delete( function (req, res) { Cosimg.remove({_id: req.params.id}, function (err) { if(err) { return res.send(err); } res.json({ message: 'Cosimg deleted'}); }); }); module.exports = router;
var Cosimg = require('../models/cosimg'); var express = require('express'); var router = express.Router(); //retrieve all router.route('/cosimg').get(function (req, res) { Cosimg.find({}).exec(function (err, data) { if(err) { return res.send(err); } res.json(data); }); }); //add new router.route('/cosimg').post(function (req, res) { var movie = new Cosimg(req.body); movie.save(function (err) { if(err) { return res.send(err); } res.json({message: 'New cosimg added'}); }); }); //retrieve by id router.route('/cosimg/:id').get(function (req, res) { Cosimg.findOne({ _id: req.params.id }, function (err, movie) { if(err) { return res.send(err); } res.json(movie); }); }); module.exports = router;
Element: Remove the ‘isNestedObject’ helper, no longer used.
import TYPES from 'types'; function isMember(element) { if (element.element) { return element.element === TYPES.MEMBER; } return element === TYPES.MEMBER; } function getValueType({element, content}) { if (isMember(element)) { return content.value.element; } return element; } function getType(element) { if (isMember(element.element)) { return getValueType(element); } return element.element; } function isObject(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.OBJECT; } return element === TYPES.OBJECT; } function isArray(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ARRAY; } function isEnum(element) { if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ENUM; } function isObjectOrArray(element) { return isObject(element) || isArray(element); } function hasSamples(element) { const attributes = element.attributes; let samples = null; if (attributes) { return !!attributes.samples; } else { return false; } } } export { getValueType, getType, isMember, isEnum, isObject, isArray, isObjectOrArray, hasSamples, };
import TYPES from 'types'; function isMember(element) { if (element.element) { return element.element === TYPES.MEMBER; } return element === TYPES.MEMBER; } function getValueType({element, content}) { if (isMember(element)) { return content.value.element; } return element; } function getType(element) { if (isMember(element.element)) { return getValueType(element); } return element.element; } function isObject(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.OBJECT; } return element === TYPES.OBJECT; } function isArray(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ARRAY; } function isEnum(element) { if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ENUM; } function isNestedObject(element) { return isObject(element) || isArray(element) || isEnum(element); function hasSamples(element) { const attributes = element.attributes; let samples = null; if (attributes) { return !!attributes.samples; } else { return false; } } } export { getValueType, getType, isMember, isEnum, isObject, isArray, isNestedObject, hasSamples, };
Change DoubleShot to use a boolean
package edu.stuy.starlorn.upgrades; public class DoubleShotUpgrade extends GunUpgrade { private boolean _shotNum; public DoubleShotUpgrade() { super(); _shotNum = false; } @Override public int getNumShots() { return 2; } @Override public double getAimAngle() { int direction = 0; if (_shotNum) { _shotNum = !_shotNum; direction = 1; } else if (!_shotNum) { _shotNum = !_shotNum; direction = -1; } return direction * Math.PI/8; } }
package edu.stuy.starlorn.upgrades; public class DoubleShotUpgrade extends GunUpgrade { private int _shotNum; public DoubleShotUpgrade() { super(); _shotNum = 0; } @Override public int getNumShots() { return 2; } @Override public double getAimAngle() { if (_shotNum == 0) { _shotNum++; return Math.PI/8; } else if (_shotNum == 1) { _shotNum--; return -Math.PI/8; } else { // If those failed, something weird is going on, reset and aim straight. _shotNum = 0; return 0; } } }
Handle that we could use the object version of Boolean and it could be null
/* * Copyright (c) 2015. Troels Liebe Bentsen <tlb@nversion.dk> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from(value != null ? ((boolean)value ? 1 : 0) : null, length, decimals, addPadding); } }
/* * Copyright (c) 2015. Troels Liebe Bentsen <tlb@nversion.dk> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from((boolean)value ? 1 : 0, length, decimals, addPadding); } }
Add condition for testing env
<?php namespace Xetaravel\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; use Xetaravel\Models\Session; use Xetaravel\Models\Repositories\SessionRepository; class SessionLogs { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->user() || App::environment() == 'testing') { return $next($request); } $session = Session::where('id', $request->session()->getId())->first(); $data = [ 'url' => $request->path(), 'method' => $request->method() ]; SessionRepository::update($data, $session); return $next($request); } }
<?php namespace Xetaravel\Http\Middleware; use Closure; use Xetaravel\Models\Session; use Xetaravel\Models\Repositories\SessionRepository; class SessionLogs { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->user()) { return $next($request); } $session = Session::where('id', $request->session()->getId())->first(); $data = [ 'url' => $request->path(), 'method' => $request->method() ]; SessionRepository::update($data, $session); return $next($request); } }
Fix a typo in STEAMDIR
from command.default import ManagerDefaultController from cement.core.controller import expose from util.config import Configuration import os import sys class SetupController(ManagerDefaultController): class Meta: label = 'setup' description = 'Allows to set directories for SteamCMD and Quake Live' arguments = [ (['--steamcmd'], dict(help='Sets location of steamcmd', dest='STEAMDIR')), (['--ql'], dict(help='Sets location of QL Dedicated Server', dest='QLDIR')), ] @expose(hide=True) def default(self): if self.app.pargs.QLDIR is None and self.app.pargs.STEAMDIR is None: self._help() sys.exit() config = Configuration() if self.app.pargs.QLDIR is not None: config.set('directories', 'ql', os.path.expanduser(self.app.pargs.QLDIR)) if self.app.pargs.STEAMDIR is not None: config.set('directories', 'steamcmd', os.path.expanduser(self.app.pargs.STEAMDIR)) config.update()
from command.default import ManagerDefaultController from cement.core.controller import expose from util.config import Configuration import os import sys class SetupController(ManagerDefaultController): class Meta: label = 'setup' description = 'Allows to set directories for SteamCMD and Quake Live' arguments = [ (['--steamcmd'], dict(help='Sets location of steamcmd', dest='STEAMDIR')), (['--ql'], dict(help='Sets location of QL Dedicated Server', dest='QLDIR')), ] @expose(hide=True) def default(self): if self.app.pargs.QLDIR is None and self.app.pargs.STEAMDIR is None: self._help() sys.exit() config = Configuration() if self.app.pargs.QLDIR is not None: config.set('directories', 'ql', os.path.expanduser(self.app.pargs.QLDIR)) if self.app.pargs.STEAMDIR is not None: config.set('directories', 'steamcmd', os.path.expanduser(self.app.pargs.STEAMCMD)) config.update()
Set cron ranges to match real arrangement times
const RoundpiecesBot = require('./../src/roundpiecesbot'); const token = process.env.ROUNDPIECES_API_KEY; const adminUserName = process.env.ROUNDPIECES_ADMIN_USERNAME; const listPath = process.env.ROUNDPIECES_LIST_PATH; const startSearch = '00 00 9 * * 4'; // 09.00 Thursdays const endSearch = '00 00 12 * * 4'; // 12.00 Thursdays const resetSearch = '00 00 9 * * 5'; // 09.00 Fridays if (token && adminUserName && listPath) { const roundpiecesBot = new RoundpiecesBot({ token: token, name: 'Roundpieces Administration Bot', adminUserName: adminUserName, listPath: listPath, cronRanges: { start: startSearch, end: endSearch, reset: resetSearch } }); roundpiecesBot.run(); } else { console.error(`Environment is not properly configured. Please make sure you have set\n ROUNDPIECES_API_KEY to the slack bot API token ROUNDPIECES_ADMIN_USERNAME to the slack username of your roundpieces administrator ROUNDPIECES_LIST_PATH to the absolute path to your list of participants`); }
const RoundpiecesBot = require('./../src/roundpiecesbot'); const token = process.env.ROUNDPIECES_API_KEY; const adminUserName = process.env.ROUNDPIECES_ADMIN_USERNAME; const listPath = process.env.ROUNDPIECES_LIST_PATH; const startSearch = '00 * * * * *'; const endSearch = '30 * * * * *'; const resetSearch = '55 * * * * *'; if (token && adminUserName && listPath) { const roundpiecesBot = new RoundpiecesBot({ token: token, name: 'Roundpieces Administration Bot', adminUserName: adminUserName, listPath: listPath, cronRanges: { start: startSearch, end: endSearch, reset: resetSearch } }); roundpiecesBot.run(); } else { console.error(`Environment is not properly configured. Please make sure you have set\n ROUNDPIECES_API_KEY to the slack bot API token ROUNDPIECES_ADMIN_USERNAME to the slack username of your roundpieces administrator ROUNDPIECES_LIST_PATH to the absolute path to your list of participants`); }
Use real invoker by default
package uk.org.mygrid.cagrid.servicewrapper.service.ncbiblast.invoker; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.InvokerException; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.DummyNCBIBlastInvoker; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.NCBIBlastInvoker; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.NCBIBlastInvokerImpl; public class InvokerFactory { private static NCBIBlastInvoker invoker; public static NCBIBlastInvoker getInvoker() { if (invoker == null) { synchronized (InvokerFactory.class) { if (invoker == null) { // invoker = new DummyNCBIBlastInvoker(); try { invoker = new NCBIBlastInvokerImpl(); } catch (InvokerException e) { throw new RuntimeException("Can't instantiate NCBIBlast invoker", e); } } } } return invoker; } }
package uk.org.mygrid.cagrid.servicewrapper.service.ncbiblast.invoker; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.InvokerException; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.NCBIBlastInvoker; import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.NCBIBlastInvokerImpl; public class InvokerFactory { private static NCBIBlastInvoker invoker; public static NCBIBlastInvoker getInvoker() { if (invoker == null) { synchronized (InvokerFactory.class) { if (invoker == null) { //invoker = new DummyNCBIBlastInvoker(); try { invoker = new NCBIBlastInvokerImpl(); } catch (InvokerException e) { throw new RuntimeException("Can't instantiate NCBIBlast invoker", e); } } } } return invoker; } }
Use lodash-node instead of grunt.util._ Because grunt.util._ is deprecated. (cf. http://gruntjs.com/api/grunt.util#grunt.util._)
var path = require('path'); var _ = require('lodash-node/modern/objects'); require('js-yaml'); module.exports = function(grunt, options) { var cwd = process.cwd(); var defaults = { configPath: path.join(cwd, 'grunt'), init: true }; options = _.extend({}, defaults, options); var glob = require('glob'); var object = {}; var key; var aliases; glob.sync('*.{js,yml,yaml,coffee}', {cwd: options.configPath}).forEach(function(option) { key = option.replace(/\.(js|yml|yaml|coffee)$/,''); var fullPath = path.join(options.configPath, option); var settings = require(fullPath); if (key == 'aliases') { aliases = settings; } else { object[key] = _.isFunction(settings) ? settings(grunt) : settings; } }); object.package = grunt.file.readJSON(path.join(cwd, 'package.json')); if (options.config) { _.merge(object, options.config); } if (options.loadGruntTasks !== false) { var loadTasksOptions = options.loadGruntTasks || {}; require('load-grunt-tasks')(grunt, loadTasksOptions); } if (options.init) { grunt.initConfig(object); } if (aliases) { for (var taskName in aliases) { grunt.registerTask(taskName, aliases[taskName]); } } return object; };
var path = require('path'); require('js-yaml'); module.exports = function(grunt, options) { var cwd = process.cwd(); var defaults = { configPath: path.join(cwd, 'grunt'), init: true }; options = grunt.util._.extend({}, defaults, options); var glob = require('glob'); var object = {}; var key; var aliases; glob.sync('*.{js,yml,yaml,coffee}', {cwd: options.configPath}).forEach(function(option) { key = option.replace(/\.(js|yml|yaml|coffee)$/,''); var fullPath = path.join(options.configPath, option); var settings = require(fullPath); if (key == 'aliases') { aliases = settings; } else { object[key] = grunt.util._.isFunction(settings) ? settings(grunt) : settings; } }); object.package = grunt.file.readJSON(path.join(cwd, 'package.json')); if (options.config) { grunt.util._.merge(object, options.config); } if (options.loadGruntTasks !== false) { var loadTasksOptions = options.loadGruntTasks || {}; require('load-grunt-tasks')(grunt, loadTasksOptions); } if (options.init) { grunt.initConfig(object); } if (aliases) { for (var taskName in aliases) { grunt.registerTask(taskName, aliases[taskName]); } } return object; };
Change 'language' to 'syntax', that is more precise terminology.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-json # License: MIT # """This module exports the JSON plugin linter class.""" import json from SublimeLinter.lint import Linter class JSON(Linter): """Provides an interface to json.loads().""" syntax = 'json' cmd = None regex = r'^(?P<message>.+):\s*line (?P<line>\d+) column (?P<col>\d+)' def run(self, cmd, code): """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails.""" try: json.loads(code) return '' except ValueError as err: return str(err)
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-json # License: MIT # """This module exports the JSON plugin linter class.""" import json from SublimeLinter.lint import Linter class JSON(Linter): """Provides an interface to json.loads().""" language = 'json' cmd = None regex = r'^(?P<message>.+):\s*line (?P<line>\d+) column (?P<col>\d+)' def run(self, cmd, code): """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails.""" try: json.loads(code) return '' except ValueError as err: return str(err)
Select form part accepts any type of value as option
import React from 'react' const el = React.createElement import findIndex from 'lodash/findIndex' export const selectInput = function ({ options, multiple = false, nullLabel="" }) { if (!multiple) options = [[null, nullLabel]].concat(options) return function ({ value, onChange }) { return el('select', { multiple, value: normalizeValue(value, options, multiple), onChange: (ev) => onChange(normalizeEvent(ev, options, multiple)), }, options.map((op, i) => el('option', { key: i, value: i }, op[1]))) } } export default function(arg) { let { options, multiple } = arg if (!options) { options = arg } return selectInput({ options, multiple, }) } function indexFromValue(value, options) { return findIndex(options, (option) => option[0] === value) } function valueFromIndex(index, options) { return options[index][0] } function normalizeValue(val, options, multiple) { return multiple ? normalizeMultiValue(val, options) : normalizeMonoValue(val, options) } function normalizeMultiValue(value, options) { if (value === undefined) return [] if (value === null) return [] return Array.isArray(value) ? value.map(v => indexFromValue(v, options)) : [value] } function normalizeMonoValue(value, options) { return indexFromValue((value === undefined) ? null : value, options) } function normalizeEvent(ev, options, multiple) { return multiple ? [...ev.target.selectedOptions].map(opt => valueFromIndex(opt.value, options)) : valueFromIndex(ev.target.value, options) }
import React from 'react' const el = React.createElement export const selectInput = function ({ options, multiple = false, nullLabel="" }) { if (!multiple) options = [['$null', nullLabel]].concat(options) return function ({ value, onChange }) { return el('select', { multiple, value: normalizeValue(value, multiple), onChange: (ev) => onChange(normalizeEvent(ev, multiple)), }, options.map(op => el('option', {key: op[0], value: op[0]}, op[1]))) } } export default function(arg) { let { options, multiple } = arg if (!options) { options = arg } return selectInput({ options, multiple, }) } function normalizeValue(val, multiple) { return multiple ? normalizeMultiValue(val) : normalizeMonoValue(val) } function normalizeMultiValue(value) { if (value === undefined) return [] if (value === null) return [] return Array.isArray(value) ? value: [value] } function normalizeMonoValue(value) { return (value === undefined) ? '$null' : value } function normalizeEvent(ev, multiple) { return multiple ? [...ev.target.selectedOptions].map(opt => opt.value) : ev.target.value === '$null' ? null : ev.target.value }
Add back base per review
'use strict'; /** * Provides new tab and tabview widgets with some additional functions for * jujugui. * * @namespace juju * @module browser * @submodule widgets */ YUI.add('browser-tabview', function(Y) { var ns = Y.namespace('juju.widgets.browser'); /** * Tabview provides extra rendering options--it can be rendered with the * tabs horizontally rendered like Y.TabView, or vertically. * * @class Y.juju.widgets.browser.TabView * @extends {Y.TabView} */ ns.TabView = Y.Base.create('juju-browser-tabview', Y.TabView, [], { /** * Renders the DOM nodes for the widget. * * @method renderUI */ renderUI: function() { ns.TabView.superclass.renderUI.apply(this); if (this.get('vertical')) { this.get('contentBox').addClass('vertical'); } } }, { ATTRS: { /** * @attribute vertical * @default false * @type {boolean} */ vertical: { value: false } } }); }, '0.1.0', { requires: [ 'array-extras', 'base', 'tabview' ] });
'use strict'; /** * Provides new tab and tabview widgets with some additional functions for * jujugui. * * @namespace juju * @module browser * @submodule widgets */ YUI.add('browser-tabview', function(Y) { var ns = Y.namespace('juju.widgets.browser'); /** * Tabview provides extra rendering options--it can be rendered with the * tabs horizontally rendered like Y.TabView, or vertically. * * @class Y.juju.widgets.browser.TabView * @extends {Y.TabView} */ ns.TabView = Y.Base.create('juju-browser-tabview', Y.TabView, [], { /** * Renders the DOM nodes for the widget. * * @method renderUI */ renderUI: function() { ns.TabView.superclass.renderUI.apply(this); if (this.get('vertical')) { this.get('contentBox').addClass('vertical'); } } }, { ATTRS: { /** * @attribute vertical * @default false * @type {boolean} */ vertical: { value: false } } }); }, '0.1.0', { requires: [ 'array-extras', 'tabview' ] });
Karma: Split long line to make it more readable. Signed-off-by: Jakub Novak <3db738bfafc513cdba5d3154e6b5319945461327@gmail.com>
from brutal.core.plugin import cmd, match import collections karmas = collections.Counter() @match(regex=r'^([a-zA-Z0-9_]+)((:?\+)+)$') def karma_inc(event, name, pluses, *args): if name == event.meta['nick']: return 'Not in this universe, maggot!' else: karmas[name] += len(pluses)//2 @match(regex=r'^([a-zA-Z0-9_]+)((:?\-)+)$') def karma_dec(event, name, minuses, *args): if name == event.meta['nick']: return 'Not in this universe, maggot!' else: karmas[name] -= len(minuses)//2 @cmd def karma(event): """Returns karma points for a given user.""" args = event.args if len(args) < 1: return "{0}'s karma level is: {1}".format(event.meta['nick'], karmas[event.meta['nick']]) user = event.args[0] if user not in karmas: karmas[user] = 0 return "{0}'s karma level is: {1}".format(user, karmas[user])
from brutal.core.plugin import cmd, match import collections karmas = collections.Counter() @match(regex=r'^([a-zA-Z0-9_]+)((:?\+)+)$') def karma_inc(event, name, pluses, *args): if name == event.meta['nick']: return 'Not in this universe, maggot!' else: karmas[name] += len(pluses)//2 @match(regex=r'^([a-zA-Z0-9_]+)((:?\-)+)$') def karma_dec(event, name, minuses, *args): if name == event.meta['nick']: return 'Not in this universe, maggot!' else: karmas[name] -= len(minuses)//2 @cmd def karma(event): """Returns karma points for a given user.""" args = event.args if len(args) < 1: return "{0}'s karma level is: {1}".format(event.meta['nick'], karmas[event.meta['nick']]) user = event.args[0] if user not in karmas: karmas[user] = 0 return "{0}'s karma level is: {1}".format(user, karmas[user])
Fix the case where respond time is null
/** * */ package org.opennms.dashboard.client; import com.google.gwt.user.client.ui.FlexTable; class NotificationView extends PageableTableView { private Notification[] m_notifications; NotificationView() { super(new String[] { "Node", "Service", "Sent Time", "Responder", "Response Time" }); } public void setNotifications(Notification[] notifications) { m_notifications = notifications; refresh(); } protected void setRow(FlexTable table, int row, int elementIndex) { Notification notif = m_notifications[elementIndex]; table.setText(row, 0, notif.getNodeLabel()); table.setText(row, 1, notif.getServiceName()); table.setText(row, 2, ""+notif.getSentTime()); table.setText(row, 3, notif.getResponder()); table.setText(row, 4, (notif.getRespondTime() != null) ? notif.getRespondTime().toString() : ""); table.getRowFormatter().setStyleName(row, notif.getSeverity()); } public int getElementCount() { return (m_notifications == null ? 0 : m_notifications.length); } }
/** * */ package org.opennms.dashboard.client; import com.google.gwt.user.client.ui.FlexTable; class NotificationView extends PageableTableView { private Notification[] m_notifications; NotificationView() { super(new String[] { "Node", "Service", "Sent Time", "Responder", "Response Time" }); } public void setNotifications(Notification[] notifications) { m_notifications = notifications; refresh(); } protected void setRow(FlexTable table, int row, int elementIndex) { Notification notif = m_notifications[elementIndex]; table.setText(row, 0, notif.getNodeLabel()); table.setText(row, 1, notif.getServiceName()); table.setText(row, 2, ""+notif.getSentTime()); table.setText(row, 3, notif.getResponder()); table.setText(row, 4, ""+notif.getRespondTime()); table.getRowFormatter().setStyleName(row, notif.getSeverity()); } public int getElementCount() { return (m_notifications == null ? 0 : m_notifications.length); } }
Fix 'disconnected from the document' error ref https://github.com/mervick/emojionearea/pull/240
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0] && self.lasyEmoji.eq(0).is(".lazy-emoji")) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0]) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
Fix bug where cancelWindowResize, would remove the wrong callback
jsio('import browser.events') var logger = logging.getLogger(jsio.__path); var windowResizeCallbacks = []; function handleResize() { if (!windowResizeCallbacks.length) { return; } var size = exports.getWindowSize(); for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { callback(size); } } browser.events.add(window, 'resize', handleResize); exports = { onWindowResize: function(callback) { callback(exports.getWindowSize()); windowResizeCallbacks.push(callback); }, cancelWindowResize: function(targetCallback) { for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { if (callback != targetCallback) { continue; } windowResizeCallbacks.splice(i, 1); return; } }, getWindowSize: function() { return { width: window.innerWidth, height: window.innerHeight }; }, fireResize: handleResize }
jsio('import browser.events') var logger = logging.getLogger(jsio.__path); var windowResizeCallbacks = []; function handleResize() { if (!windowResizeCallbacks.length) { return; } var size = exports.getWindowSize(); for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { callback(size); } } browser.events.add(window, 'resize', handleResize); exports = { onWindowResize: function(callback) { callback(exports.getWindowSize()); windowResizeCallbacks.push(callback); }, cancelWindowResize: function(targetCallback) { for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { if (callback == targetCallback) { continue; } windowResizeCallbacks.splice(i, 1); return; } }, getWindowSize: function() { return { width: window.innerWidth, height: window.innerHeight }; }, fireResize: handleResize }
Fix : MIT license + version update
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup root = os.path.abspath(os.path.dirname(__file__)) version = __import__('pyelevator').__version__ with open(os.path.join(root, 'README.md')) as f: README = f.read() setup( name='py-elevator', version=version, license='MIT', description = 'Python client for key/value database Elevator', long_description=README, author='Oleiade', author_email='tcrevon@gmail.com', url='http://github.com/oleiade/py-elevator', classifiers=[ 'Development Status :: 0.4', 'Environment :: Unix-like Systems', 'Programming Language :: Python', 'Operating System :: Unix-like', ], keywords='py-elevator elevator leveldb database key-value', packages=[ 'pyelevator', 'pyelevator.utils', ], package_dir={'': '.'}, install_requires=[ 'pyzmq>=2.1.11', 'msgpack-python' ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup root = os.path.abspath(os.path.dirname(__file__)) version = __import__('pyelevator').__version__ with open(os.path.join(root, 'README.md')) as f: README = f.read() setup( name='py-elevator', version=version, license='BSD', description = 'Python client for key/value database Elevator', long_description=README, author='Oleiade', author_email='tcrevon@gmail.com', url='http://github.com/oleiade/py-elevator', classifiers=[ 'Development Status :: 0.0.1', 'Environment :: Unix-like Systems', 'Programming Language :: Python', 'Operating System :: Unix-like', ], keywords='py-elevator elevator leveldb database key-value', packages=[ 'pyelevator', 'pyelevator.utils' ], package_dir={'': '.'}, install_requires=[ 'pyzmq>=2.1.11', 'msgpack-python' ], )
Update test file paths for common to point to compressed versions.
from unittest.mock import Mock, patch from django.test import TestCase from data_refinery_common import microarray CEL_FILE_HUMAN = "test-files/C30057.CEL.gz" CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz" CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz" CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz" class MicroarrayTestCase(TestCase): def test_get_platform_from_CEL(self): self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN)) self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT)) self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE)) self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
from unittest.mock import Mock, patch from django.test import TestCase from data_refinery_common import microarray CEL_FILE_HUMAN = "test-files/C30057.CEL" CEL_FILE_RAT = "test-files/SG2_u34a.CEL" CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL" CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel" class MicroarrayTestCase(TestCase): def test_get_platform_from_CEL(self): self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN)) self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT)) self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE)) self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
Revert "Should break travis integration" This reverts commit a0dc0168e103ec836e434019c34b345b51e16257.
""" WSGI config for {{ project_name }} project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") import {{ project_name }}.startup as startup startup.run() # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for {{ project_name }} project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") import project_name.startup as startup startup.run() # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
!!!TASK: Add method argument and return type hints
<?php declare(strict_types=1); namespace Neos\Flow\Persistence; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * A container for the list of allowed objects to be persisted during this request. * * @Flow\Scope("singleton") */ final class AllowedObjectsContainer extends \SplObjectStorage { /** * @var bool */ protected $checkNext = false; /** * Set the internal flag to return true for `shouldCheck()` on the next invocation. * * @param bool $checkNext */ public function checkNext(bool $checkNext = true): void { $this->checkNext = $checkNext; } /** * Returns true if allowed objects should be checked this time and resets the internal flag to false, * so the next call will return false unless `checkNext(true)` is called again. * * @return bool */ public function shouldCheck(): bool { $shouldCheck = $this->checkNext; $this->checkNext = false; return $shouldCheck; } }
<?php declare(strict_types=1); namespace Neos\Flow\Persistence; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * A container for the list of allowed objects to be persisted during this request. * * @Flow\Scope("singleton") */ final class AllowedObjectsContainer extends \SplObjectStorage { /** * @var bool */ protected $checkNext = false; /** * Set the internal flag to return true for `shouldCheck()` on the next invocation. * * @param bool $checkNext */ public function checkNext($checkNext = true) { $this->checkNext = $checkNext; } /** * Returns true if allowed objects should be checked this time and resets the internal flag to false, * so the next call will return false unless `checkNext(true)` is called again. * * @return bool */ public function shouldCheck(): bool { $shouldCheck = $this->checkNext; $this->checkNext = false; return $shouldCheck; } }
Use class, module and async
import EventEmitter from 'events' import util from 'util' import web3 from 'web3' import request from 'request' import async from 'async' class RPC extends EventEmitter { constructor (options) { super() this.url = ['http://', options.host || 'localhost', ':', options.port || 6767].join('') this.connected = false } connect () { web3.setProvider(new web3.providers.HttpProvider(this.url)) } isConnectedAsync (done) { request({ uri: this.url, form: { id: 9999999999, jsonrpc: '2.0', method: 'net_listening', params: [] } }, function (err, res, body) { if (err) { done(false) } else { done(true) } }) } watch () { var self = this async.forever(function (done) { setTimeout(function () { self.isConnectedAsync(function (connected) { if (connected !== self.connected) { self.connected = connected self.emit('connection', self.connected) } done() }) }, 1000) }) } } export default RPC
var events = require('events') var util = require('util') var web3 = require('web3') var request = require('request') var async = require('async') function RPC (options) { this.url = ['http://', options.host || 'localhost', ':', options.port || 6767].join('') this.connected = false } util.inherits(RPC, events.EventEmitter) module.exports = RPC RPC.prototype.connect = function () { web3.setProvider(new web3.providers.HttpProvider(this.url)) } RPC.prototype.isConnectedAsync = function (done) { request({ uri: this.url, form: { id: 9999999999, jsonrpc: '2.0', method: 'net_listening', params: [] } }, function (err, res, body) { if (err) { done(false) } else { done(true) } }) } RPC.prototype.watch = function () { var self = this async.forever(function (done) { setTimeout(function () { self.isConnectedAsync(function (connected) { if (connected !== self.connected) { self.connected = connected self.emit('connection', self.connected) } done() }) }, 1000) }) }
Add last event time in Redis This makes sure events are not missed if the server restarts.
""" This module defines the Castor server, that consumes the Docker events from a given host. This module can be run as a command line script or get imported by another Python script. """ import docker import redis import settings import tasks def consume(docker_client, redis_client): """ Starts consuming Docker events accoding to the already defined settings. """ print 'Start consuming events from %s' % docker_client.base_url since = redis_client.get('castor:last_event') for event in docker_client.events(decode=True, since=since): for hook in settings.HOOKS: tasks.dispatch_event.delay(event, hook) redis_client.set('castor:last_event', event['time']) if __name__ == '__main__': try: docker_client = docker.Client(**settings.SETTINGS.get('docker', {})) redis_client = redis.StrictRedis( host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB, ) consume(docker_client, redis_client) except KeyboardInterrupt: # Do not display ugly exception if stopped with Ctrl + C print '\rBye.'
""" This module defines the Castor server, that consumes the Docker events from a given host. This module can be run as a command line script or get imported by another Python script. """ import docker import tasks import settings DOCKER_SETTINGS = settings.SETTINGS.get('docker', {}) # Customize the Docker client according to settings in `settings.json` DOCKER_CLIENT = docker.Client(**DOCKER_SETTINGS) def consume(): """ Starts consuming Docker events accoding to the already defined settings. """ print 'Start consuming events from %s' % DOCKER_SETTINGS['base_url'] for event in DOCKER_CLIENT.events(decode=True): for hook in settings.HOOKS: tasks.dispatch_event.delay(event, hook) if __name__ == '__main__': try: consume() except KeyboardInterrupt: # Do not display ugly exception if stopped with Ctrl + C print '\rBye.'
Move resource endpoint into constructor - SAAS-250
'use strict'; (function() { angular.module('ncsaas') .service('resourcesService', ['baseServiceClass', resourcesService]); function resourcesService(baseServiceClass) { var ServiceClass = baseServiceClass.extend({ init:function() { this._super(); this.stopResource = this.operation.bind(this, 'stop'); this.startResource = this.operation.bind(this, 'start'); this.restartResource = this.operation.bind(this, 'restart'); this.endpoint = '/instances/'; }, getAvailableOperations:function(resource) { var state = resource.state.toLowerCase(); if (state === 'online') {return ['stop', 'restart'];} if (state === 'offline') {return ['start', 'delete'];} return []; } }); return new ServiceClass(); } })();
'use strict'; (function() { angular.module('ncsaas') .service('resourcesService', ['baseServiceClass', resourcesService]); function resourcesService(baseServiceClass) { var ServiceClass = baseServiceClass.extend({ init:function() { this._super(); this.stopResource = this.operation.bind(this, 'stop'); this.startResource = this.operation.bind(this, 'start'); this.restartResource = this.operation.bind(this, 'restart'); }, getAvailableOperations:function(resource) { var state = resource.state.toLowerCase(); if (state === 'online') {return ['stop', 'restart'];} if (state === 'offline') {return ['start', 'delete'];} return []; }, getEndpoint:function(isList) { return '/instances/'; } }); return new ServiceClass(); } })();
Fix unit tests for Header component
import React from "react"; import Header from "../Header"; import { shallow } from "enzyme"; describe('Header', () => { let wrapper; it('should have only title', () => { const props = { name: 'name' }; wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); }); it('should have only header info', () => { const props = { headerInfo: <Header/>//TODO mockElement }; wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); }); it('should have both name and header info', () => { const props = { name: 'name', headerInfo: <Header/>//TODO mockElement }; console.log(wrapper.find('.breadcrumbs__item').length); wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(2); }); });
jest.unmock('../Header'); import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { Header } from '../Header'; xdescribe('Header', () => { it('should have title', () => { const container = <Header name="test title" />; const DOM = TestUtils.renderIntoDocument(container); const title = TestUtils.findRenderedDOMComponentWithTag( DOM, 'h1'); expect(title.textContent).toEqual('test title'); }); it('should have only one h1', () => { const container = <Header name="title" />; const DOM = TestUtils.renderIntoDocument(container); const title = TestUtils.scryRenderedDOMComponentsWithTag( DOM, 'h1'); expect(title.length).toEqual(1); }); });
Send correct number to highlight and select functions
var atlas = {}; function initMap() { atlas = L.map('atlas').setView([40, -100], 4); L.tileLayer('//stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png').addTo(atlas); } function buildMap() { console.log(data.maps); _.each(data.maps, function(map) { var options = { className: 'atlas--map-area', fill: false }; var rect = L.rectangle([ [map.bottom, map.left], [map.top, map.right] ]).toGeoJSON(); rect.properties = { number: parseInt(map.number) } L.geoJson(rect, { style: function(f) { return { fill: false, className: 'atlas--map-area' } }, onEachFeature: function(f, l) { l.on({ click: function() { $(document).trigger('select:', f.properties.number) }, mouseover: function() { $(document).trigger('highlight:', f.properties.number) } }); } }).addTo(atlas); }); }
var atlas = {}; function initMap() { atlas = L.map('atlas').setView([40, -100], 4); L.tileLayer('//stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png').addTo(atlas); } function buildMap() { console.log(data.maps); _.each(data.maps, function(map) { var options = { className: 'atlas--map-area', fill: false }; var rect = L.rectangle([ [map.bottom, map.left], [map.top, map.right] ]).toGeoJSON(); L.geoJson(rect, { style: function(f) { return { fill: false, className: 'atlas--map-area' } }, onEachFeature: function(f, l) { l.on({ click: function() { $(document).trigger('select:', this) }, mouseover: function() { $(document).trigger('highlight:', this) } }); } }).addTo(atlas); }); }
Fix undefined error in test
var React = require('react'); var TestUtils = require('react-addons-test-utils'); var expect = require('expect'); var sdk = require('matrix-react-sdk'); var test_utils = require('../../test-utils'); var peg = require('../../../src/MatrixClientPeg.js'); var q = require('q'); describe('MatrixChat', function () { var MatrixChat; before(function() { test_utils.stubClient(); MatrixChat = sdk.getComponent('structures.MatrixChat'); }); it('gives a login panel by default', function () { peg.get().loginFlows.returns(q({flows:[]})); var res = TestUtils.renderIntoDocument( <MatrixChat config={{}}/> ); // we expect a single <Login> component TestUtils.findRenderedComponentWithType( res, sdk.getComponent('structures.login.Login')); }); });
var React = require('react'); var TestUtils = require('react-addons-test-utils'); var expect = require('expect'); var sdk = require('matrix-react-sdk'); var test_utils = require('../../test-utils'); var peg = require('../../../src/MatrixClientPeg.js'); var q = require('q'); describe('MatrixChat', function () { var MatrixChat; before(function() { test_utils.stubClient(); MatrixChat = sdk.getComponent('structures.MatrixChat'); }); it('gives a login panel by default', function () { peg.get().loginFlows.returns(q({})); var res = TestUtils.renderIntoDocument( <MatrixChat config={{}}/> ); // we expect a single <Login> component TestUtils.findRenderedComponentWithType( res, sdk.getComponent('structures.login.Login')); }); });
Move event alias mappings to their components.
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Http\Event\SwitchUserEvent; final class SecurityEvents { /** * The INTERACTIVE_LOGIN event occurs after a user has actively logged * into your website. It is important to distinguish this action from * non-interactive authentication methods, such as: * - authentication based on your session. * - authentication using a HTTP basic or HTTP digest header. * * @Event("Symfony\Component\Security\Http\Event\InteractiveLoginEvent") */ const INTERACTIVE_LOGIN = 'security.interactive_login'; /** * The SWITCH_USER event occurs before switch to another user and * before exit from an already switched user. * * @Event("Symfony\Component\Security\Http\Event\SwitchUserEvent") */ const SWITCH_USER = 'security.switch_user'; /** * Event aliases. * * These aliases can be consumed by RegisterListenersPass. */ const ALIASES = [ InteractiveLoginEvent::class => self::INTERACTIVE_LOGIN, SwitchUserEvent::class => self::SWITCH_USER, ]; }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http; final class SecurityEvents { /** * The INTERACTIVE_LOGIN event occurs after a user has actively logged * into your website. It is important to distinguish this action from * non-interactive authentication methods, such as: * - authentication based on your session. * - authentication using a HTTP basic or HTTP digest header. * * @Event("Symfony\Component\Security\Http\Event\InteractiveLoginEvent") */ const INTERACTIVE_LOGIN = 'security.interactive_login'; /** * The SWITCH_USER event occurs before switch to another user and * before exit from an already switched user. * * @Event("Symfony\Component\Security\Http\Event\SwitchUserEvent") */ const SWITCH_USER = 'security.switch_user'; }
Add return values for BackendWrap We need to return some values from the BackendWrap. It is not trivial what we are expecting here, especially from `setMultiple`. Always returning `true` should be satisfactory for now.
<?php namespace iFixit\Matryoshka; use iFixit\Matryoshka; /** * Ensures that a delete is issued before trying to update an existing key. * * This layer is useful for working with mcrouter. mcrouter provides a reliable * delete stream, but can't guarantee updates are recorded. */ class DeleteBeforeUpdate extends BackendWrap { public function set($key, $value, $expiration = 0) { $addResponse = $this->backend->add($key, $value, $expiration); if ($addResponse === false) { $this->backend->delete($key); return $this->backend->set($key, $value, $expiration); } return $addResponse; } public function setMultiple(array $values, $expiration = 0) { foreach ($values as $key => $value) { $this->set($key, $value, $expiration); } return true; } }
<?php namespace iFixit\Matryoshka; use iFixit\Matryoshka; /** * Ensures that a delete is issued before trying to update an existing key. * * This layer is useful for working with mcrouter. mcrouter provides a reliable * delete stream, but can't guarantee updates are recorded. */ class DeleteBeforeUpdate extends BackendWrap { public function set($key, $value, $expiration = 0) { if ($this->backend->add($key, $value, $expiration) === false) { $this->backend->delete($key); $this->backend->set($key, $value, $expiration); } } public function setMultiple(array $values, $expiration = 0) { foreach ($values as $key => $value) { $this->set($key, $value, $expiration); } } }